From d98f5d9723bff9903fa6df53a461dd58338d0404 Mon Sep 17 00:00:00 2001 From: Driftay Date: Sun, 15 Sep 2019 05:02:53 -0400 Subject: [PATCH] Showing Dropping Anvil Something (Ignore) --- .../java/com/massivecraft/factions/Board.java | 104 +- .../java/com/massivecraft/factions/Conf.java | 788 ++--- .../com/massivecraft/factions/FLocation.java | 386 +- .../com/massivecraft/factions/FPlayer.java | 424 +-- .../com/massivecraft/factions/FPlayers.java | 38 +- .../com/massivecraft/factions/Faction.java | 392 +-- .../com/massivecraft/factions/Factions.java | 56 +- .../massivecraft/factions/FactionsPlugin.java | 1268 +++---- .../factions/cmd/BrigadierManager.java | 120 +- .../factions/cmd/BrigadierProvider.java | 2 +- .../massivecraft/factions/cmd/CmdAHome.java | 60 +- .../massivecraft/factions/cmd/CmdAdmin.java | 120 +- .../factions/cmd/CmdAnnounce.java | 68 +- .../factions/cmd/CmdAutoHelp.java | 52 +- .../com/massivecraft/factions/cmd/CmdBan.java | 110 +- .../massivecraft/factions/cmd/CmdBanlist.java | 86 +- .../massivecraft/factions/cmd/CmdBanner.java | 185 +- .../massivecraft/factions/cmd/CmdBoom.java | 60 +- .../massivecraft/factions/cmd/CmdBypass.java | 50 +- .../massivecraft/factions/cmd/CmdChat.java | 146 +- .../massivecraft/factions/cmd/CmdChatSpy.java | 46 +- .../factions/cmd/CmdCheckpoint.java | 96 +- .../factions/cmd/CmdColeader.java | 124 +- .../massivecraft/factions/cmd/CmdConfig.java | 394 +-- .../massivecraft/factions/cmd/CmdConvert.java | 56 +- .../massivecraft/factions/cmd/CmdCoords.java | 44 +- .../massivecraft/factions/cmd/CmdCreate.java | 148 +- .../factions/cmd/CmdDeinvite.java | 108 +- .../factions/cmd/CmdDelFWarp.java | 62 +- .../factions/cmd/CmdDescription.java | 70 +- .../massivecraft/factions/cmd/CmdDisband.java | 130 +- .../massivecraft/factions/cmd/CmdFGlobal.java | 50 +- .../massivecraft/factions/cmd/CmdFWarp.java | 102 +- .../com/massivecraft/factions/cmd/CmdFly.java | 316 +- .../massivecraft/factions/cmd/CmdFocus.java | 70 +- .../factions/cmd/CmdGetVault.java | 96 +- .../massivecraft/factions/cmd/CmdHelp.java | 350 +- .../massivecraft/factions/cmd/CmdHome.java | 188 +- .../massivecraft/factions/cmd/CmdInspect.java | 46 +- .../factions/cmd/CmdInventorySee.java | 72 +- .../massivecraft/factions/cmd/CmdInvite.java | 108 +- .../massivecraft/factions/cmd/CmdJoin.java | 204 +- .../massivecraft/factions/cmd/CmdKick.java | 190 +- .../factions/cmd/CmdKillHolograms.java | 34 +- .../massivecraft/factions/cmd/CmdLeave.java | 32 +- .../massivecraft/factions/cmd/CmdList.java | 164 +- .../massivecraft/factions/cmd/CmdLock.java | 36 +- .../massivecraft/factions/cmd/CmdLogins.java | 42 +- .../factions/cmd/CmdLowPower.java | 46 +- .../com/massivecraft/factions/cmd/CmdMap.java | 86 +- .../factions/cmd/CmdMapHeight.java | 46 +- .../com/massivecraft/factions/cmd/CmdMod.java | 116 +- .../factions/cmd/CmdModifyPower.java | 56 +- .../massivecraft/factions/cmd/CmdNear.java | 66 +- .../massivecraft/factions/cmd/CmdOpen.java | 62 +- .../massivecraft/factions/cmd/CmdOwner.java | 142 +- .../factions/cmd/CmdOwnerList.java | 84 +- .../factions/cmd/CmdPaypalSee.java | 80 +- .../factions/cmd/CmdPaypalSet.java | 92 +- .../factions/cmd/CmdPeaceful.java | 70 +- .../massivecraft/factions/cmd/CmdPerm.java | 158 +- .../factions/cmd/CmdPermanent.java | 72 +- .../factions/cmd/CmdPermanentPower.java | 70 +- .../massivecraft/factions/cmd/CmdPower.java | 58 +- .../factions/cmd/CmdPowerBoost.java | 122 +- .../massivecraft/factions/cmd/CmdReload.java | 44 +- .../massivecraft/factions/cmd/CmdRules.java | 134 +- .../com/massivecraft/factions/cmd/CmdSB.java | 46 +- .../massivecraft/factions/cmd/CmdSaveAll.java | 40 +- .../factions/cmd/CmdSeeChunk.java | 198 +- .../factions/cmd/CmdSetBanner.java | 40 +- .../factions/cmd/CmdSetDefaultRole.java | 60 +- .../factions/cmd/CmdSetFWarp.java | 90 +- .../factions/cmd/CmdSetMaxVaults.java | 54 +- .../massivecraft/factions/cmd/CmdSethome.java | 82 +- .../massivecraft/factions/cmd/CmdShow.java | 160 +- .../factions/cmd/CmdShowClaims.java | 72 +- .../factions/cmd/CmdShowInvites.java | 44 +- .../massivecraft/factions/cmd/CmdStatus.java | 48 +- .../massivecraft/factions/cmd/CmdStealth.java | 38 +- .../massivecraft/factions/cmd/CmdStrikes.java | 48 +- .../factions/cmd/CmdStrikesGive.java | 44 +- .../factions/cmd/CmdStrikesInfo.java | 44 +- .../factions/cmd/CmdStrikesSet.java | 46 +- .../factions/cmd/CmdStrikesTake.java | 46 +- .../massivecraft/factions/cmd/CmdStuck.java | 156 +- .../com/massivecraft/factions/cmd/CmdTag.java | 114 +- .../massivecraft/factions/cmd/CmdTitle.java | 50 +- .../factions/cmd/CmdToggleAllianceChat.java | 48 +- .../com/massivecraft/factions/cmd/CmdTop.java | 286 +- .../factions/cmd/CmdTpBanner.java | 54 +- .../massivecraft/factions/cmd/CmdUnban.java | 72 +- .../factions/cmd/CmdUpgrades.java | 42 +- .../massivecraft/factions/cmd/CmdVault.java | 88 +- .../massivecraft/factions/cmd/CmdVersion.java | 30 +- .../factions/cmd/CmdViewChest.java | 52 +- .../factions/cmd/CommandContext.java | 618 ++-- .../factions/cmd/CommandRequirements.java | 230 +- .../massivecraft/factions/cmd/FCmdRoot.java | 558 +-- .../massivecraft/factions/cmd/FCommand.java | 378 +- .../factions/cmd/alts/CmdAlts.java | 52 +- .../factions/cmd/alts/CmdAltsList.java | 64 +- .../factions/cmd/alts/CmdInviteAlt.java | 120 +- .../factions/cmd/check/CheckHistoryFrame.java | 126 +- .../cmd/check/CheckSettingsFrame.java | 166 +- .../factions/cmd/check/CheckTask.java | 154 +- .../factions/cmd/check/CmdCheck.java | 168 +- .../factions/cmd/check/CmdWeeWoo.java | 70 +- .../factions/cmd/check/WeeWooTask.java | 26 +- .../factions/cmd/chest/ChestLogsHandler.java | 184 +- .../factions/cmd/chest/CmdChest.java | 44 +- .../factions/cmd/claim/CmdAutoClaim.java | 84 +- .../factions/cmd/claim/CmdClaim.java | 120 +- .../factions/cmd/claim/CmdClaimAt.java | 54 +- .../factions/cmd/claim/CmdClaimLine.java | 118 +- .../factions/cmd/claim/CmdCorner.java | 86 +- .../factions/cmd/claim/CmdSafeunclaimall.java | 58 +- .../factions/cmd/claim/CmdUnclaim.java | 304 +- .../factions/cmd/claim/CmdUnclaimall.java | 114 +- .../factions/cmd/claim/CmdWarunclaimall.java | 52 +- .../cmd/configsf/CmdConvertConfig.java | 30 +- .../cmd/configsf/ConvertConfigHandler.java | 243 +- .../factions/cmd/econ/CmdMoney.java | 66 +- .../factions/cmd/econ/CmdMoneyBalance.java | 62 +- .../factions/cmd/econ/CmdMoneyDeposit.java | 52 +- .../factions/cmd/econ/CmdMoneyTransferFf.java | 56 +- .../factions/cmd/econ/CmdMoneyTransferFp.java | 54 +- .../factions/cmd/econ/CmdMoneyTransferPf.java | 54 +- .../factions/cmd/econ/CmdMoneyWithdraw.java | 64 +- .../factions/cmd/grace/CmdGrace.java | 32 +- .../factions/cmd/logout/CmdLogout.java | 42 +- .../factions/cmd/logout/LogoutHandler.java | 54 +- .../factions/cmd/points/CmdPoints.java | 52 +- .../factions/cmd/points/CmdPointsAdd.java | 64 +- .../factions/cmd/points/CmdPointsRemove.java | 60 +- .../factions/cmd/points/CmdPointsSet.java | 60 +- .../cmd/relational/CmdRelationAlly.java | 8 +- .../cmd/relational/CmdRelationEnemy.java | 8 +- .../cmd/relational/CmdRelationNeutral.java | 8 +- .../cmd/relational/CmdRelationTruce.java | 8 +- .../cmd/relational/FRelationCommand.java | 180 +- .../factions/cmd/roles/CmdDemote.java | 8 +- .../factions/cmd/roles/CmdPromote.java | 10 +- .../factions/cmd/roles/FPromoteCommand.java | 122 +- .../massivecraft/factions/cmd/tnt/CmdTnt.java | 278 +- .../factions/cmd/tnt/CmdTntFill.java | 366 +- .../event/FPlayerEnteredFactionEvent.java | 52 +- .../factions/event/FPlayerJoinEvent.java | 50 +- .../factions/event/FPlayerLeaveEvent.java | 52 +- .../event/FPlayerRoleChangeEvent.java | 56 +- .../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 | 698 ++-- .../factions/integration/Essentials.java | 64 +- .../factions/integration/Worldguard.java | 172 +- .../integration/dynmap/DynmapStyle.java | 164 +- .../integration/dynmap/EngineDynmap.java | 1286 +++---- .../integration/dynmap/TempAreaMarker.java | 170 +- .../integration/dynmap/TempMarker.java | 100 +- .../integration/dynmap/TempMarkerSet.java | 72 +- .../listeners/EssentialsHomeHandler.java | 44 +- .../listeners/FactionsBlockListener.java | 1004 +++--- .../listeners/FactionsChatListener.java | 356 +- .../listeners/FactionsEntityListener.java | 1268 +++---- .../listeners/FactionsExploitListener.java | 102 +- .../listeners/FactionsPlayerListener.java | 1857 +++++----- .../factions/missions/CmdMissions.java | 46 +- .../factions/missions/Mission.java | 38 +- .../factions/missions/MissionGUI.java | 154 +- .../factions/missions/MissionHandler.java | 164 +- .../scoreboards/BufferedObjective.java | 242 +- .../factions/scoreboards/FScoreboard.java | 216 +- .../scoreboards/FSidebarProvider.java | 44 +- .../factions/scoreboards/FTeamWrapper.java | 342 +- .../scoreboards/sidebar/FDefaultSidebar.java | 48 +- .../scoreboards/sidebar/FInfoSidebar.java | 34 +- .../massivecraft/factions/shop/CmdShop.java | 38 +- .../factions/shop/ShopClickPersistence.java | 124 +- .../factions/shop/ShopConfig.java | 76 +- .../massivecraft/factions/shop/ShopGUI.java | 128 +- .../player/PlayerChunkLocationExpression.java | 62 +- .../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 | 268 +- .../factions/struct/Placeholder.java | 24 +- .../factions/struct/Relation.java | 370 +- .../massivecraft/factions/struct/Role.java | 216 +- .../massivecraft/factions/tag/FactionTag.java | 222 +- .../massivecraft/factions/tag/FancyTag.java | 316 +- .../massivecraft/factions/tag/GeneralTag.java | 80 +- .../massivecraft/factions/tag/PlayerTag.java | 76 +- .../com/massivecraft/factions/tag/Tag.java | 120 +- .../factions/util/AsciiCompass.java | 172 +- .../factions/util/AutoLeaveProcessTask.java | 132 +- .../factions/util/AutoLeaveTask.java | 32 +- .../util/ClipPlaceholderAPIManager.java | 296 +- .../factions/util/CornerTask.java | 42 +- .../factions/util/EnumTypeAdapter.java | 86 +- .../factions/util/FactionGUI.java | 4 +- .../factions/util/FactionWarpsFrame.java | 156 +- .../factions/util/InventoryTypeAdapter.java | 22 +- .../factions/util/InventoryUtil.java | 130 +- .../factions/util/LazyLocation.java | 140 +- .../factions/util/LocationTypeAdapter.java | 60 +- .../util/MapFLocToStringSetTypeAdapter.java | 150 +- .../massivecraft/factions/util/MiscUtil.java | 176 +- .../factions/util/MyLocationTypeAdapter.java | 80 +- .../util/Particles/ParticleEffect.java | 3096 ++++++++--------- .../factions/util/Particles/Particles.java | 76 +- .../util/Particles/ReflectionUtils.java | 1150 +++--- .../util/PermissionsMapTypeAdapter.java | 150 +- .../factions/util/Placeholder.java | 24 +- .../factions/util/QuadFunction.java | 2 +- .../factions/util/RelationUtil.java | 152 +- .../factions/util/SpiralTask.java | 296 +- .../massivecraft/factions/util/UtilFly.java | 136 +- .../factions/util/VisualizeUtil.java | 94 +- .../factions/util/WarmUpUtil.java | 56 +- .../massivecraft/factions/util/XMaterial.java | 2994 ++++++++-------- .../factions/zcore/CommandVisibility.java | 6 +- .../massivecraft/factions/zcore/MCommand.java | 918 ++--- .../massivecraft/factions/zcore/MPlugin.java | 538 +-- .../zcore/MPluginSecretPlayerListener.java | 52 +- .../factions/zcore/fperms/Access.java | 66 +- .../zcore/fperms/DefaultPermissions.java | 298 +- .../factions/zcore/fperms/Permissable.java | 6 +- .../zcore/fperms/PermissableAction.java | 174 +- .../fperms/gui/PermissableActionFrame.java | 147 +- .../fperms/gui/PermissableRelationFrame.java | 105 +- .../zcore/fupgrades/CropUpgrades.java | 96 +- .../factions/zcore/fupgrades/EXPUpgrade.java | 62 +- .../zcore/fupgrades/FUpgradesGUI.java | 698 ++-- .../zcore/fupgrades/RedstoneUpgrade.java | 36 +- .../zcore/fupgrades/SpawnerUpgrades.java | 50 +- .../factions/zcore/fupgrades/UpgradeType.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 | 620 ++-- .../factions/zcore/persist/MemoryFPlayer.java | 2452 ++++++------- .../zcore/persist/MemoryFPlayers.java | 82 +- .../factions/zcore/persist/MemoryFaction.java | 2552 +++++++------- .../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 | 290 +- .../zcore/persist/json/JSONFaction.java | 16 +- .../zcore/persist/json/JSONFactions.java | 386 +- .../factions/zcore/util/DiscUtil.java | 166 +- .../factions/zcore/util/PermUtil.java | 98 +- .../factions/zcore/util/Persist.java | 210 +- .../factions/zcore/util/SmokeUtil.java | 88 +- .../massivecraft/factions/zcore/util/TL.java | 2362 ++++++------- .../factions/zcore/util/TagReplacer.java | 540 +-- .../factions/zcore/util/TagUtil.java | 520 +-- .../factions/zcore/util/TextUtil.java | 362 +- .../factions/zcore/util/UUIDFetcher.java | 140 +- 285 files changed, 28732 insertions(+), 28729 deletions(-) diff --git a/src/main/java/com/massivecraft/factions/Board.java b/src/main/java/com/massivecraft/factions/Board.java index bfd3b94d..1fa2b446 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 List 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 List 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 637d0e86..44fde5f4 100644 --- a/src/main/java/com/massivecraft/factions/Conf.java +++ b/src/main/java/com/massivecraft/factions/Conf.java @@ -13,430 +13,430 @@ 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; + // 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; - // 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; - public static int factionAltMemberLimit = 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 int factionBufferSize = 20; - public static boolean useCheckSystem = true; - public static boolean gracePeriod = false; - 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 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 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 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 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); - /// - /// This defines a set of materials which should always be allowed to use, regardless of factions permissions. - /// Useful for HCF features. - /// - public static Set territoryBypassProtectedMaterials = EnumSet.noneOf(Material.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; + public static int factionAltMemberLimit = 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 int factionBufferSize = 20; + public static boolean useCheckSystem = true; + public static boolean gracePeriod = false; + 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 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 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 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 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); + /// + /// This defines a set of materials which should always be allowed to use, regardless of factions permissions. + /// Useful for HCF features. + /// + public static Set territoryBypassProtectedMaterials = EnumSet.noneOf(Material.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; - public static double econFactionStartingBalance = 0.0; - public static double econDenyWithdrawWhenMinutesAgeLessThan = 2880; // 2 days - public static String dateFormat = "HH:mm dd/MM/yyyy"; + // 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; + public static double econFactionStartingBalance = 0.0; + public static double econDenyWithdrawWhenMinutesAgeLessThan = 2880; // 2 days + public static String dateFormat = "HH:mm dd/MM/yyyy"; - // -------------------------------------------- // - // 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 boolean useWorldConfigurationsAsWhitelist = false; - 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 boolean useWorldConfigurationsAsWhitelist = false; + 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 int defaultMaxVaults = 0; - public static boolean disableFlightOnFactionClaimChange = true; + // faction- + public static int defaultMaxVaults = 0; + public static boolean disableFlightOnFactionClaimChange = true; - 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(); - //Cooldown for /f logout in seconds - public static long logoutCooldown = 30; + //Cooldown for /f logout in seconds + public static long logoutCooldown = 30; - // Custom Ranks - Oof I forgot I was doing this _SvenjaReissaus_ - //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 - // ----------------------------------------- // + // Custom Ranks - Oof I forgot I was doing this _SvenjaReissaus_ + //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 + // ----------------------------------------- // - // Default Faction Permission Settings. - public static boolean useLockedPermissions = false; - public static boolean useCustomDefaultPermissions = true; - public static boolean usePermissionHints = false; - public static HashMap defaultFactionPermissions = new HashMap<>(); - public static HashSet lockedPermissions = new HashSet<>(); + // Default Faction Permission Settings. + public static boolean useLockedPermissions = false; + public static boolean useCustomDefaultPermissions = true; + public static boolean usePermissionHints = false; + public static HashMap defaultFactionPermissions = new HashMap<>(); + public static HashSet lockedPermissions = new HashSet<>(); - private static transient Conf i = new Conf(); + private static transient Conf i = new Conf(); - static { - lockedPermissions.add(PermissableAction.CHEST); - } + static { + lockedPermissions.add(PermissableAction.CHEST); + } - 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"); - /// TODO: Consider removing this in a future release, as permissions works just fine now - territoryProtectedMaterials.add(Material.BEACON); + /// TODO: Consider removing this in a future release, as permissions works just fine now + territoryProtectedMaterials.add(Material.BEACON); - // Config is not loading if value is empty ??? - territoryBypassProtectedMaterials.add(Material.COOKIE); + // Config is not loading if value is empty ??? + territoryBypassProtectedMaterials.add(Material.COOKIE); - territoryDenyUseageMaterials.add(XMaterial.FIRE_CHARGE.parseMaterial()); - territoryDenyUseageMaterials.add(Material.FLINT_AND_STEEL); - territoryDenyUseageMaterials.add(Material.BUCKET); - territoryDenyUseageMaterials.add(Material.WATER_BUCKET); - territoryDenyUseageMaterials.add(Material.LAVA_BUCKET); - if (!FactionsPlugin.getInstance().mc17) { - territoryDenyUseageMaterials.add(Material.ARMOR_STAND); - } + territoryDenyUseageMaterials.add(XMaterial.FIRE_CHARGE.parseMaterial()); + territoryDenyUseageMaterials.add(Material.FLINT_AND_STEEL); + territoryDenyUseageMaterials.add(Material.BUCKET); + territoryDenyUseageMaterials.add(Material.WATER_BUCKET); + territoryDenyUseageMaterials.add(Material.LAVA_BUCKET); + if (!FactionsPlugin.getInstance().mc17) { + territoryDenyUseageMaterials.add(Material.ARMOR_STAND); + } - territoryProtectedMaterialsWhenOffline.add(Material.BEACON); + territoryProtectedMaterialsWhenOffline.add(Material.BEACON); - territoryDenyUseageMaterialsWhenOffline.add(XMaterial.FIRE_CHARGE.parseMaterial()); - territoryDenyUseageMaterialsWhenOffline.add(Material.FLINT_AND_STEEL); - territoryDenyUseageMaterialsWhenOffline.add(Material.BUCKET); - territoryDenyUseageMaterialsWhenOffline.add(Material.WATER_BUCKET); - territoryDenyUseageMaterialsWhenOffline.add(Material.LAVA_BUCKET); - if (!FactionsPlugin.getInstance().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); + territoryDenyUseageMaterialsWhenOffline.add(XMaterial.FIRE_CHARGE.parseMaterial()); + territoryDenyUseageMaterialsWhenOffline.add(Material.FLINT_AND_STEEL); + territoryDenyUseageMaterialsWhenOffline.add(Material.BUCKET); + territoryDenyUseageMaterialsWhenOffline.add(Material.WATER_BUCKET); + territoryDenyUseageMaterialsWhenOffline.add(Material.LAVA_BUCKET); + if (!FactionsPlugin.getInstance().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("NORMAL MEMBER", new DefaultPermissions(false)); - defaultFactionPermissions.put("RECRUIT", new DefaultPermissions(false)); - } + // 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("NORMAL MEMBER", new DefaultPermissions(false)); + defaultFactionPermissions.put("RECRUIT", new DefaultPermissions(false)); + } - public static void load() { - FactionsPlugin.getInstance().persist.loadOrSaveDefault(i, Conf.class, "conf"); - } + public static void load() { + FactionsPlugin.getInstance().persist.loadOrSaveDefault(i, Conf.class, "conf"); + } - public static void save() { - FactionsPlugin.getInstance().persist.save(i); - } + public static void save() { + FactionsPlugin.getInstance().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 8eacaf44..8cff7080 100644 --- a/src/main/java/com/massivecraft/factions/FLocation.java +++ b/src/main/java/com/massivecraft/factions/FLocation.java @@ -12,248 +12,248 @@ import java.util.Objects; 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; + 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 || -diffZ >= lim); - } + return (diffX > lim || diffZ > lim) || (-diffX >= lim || -diffZ >= lim); + } - //----------------------------------------------// - // 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 && (Objects.equals(this.worldName, that.worldName)); - } + FLocation that = (FLocation) obj; + return this.x == that.x && this.z == that.z && (Objects.equals(this.worldName, 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 fd16466c..41a17f9f 100644 --- a/src/main/java/com/massivecraft/factions/FPlayer.java +++ b/src/main/java/com/massivecraft/factions/FPlayer.java @@ -26,368 +26,368 @@ import java.util.List; public interface FPlayer extends EconomyParticipator { - void setNotificationsEnabled(boolean notifications); + void setNotificationsEnabled(boolean notifications); - boolean hasNotificationsEnabled(); + boolean hasNotificationsEnabled(); - boolean isAlt(); + boolean isAlt(); - void setAlt(boolean alt); + void setAlt(boolean alt); - /** - * 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, boolean alt); + /** + * Sets the faction of the FPlayer + * + * @param faction faction to set. + */ + void setFaction(Faction faction, boolean alt); - /** - * 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(); - int getCooldown(String cmd); + int getCooldown(String cmd); - void setCooldown(String cmd, long cooldown); + void setCooldown(String cmd, long cooldown); - boolean isCooldownEnded(String cmd); + boolean isCooldownEnded(String cmd); - // ------------------------------- - // 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 894ab326..cbbc37a0 100644 --- a/src/main/java/com/massivecraft/factions/FPlayers.java +++ b/src/main/java/com/massivecraft/factions/FPlayers.java @@ -7,34 +7,34 @@ import org.bukkit.entity.Player; import java.util.Collection; public abstract class FPlayers { - protected static FPlayers instance = getFPlayersImpl(); + protected static FPlayers instance = getFPlayersImpl(); - public static FPlayers getInstance() { - return instance; - } + public static FPlayers getInstance() { + return instance; + } - private static FPlayers getFPlayersImpl() { - if (Conf.backEnd == Conf.Backend.JSON) { - return new JSONFPlayers(); - } - return null; - } + private static FPlayers getFPlayersImpl() { + if (Conf.backEnd == Conf.Backend.JSON) { + return new JSONFPlayers(); + } + return null; + } - public abstract void clean(); + public abstract void clean(); - public abstract Collection getOnlinePlayers(); + public abstract Collection getOnlinePlayers(); - public abstract FPlayer getByPlayer(Player player); + public abstract FPlayer getByPlayer(Player player); - public abstract Collection getAllFPlayers(); + public abstract Collection getAllFPlayers(); - public abstract void forceSave(); + public abstract void forceSave(); - public abstract void forceSave(boolean sync); + public abstract void forceSave(boolean sync); - public abstract FPlayer getByOfflinePlayer(OfflinePlayer player); + public abstract FPlayer getByOfflinePlayer(OfflinePlayer player); - public abstract FPlayer getById(String string); + public abstract FPlayer getById(String string); - public abstract void load(); + 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 497550b1..a2c72b3a 100644 --- a/src/main/java/com/massivecraft/factions/Faction.java +++ b/src/main/java/com/massivecraft/factions/Faction.java @@ -24,370 +24,370 @@ import java.util.concurrent.ConcurrentHashMap; public interface Faction extends EconomyParticipator { - int getWallCheckMinutes(); + int getWallCheckMinutes(); - void setWallCheckMinutes(int minutes); + void setWallCheckMinutes(int minutes); - int getBufferCheckMinutes(); + int getBufferCheckMinutes(); - void setBufferCheckMinutes(int minutes); + void setBufferCheckMinutes(int minutes); - Map getChecks(); + Map getChecks(); - Map getPlayerBufferCheckCount(); + Map getPlayerBufferCheckCount(); - Map getPlayerWallCheckCount(); + Map getPlayerWallCheckCount(); - boolean isWeeWoo(); + boolean isWeeWoo(); - void setWeeWoo(boolean weeWoo); + void setWeeWoo(boolean weeWoo); - boolean altInvited(FPlayer fplayer); + boolean altInvited(FPlayer fplayer); - Map getMissions(); + Map getMissions(); - void deinviteAlt(FPlayer alt); + void deinviteAlt(FPlayer alt); - void deinviteAllAlts(); + void deinviteAllAlts(); - void altInvite(FPlayer fplayer); + void altInvite(FPlayer fplayer); - boolean addAltPlayer(FPlayer fplayer); + boolean addAltPlayer(FPlayer fplayer); - boolean removeAltPlayer(FPlayer fplayer); + boolean removeAltPlayer(FPlayer fplayer); - Set getAltPlayers(); + Set getAltPlayers(); - 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(UpgradeType upgrade, int level); + void setUpgrade(UpgradeType upgrade, int level); - int getUpgrade(UpgradeType upgrade); + int getUpgrade(UpgradeType upgrade); - boolean isInvited(FPlayer fplayer); + boolean isInvited(FPlayer fplayer); - void ban(FPlayer target, FPlayer banner); + void ban(FPlayer target, FPlayer banner); - int getPoints(); + int getPoints(); - void setPoints(int points); + void setPoints(int points); - int getStrikes(); + int getStrikes(); - void setStrikes(int strikes); + void setStrikes(int strikes); - 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 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(); - boolean isSystemFaction(); + boolean isSystemFaction(); - @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); - boolean setPermission(Permissable permissable, PermissableAction permissableAction, Access access); + boolean setPermission(Permissable permissable, PermissableAction permissableAction, Access access); - void resetPerms(); + void resetPerms(); - void setDefaultPerms(); + void setDefaultPerms(); - void disband(Player disbander); + void disband(Player disbander); - void disband(Player disbander, PlayerDisbandReason reason); + void disband(Player disbander, PlayerDisbandReason reason); - // ------------------------------- - // Relation and relation colors - // ------------------------------- + // ------------------------------- + // Relation and relation colors + // ------------------------------- - Map> getPermissions(); + Map> getPermissions(); - @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); - @Override - ChatColor getColorTo(RelationParticipator rp); + @Override + ChatColor getColorTo(RelationParticipator rp); - Relation getRelationWish(Faction otherFaction); + Relation getRelationWish(Faction otherFaction); - void setRelationWish(Faction otherFaction, Relation relation); + void setRelationWish(Faction otherFaction, Relation relation); - int getRelationCount(Relation relation); + int getRelationCount(Relation relation); - // ----------------------------------------------// - // Power - // ----------------------------------------------// - double getPower(); + // ----------------------------------------------// + // Power + // ----------------------------------------------// + double getPower(); - double getPowerMax(); + double getPowerMax(); - int getPowerRounded(); + int getPowerRounded(); - int getPowerMaxRounded(); + int getPowerMaxRounded(); - int getLandRounded(); + int getLandRounded(); - int getLandRoundedInWorld(String worldName); + int getLandRoundedInWorld(String worldName); - // ------------------------------- - // FPlayers - // ------------------------------- + // ------------------------------- + // FPlayers + // ------------------------------- - boolean hasLandInflation(); + boolean hasLandInflation(); - // maintain the reference list of FPlayers in this faction - void refreshFPlayers(); + // maintain the reference list of FPlayers in this faction + void refreshFPlayers(); - boolean addFPlayer(FPlayer fplayer); + boolean addFPlayer(FPlayer fplayer); - boolean removeFPlayer(FPlayer fplayer); + boolean removeFPlayer(FPlayer fplayer); - int getSize(); + int getSize(); - Set getFPlayers(); + Set getFPlayers(); - Set getFPlayersWhereOnline(boolean online); + Set getFPlayersWhereOnline(boolean online); - Set getFPlayersWhereOnline(boolean online, FPlayer viewer); + Set getFPlayersWhereOnline(boolean online, FPlayer viewer); - FPlayer getFPlayerAdmin(); + FPlayer getFPlayerAdmin(); - FPlayer getFPlayerLeader(); + FPlayer getFPlayerLeader(); - ArrayList getFPlayersWhereRole(Role role); + ArrayList getFPlayersWhereRole(Role role); - ArrayList getOnlinePlayers(); + ArrayList getOnlinePlayers(); - // slightly faster check than getOnlinePlayers() if you just want to see if - // there are any players online - boolean hasPlayersOnline(); + // slightly faster check than getOnlinePlayers() if you just want to see if + // there are any players online + boolean hasPlayersOnline(); - void memberLoggedOff(); + void memberLoggedOff(); - // 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(); + // 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 promoteNewLeader(boolean autoLeave); + void promoteNewLeader(boolean autoLeave); - Role getDefaultRole(); + Role getDefaultRole(); - void setDefaultRole(Role role); + void setDefaultRole(Role role); - // ----------------------------------------------// - // Messages - // ----------------------------------------------// - void msg(String message, Object... args); + // ----------------------------------------------// + // Messages + // ----------------------------------------------// + void msg(String message, Object... args); - void sendMessage(String message); + void sendMessage(String message); - // ----------------------------------------------// - // Ownership of specific claims - // ----------------------------------------------// + // ----------------------------------------------// + // Ownership of specific claims + // ----------------------------------------------// - void sendMessage(List messages); + void sendMessage(List messages); - Map> getClaimOwnership(); + Map> getClaimOwnership(); - void clearAllClaimOwnership(); + void clearAllClaimOwnership(); - void clearClaimOwnership(FLocation loc); + void clearClaimOwnership(FLocation loc); - void clearClaimOwnership(FPlayer player); + void clearClaimOwnership(FPlayer player); - int getCountOfClaimsWithOwners(); + int getCountOfClaimsWithOwners(); - boolean doesLocationHaveOwnersSet(FLocation loc); + boolean doesLocationHaveOwnersSet(FLocation loc); - boolean isPlayerInOwnerList(FPlayer player, FLocation loc); + boolean isPlayerInOwnerList(FPlayer player, FLocation loc); - void setPlayerAsOwner(FPlayer player, FLocation loc); + void setPlayerAsOwner(FPlayer player, FLocation loc); - void removePlayerAsOwner(FPlayer player, FLocation loc); + void removePlayerAsOwner(FPlayer player, FLocation loc); - Set getOwnerList(FLocation loc); + Set getOwnerList(FLocation loc); - String getOwnerListString(FLocation loc); + String getOwnerListString(FLocation loc); - boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc); + boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc); - // ----------------------------------------------// - // Persistance and entity management - // ----------------------------------------------// - void remove(); + // ----------------------------------------------// + // Persistance and entity management + // ----------------------------------------------// + void remove(); - Set getAllClaims(); + Set getAllClaims(); - String getPaypal(); + String getPaypal(); - void paypalSet(String paypal); + 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 09a2c722..74c09e12 100644 --- a/src/main/java/com/massivecraft/factions/Factions.java +++ b/src/main/java/com/massivecraft/factions/Factions.java @@ -6,50 +6,50 @@ import java.util.ArrayList; import java.util.Set; public abstract class Factions { - protected static Factions instance = getFactionsImpl(); + protected static Factions instance = getFactionsImpl(); - public static Factions getInstance() { - return instance; - } + public static Factions getInstance() { + return instance; + } - private static Factions getFactionsImpl() { - switch (Conf.backEnd) { - case JSON: - return new JSONFactions(); - } - return null; - } + private static Factions getFactionsImpl() { + switch (Conf.backEnd) { + case JSON: + return new JSONFactions(); + } + return null; + } - public abstract Faction getFactionById(String id); + public abstract Faction getFactionById(String id); - public abstract Faction getByTag(String str); + public abstract Faction getByTag(String str); - public abstract Faction getBestTagMatch(String start); + public abstract Faction getBestTagMatch(String start); - public abstract boolean isTagTaken(String str); + public abstract boolean isTagTaken(String str); - public abstract boolean isValidFactionId(String id); + public abstract boolean isValidFactionId(String id); - public abstract Faction createFaction(); + public abstract Faction createFaction(); - public abstract void removeFaction(String id); + public abstract void removeFaction(String id); - public abstract Set getFactionTags(); + public abstract Set getFactionTags(); - public abstract ArrayList getAllFactions(); + public abstract ArrayList getAllFactions(); - @Deprecated - public abstract Faction getNone(); + @Deprecated + public abstract Faction getNone(); - public abstract Faction getWilderness(); + public abstract Faction getWilderness(); - public abstract Faction getSafeZone(); + public abstract Faction getSafeZone(); - public abstract Faction getWarZone(); + public abstract Faction getWarZone(); - public abstract void forceSave(); + public abstract void forceSave(); - public abstract void forceSave(boolean sync); + public abstract void forceSave(boolean sync); - public abstract void load(); + public abstract void load(); } diff --git a/src/main/java/com/massivecraft/factions/FactionsPlugin.java b/src/main/java/com/massivecraft/factions/FactionsPlugin.java index b9ad2f73..33b481af 100644 --- a/src/main/java/com/massivecraft/factions/FactionsPlugin.java +++ b/src/main/java/com/massivecraft/factions/FactionsPlugin.java @@ -58,677 +58,677 @@ import java.util.stream.Collectors; public class FactionsPlugin extends MPlugin { - // Our single plugin instance. - // Single 4 life. - public static FactionsPlugin instance; - public static Permission perms = null; - // This plugin sets the boolean true when fully enabled. - // Plugins can check this boolean while hooking in have - // a green light to use the api. - public static boolean startupFinished = false; - public static Economy econ = null; - public boolean PlaceholderApi; - // Commands - public FCmdRoot cmdBase; - public CmdAutoHelp cmdAutoHelp; - public boolean mc17 = false; - public boolean mc18 = false; - public boolean mc112 = false; - public boolean mc113 = false; - public boolean mc114 = false; - public boolean useNonPacketParticles = false; - public boolean factionsFlight = false; - SkriptAddon skriptAddon; - private FactionsPlayerListener factionsPlayerListener; - private boolean locked = false; - private boolean spam = false; - private Integer AutoLeaveTask = null; - private boolean hookedPlayervaults; - private ClipPlaceholderAPIManager clipPlaceholderAPIManager; - private boolean mvdwPlaceholderAPIManager = false; - private Listener[] eventsListener; - - - public FactionsPlugin() { - instance = this; - } - - public static FactionsPlugin getInstance() { - return instance; - } - - public boolean getLocked() { - return this.locked; - } - - public void setLocked(boolean val) { - this.locked = val; - this.setAutoSave(val); - } - - public boolean getSpam() { - return this.spam; - } - - public void setSpam(boolean val) { - this.spam = 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(instance); - return; - } - - int version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); - switch (version) { - case 7: - FactionsPlugin.instance.log("Minecraft Version 1.7 found, disabling banners, itemflags inside GUIs, and Titles."); - mc17 = true; - break; - case 8: - FactionsPlugin.instance.log("Minecraft Version 1.8 found, Title Fadeouttime etc will not be configurable."); - mc18 = true; - break; - case 12: - mc112 = true; - break; - case 13: - FactionsPlugin.instance.log("Minecraft Version 1.13 found, New Items will be used."); - mc113 = true; - break; - case 14: - FactionsPlugin.instance.log("Minecraft Version 1.14 found."); - mc114 = true; - break; - } - 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; - } - if (fPlayer.isAlt()) { - faction.addAltPlayer(fPlayer); - } else { - faction.addFPlayer(fPlayer); - } - } - - if (getConfig().getBoolean("enable-faction-flight", true)) { - UtilFly.run(); - } - - Board.getInstance().load(); - Board.getInstance().clean(); - - // Add Base Commands - this.cmdBase = new FCmdRoot(); - this.cmdAutoHelp = new CmdAutoHelp(); - - 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 (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 FactionsPlugin Addon..."); - skriptAddon = Skript.registerAddon(this); - try { - skriptAddon.loadClasses("com.massivecraft.factions.skript", "expressions"); - } catch (IOException ex) { - ex.printStackTrace(); - } - log("Skript addon registered!"); - } - if (Conf.useCheckSystem) { - int minute = 1200; - this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 3), 0L, (long) (minute * 3)); - this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 5), 0L, (long) (minute * 5)); - this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 10), 0L, (long) (minute * 10)); - this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 15), 0L, (long) (minute * 15)); - this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 30), 0L, (long) (minute * 30)); - this.getServer().getScheduler().runTaskTimer(this, CheckTask::cleanupTask, 0L, 1200L); - this.getServer().getScheduler().runTaskTimerAsynchronously(this, new WeeWooTask(this), 600L, 600L); - } - ShopConfig.setup(); - - getServer().getPluginManager().registerEvents(factionsPlayerListener = new FactionsPlayerListener(), this); - - // Register Event Handlers - eventsListener = new Listener[]{ - new FactionsChatListener(), - new FactionsEntityListener(), - new FactionsExploitListener(), - new FactionsBlockListener(), - new FUpgradesGUI(), - new EXPUpgrade(), - new CropUpgrades(), - new RedstoneUpgrade(), - new ShopClickPersistence(), - new MissionHandler(this), - new ChestLogsHandler(), - new SpawnerUpgrades() - }; - - for (Listener eventListener : eventsListener) - getServer().getPluginManager().registerEvents(eventListener, this); - - this.getCommand(refCommand).setExecutor(cmdBase); - - if (!CommodoreProvider.isSupported()) this.getCommand(refCommand).setTabCompleter(this); - - - RegisteredServiceProvider rsp = FactionsPlugin.this.getServer().getServicesManager().getRegistration(Economy.class); - FactionsPlugin.econ = rsp.getProvider(); - - 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/Driftay/Saber-Factions/issues"); - divider(); - } - - this.setupPlaceholderAPI(); - this.postEnable(); - this.loadSuccessful = true; - // Set startup finished to true. to give plugins hooking in a greenlight - FactionsPlugin.startupFinished = true; - } - - public SkriptAddon getSkriptAddon() { - return skriptAddon; - } - - - 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."); - } - } - - public List replacePlaceholders(List lore, Placeholder... placeholders) { - for (Placeholder placeholder : placeholders) { - for (int x = 0; x <= lore.size() - 1; x++) - lore.set(x, lore.get(x).replace(placeholder.getTag(), placeholder.getReplace())); - } - return lore; - } - - private void migrateFPlayerLeaders() { - List lines = new ArrayList<>(); - File fplayerFile = new File("plugins" + File.pathSeparator + "Factions" + File.pathSeparator + "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 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(XMaterial.matchXMaterial(material.toString()).parseMaterial(), 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(FactionsPlugin.instance.getConfig().getString(name))); - meta.setLore(colorList(FactionsPlugin.instance.getConfig().getStringList(lore))); - item.setItemMeta(meta); - return item; - } - - public Economy getEcon() { - RegisteredServiceProvider rsp = FactionsPlugin.instance.getServer().getServicesManager().getRegistration(Economy.class); - return rsp.getProvider(); - } - - - @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); - } - - // This method must stay for < 1.12 versions - @Override - public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { - // Must be a LinkedList to prevent UnsupportedOperationException. - List argsList = new LinkedList<>(Arrays.asList(args)); - CommandContext context = new CommandContext(sender, argsList, alias); - String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0); -// String cmdValid = (cmd + " " + TextUtil.implode(context.args, " ")).trim(); - List commandsList = cmdBase.subCommands; - FCommand commandsEx = cmdBase; - List completions = new ArrayList<>(); - - // Check for "" first arg because spigot is mangled. - if (context.args.get(0).equals("")) { - for (FCommand subCommand : commandsEx.subCommands) { - if (subCommand.requirements.playerOnly && sender.hasPermission(subCommand.requirements.permission.node) && subCommand.visibility != CommandVisibility.INVISIBLE) - completions.addAll(subCommand.aliases); - } - return completions; - } else if (context.args.size() == 1) { - for (; !commandsList.isEmpty() && !context.args.isEmpty(); context.args.remove(0)) { - String cmdName = context.args.get(0).toLowerCase(); - boolean toggle = false; - for (FCommand fCommand : commandsList) { - for (String s : fCommand.aliases) { - if (s.startsWith(cmdName)) { - commandsList = fCommand.subCommands; - completions.addAll(fCommand.aliases); - toggle = true; - break; - } + // Our single plugin instance. + // Single 4 life. + public static FactionsPlugin instance; + public static Permission perms = null; + // This plugin sets the boolean true when fully enabled. + // Plugins can check this boolean while hooking in have + // a green light to use the api. + public static boolean startupFinished = false; + public static Economy econ = null; + public boolean PlaceholderApi; + // Commands + public FCmdRoot cmdBase; + public CmdAutoHelp cmdAutoHelp; + public boolean mc17 = false; + public boolean mc18 = false; + public boolean mc112 = false; + public boolean mc113 = false; + public boolean mc114 = false; + public boolean useNonPacketParticles = false; + public boolean factionsFlight = false; + SkriptAddon skriptAddon; + private FactionsPlayerListener factionsPlayerListener; + private boolean locked = false; + private boolean spam = false; + private Integer AutoLeaveTask = null; + private boolean hookedPlayervaults; + private ClipPlaceholderAPIManager clipPlaceholderAPIManager; + private boolean mvdwPlaceholderAPIManager = false; + private Listener[] eventsListener; + + + public FactionsPlugin() { + instance = this; + } + + public static FactionsPlugin getInstance() { + return instance; + } + + public boolean getLocked() { + return this.locked; + } + + public void setLocked(boolean val) { + this.locked = val; + this.setAutoSave(val); + } + + public boolean getSpam() { + return this.spam; + } + + public void setSpam(boolean val) { + this.spam = 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(instance); + return; + } + + int version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); + switch (version) { + case 7: + FactionsPlugin.instance.log("Minecraft Version 1.7 found, disabling banners, itemflags inside GUIs, and Titles."); + mc17 = true; + break; + case 8: + FactionsPlugin.instance.log("Minecraft Version 1.8 found, Title Fadeouttime etc will not be configurable."); + mc18 = true; + break; + case 12: + mc112 = true; + break; + case 13: + FactionsPlugin.instance.log("Minecraft Version 1.13 found, New Items will be used."); + mc113 = true; + break; + case 14: + FactionsPlugin.instance.log("Minecraft Version 1.14 found."); + mc114 = true; + break; + } + 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; + } + if (fPlayer.isAlt()) { + faction.addAltPlayer(fPlayer); + } else { + faction.addFPlayer(fPlayer); + } + } + + if (getConfig().getBoolean("enable-faction-flight", true)) { + UtilFly.run(); + } + + Board.getInstance().load(); + Board.getInstance().clean(); + + // Add Base Commands + this.cmdBase = new FCmdRoot(); + this.cmdAutoHelp = new CmdAutoHelp(); + + 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 (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 FactionsPlugin Addon..."); + skriptAddon = Skript.registerAddon(this); + try { + skriptAddon.loadClasses("com.massivecraft.factions.skript", "expressions"); + } catch (IOException ex) { + ex.printStackTrace(); + } + log("Skript addon registered!"); + } + if (Conf.useCheckSystem) { + int minute = 1200; + this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 3), 0L, (long) (minute * 3)); + this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 5), 0L, (long) (minute * 5)); + this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 10), 0L, (long) (minute * 10)); + this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 15), 0L, (long) (minute * 15)); + this.getServer().getScheduler().runTaskTimerAsynchronously(this, new CheckTask(this, 30), 0L, (long) (minute * 30)); + this.getServer().getScheduler().runTaskTimer(this, CheckTask::cleanupTask, 0L, 1200L); + this.getServer().getScheduler().runTaskTimerAsynchronously(this, new WeeWooTask(this), 600L, 600L); + } + ShopConfig.setup(); + + getServer().getPluginManager().registerEvents(factionsPlayerListener = new FactionsPlayerListener(), this); + + // Register Event Handlers + eventsListener = new Listener[]{ + new FactionsChatListener(), + new FactionsEntityListener(), + new FactionsExploitListener(), + new FactionsBlockListener(), + new FUpgradesGUI(), + new EXPUpgrade(), + new CropUpgrades(), + new RedstoneUpgrade(), + new ShopClickPersistence(), + new MissionHandler(this), + new ChestLogsHandler(), + new SpawnerUpgrades() + }; + + for (Listener eventListener : eventsListener) + getServer().getPluginManager().registerEvents(eventListener, this); + + this.getCommand(refCommand).setExecutor(cmdBase); + + if (!CommodoreProvider.isSupported()) this.getCommand(refCommand).setTabCompleter(this); + + + RegisteredServiceProvider rsp = FactionsPlugin.this.getServer().getServicesManager().getRegistration(Economy.class); + FactionsPlugin.econ = rsp.getProvider(); + + 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/Driftay/Saber-Factions/issues"); + divider(); + } + + this.setupPlaceholderAPI(); + this.postEnable(); + this.loadSuccessful = true; + // Set startup finished to true. to give plugins hooking in a greenlight + FactionsPlugin.startupFinished = true; + } + + public SkriptAddon getSkriptAddon() { + return skriptAddon; + } + + + 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."); + } + } + + public List replacePlaceholders(List lore, Placeholder... placeholders) { + for (Placeholder placeholder : placeholders) { + for (int x = 0; x <= lore.size() - 1; x++) + lore.set(x, lore.get(x).replace(placeholder.getTag(), placeholder.getReplace())); + } + return lore; + } + + private void migrateFPlayerLeaders() { + List lines = new ArrayList<>(); + File fplayerFile = new File("plugins" + File.pathSeparator + "Factions" + File.pathSeparator + "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\""); } - if (toggle) break; - } - } - String lastArg = args[args.length - 1].toLowerCase(); + 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."); + } + } - completions = completions.stream() - .filter(m -> m.toLowerCase().startsWith(lastArg)) - .collect(Collectors.toList()); + public boolean isClipPlaceholderAPIHooked() { + return this.clipPlaceholderAPIManager != null; + } - return completions; + public boolean isMVdWPlaceholderAPIHooked() { + return this.mvdwPlaceholderAPIManager; + } - } else { - String lastArg = args[args.length - 1].toLowerCase(); + 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; + } - for (Role value : Role.values()) completions.add(value.nicename); - for (Relation value : Relation.values()) completions.add(value.nicename); - // The stream and foreach from the old implementation looped 2 times, by looping all players -> filtered -> looped filter and added -> filtered AGAIN at the end. - // This loops them once and just adds, because we are filtering the arguments at the end anyways - for (Player player : Bukkit.getServer().getOnlinePlayers()) completions.add(player.getName()); - for (Faction faction : Factions.getInstance().getAllFactions()) - completions.add(ChatColor.stripColor(faction.getTag())); - completions = completions.stream().filter(m -> m.toLowerCase().startsWith(lastArg)).collect(Collectors.toList()); - return completions; - } - } + private boolean setupPlayervaults() { + Plugin plugin = getServer().getPluginManager().getPlugin("PlayerVaults"); + return plugin != null && plugin.isEnabled(); + } - 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(FactionsPlugin.instance.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; + @Override + public GsonBuilder getGsonBuilder() { + Type mapFLocToStringSetType = new TypeToken>>() { + }.getType(); - Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> { - armorStand.remove(); - getLogger().info("Removing Hologram."); - } - , timeout * 20); - } + 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(XMaterial.matchXMaterial(material.toString()).parseMaterial(), 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(FactionsPlugin.instance.getConfig().getString(name))); + meta.setLore(colorList(FactionsPlugin.instance.getConfig().getStringList(lore))); + item.setItemMeta(meta); + return item; + } + + public Economy getEcon() { + RegisteredServiceProvider rsp = FactionsPlugin.instance.getServer().getServicesManager().getRegistration(Economy.class); + return rsp.getProvider(); + } - // -------------------------------------------- // - // Functions for other plugins to hook into - // -------------------------------------------- // + @Override + public boolean logPlayerCommands() { + return Conf.logPlayerCommands; + } - // This value will be updated whenever new hooks are added - public int hookSupportVersion() { - return 3; - } + @Override + public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) { + return sender instanceof Player && FactionsPlayerListener.preventCommand(commandString, (Player) sender) || super.handleCommand(sender, commandString, testOnly); + } - // If another plugin is handling insertion of chat tags, this should be used to notify Factions - public void handleFactionTagExternally(boolean notByFactions) { - Conf.chatTagHandledByAnotherPlugin = notByFactions; - } + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { + if (split.length == 0) { + return handleCommand(sender, "/f help", false); + } - // 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() + // 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); + } - public boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event) { - return event != null && (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage())); - } + // This method must stay for < 1.12 versions + @Override + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + // Must be a LinkedList to prevent UnsupportedOperationException. + List argsList = new LinkedList<>(Arrays.asList(args)); + CommandContext context = new CommandContext(sender, argsList, alias); + String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0); +// String cmdValid = (cmd + " " + TextUtil.implode(context.args, " ")).trim(); + List commandsList = cmdBase.subCommands; + FCommand commandsEx = cmdBase; + List completions = new ArrayList<>(); + + // Check for "" first arg because spigot is mangled. + if (context.args.get(0).equals("")) { + for (FCommand subCommand : commandsEx.subCommands) { + if (subCommand.requirements.playerOnly && sender.hasPermission(subCommand.requirements.permission.node) && subCommand.visibility != CommandVisibility.INVISIBLE) + completions.addAll(subCommand.aliases); + } + return completions; + } else if (context.args.size() == 1) { + for (; !commandsList.isEmpty() && !context.args.isEmpty(); context.args.remove(0)) { + String cmdName = context.args.get(0).toLowerCase(); + boolean toggle = false; + for (FCommand fCommand : commandsList) { + for (String s : fCommand.aliases) { + if (s.startsWith(cmdName)) { + commandsList = fCommand.subCommands; + completions.addAll(fCommand.aliases); + toggle = true; + break; + } + } + if (toggle) break; + } + } + String lastArg = args[args.length - 1].toLowerCase(); + + completions = completions.stream() + .filter(m -> m.toLowerCase().startsWith(lastArg)) + .collect(Collectors.toList()); + + return completions; + + } else { + String lastArg = args[args.length - 1].toLowerCase(); + + for (Role value : Role.values()) completions.add(value.nicename); + for (Relation value : Relation.values()) completions.add(value.nicename); + // The stream and foreach from the old implementation looped 2 times, by looping all players -> filtered -> looped filter and added -> filtered AGAIN at the end. + // This loops them once and just adds, because we are filtering the arguments at the end anyways + for (Player player : Bukkit.getServer().getOnlinePlayers()) completions.add(player.getName()); + for (Faction faction : Factions.getInstance().getAllFactions()) + completions.add(ChatColor.stripColor(faction.getTag())); + 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(FactionsPlugin.instance.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(FactionsPlugin.instance, () -> { + armorStand.remove(); + getLogger().info("Removing Hologram."); + } + , timeout * 20); + } - // 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); + // -------------------------------------------- // + // Functions for other plugins to hook into + // -------------------------------------------- // - return me != null && me.getChatMode().isAtLeast(ChatMode.ALLIANCE); - } + // This value will be updated whenever new hooks are added + public int hookSupportVersion() { + return 3; + } - // Is this chat message actually a Factions command, and thus should be left alone by other plugins? + // If another plugin is handling insertion of chat tags, this should be used to notify Factions + public void handleFactionTagExternally(boolean notByFactions) { + Conf.chatTagHandledByAnotherPlugin = notByFactions; + } - // TODO: GET THIS BACK AND WORKING + // 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 isFactionsCommand(String check) { - return !(check == null || check.isEmpty()) && this.handleCommand(null, check, true); - } + public boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event) { + return event != null && (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage())); + } - // 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 = "~"; + // 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); - if (speaker == null) { - return tag; - } + return me != null && me.getChatMode().isAtLeast(ChatMode.ALLIANCE); + } - FPlayer me = FPlayers.getInstance().getByPlayer(speaker); - if (me == null) { - return tag; - } + // Is this chat message actually a Factions command, and thus should be left alone by other plugins? - // 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 = "~"; - } + // TODO: GET THIS BACK AND WORKING - return tag; - } + public boolean isFactionsCommand(String check) { + return !(check == null || check.isEmpty()) && this.handleCommand(null, check, true); + } - // 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 ""; - } + // 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); + } - FPlayer me = FPlayers.getInstance().getByPlayer(player); - if (me == null) { - return ""; - } + // Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag + public String getPlayerFactionTagRelation(Player speaker, Player listener) { + String tag = "~"; - return me.getTitle().trim(); - } + if (speaker == null) { + return tag; + } - public String color(String line) { - line = ChatColor.translateAlternateColorCodes('&', line); - return line; - } + FPlayer me = FPlayers.getInstance().getByPlayer(speaker); + if (me == null) { + return tag; + } - //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; - } + // 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 = "~"; + } - // Get a list of all faction tags (names) - public Set getFactionTags() { - return Factions.getInstance().getFactionTags(); - } + return tag; + } - // 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 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 ""; + } - // 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; - } + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me == null) { + return ""; + } - public boolean isHookedPlayervaults() { - return hookedPlayervaults; - } + return me.getTitle().trim(); + } - public String getPrimaryGroup(OfflinePlayer player) { - AtomicReference primaryGroup = new AtomicReference<>(); + public String color(String line) { + line = ChatColor.translateAlternateColorCodes('&', line); + return line; + } - if (perms == null || !perms.hasGroupSupport()) return " "; - else { - Bukkit.getScheduler().runTaskAsynchronously(this, () -> primaryGroup.set(perms.getPrimaryGroup(Bukkit.getWorlds().get(0).toString(), player))); - return primaryGroup.get(); - } - } + //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; + } - public void debug(Level level, String s) { - if (getConfig().getBoolean("debug", false)) { - getLogger().log(level, s); - } - } + // Get a list of all faction tags (names) + public Set getFactionTags() { + return Factions.getInstance().getFactionTags(); + } - public FactionsPlayerListener getFactionsPlayerListener() { - return this.factionsPlayerListener; - } + // 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; + } - public void debug(String s) { - debug(Level.INFO, s); - } + // 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) { + AtomicReference primaryGroup = new AtomicReference<>(); + + if (perms == null || !perms.hasGroupSupport()) return " "; + else { + Bukkit.getScheduler().runTaskAsynchronously(this, () -> primaryGroup.set(perms.getPrimaryGroup(Bukkit.getWorlds().get(0).toString(), player))); + return primaryGroup.get(); + } + } + + public void debug(Level level, String s) { + if (getConfig().getBoolean("debug", false)) { + getLogger().log(level, s); + } + } + + public FactionsPlayerListener getFactionsPlayerListener() { + return this.factionsPlayerListener; + } + + public void debug(String s) { + debug(Level.INFO, s); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/BrigadierManager.java b/src/main/java/com/massivecraft/factions/cmd/BrigadierManager.java index ecd4851b..f7099fc6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/BrigadierManager.java +++ b/src/main/java/com/massivecraft/factions/cmd/BrigadierManager.java @@ -15,78 +15,78 @@ import java.util.Map; public class BrigadierManager { - public Commodore commodore; - public LiteralArgumentBuilder brigadier = LiteralArgumentBuilder.literal("factions"); + public Commodore commodore; + public LiteralArgumentBuilder brigadier = LiteralArgumentBuilder.literal("factions"); - public BrigadierManager() { - commodore = CommodoreProvider.getCommodore(FactionsPlugin.getInstance()); - } + public BrigadierManager() { + commodore = CommodoreProvider.getCommodore(FactionsPlugin.getInstance()); + } - public void build() { - commodore.register(brigadier.build()); + public void build() { + commodore.register(brigadier.build()); - // Add factions children to f alias - LiteralArgumentBuilder fLiteral = LiteralArgumentBuilder.literal("f"); - for (CommandNode node : brigadier.getArguments()) fLiteral.then(node); - commodore.register(fLiteral.build()); - } + // Add factions children to f alias + LiteralArgumentBuilder fLiteral = LiteralArgumentBuilder.literal("f"); + for (CommandNode node : brigadier.getArguments()) fLiteral.then(node); + commodore.register(fLiteral.build()); + } - public void addSubCommand(FCommand subCommand) { - // Register brigadier to all command aliases - for (String alias : subCommand.aliases) { - LiteralArgumentBuilder literal = LiteralArgumentBuilder.literal(alias); + public void addSubCommand(FCommand subCommand) { + // Register brigadier to all command aliases + for (String alias : subCommand.aliases) { + LiteralArgumentBuilder literal = LiteralArgumentBuilder.literal(alias); - if (subCommand.requirements.brigadier != null) { - // If the requirements explicitly provide a BrigadierProvider then use it - Class brigadierProvider = subCommand.requirements.brigadier; + if (subCommand.requirements.brigadier != null) { + // If the requirements explicitly provide a BrigadierProvider then use it + Class brigadierProvider = subCommand.requirements.brigadier; - try { - Constructor constructor = brigadierProvider.getDeclaredConstructor(subCommand.getClass()); - brigadier.then(constructor.newInstance(subCommand).get(literal)); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - // Generate our own based on args - quite ugly + try { + Constructor constructor = brigadierProvider.getDeclaredConstructor(subCommand.getClass()); + brigadier.then(constructor.newInstance(subCommand).get(literal)); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + // Generate our own based on args - quite ugly - // We create an orderly stack of all args, required and optional, format them differently - List> stack = new ArrayList<>(); - for (String required : subCommand.requiredArgs) { - // Simply add the arg name as required - stack.add(RequiredArgumentBuilder.argument(required, StringArgumentType.word())); - } - - for (Map.Entry optionalEntry : subCommand.optionalArgs.entrySet()) { - RequiredArgumentBuilder optional; - - // Optional without default - if (optionalEntry.getKey().equalsIgnoreCase(optionalEntry.getValue())) { - optional = RequiredArgumentBuilder.argument(":" + optionalEntry.getKey(), StringArgumentType.word()); - // Optional with default, explain - } else { - optional = RequiredArgumentBuilder.argument(optionalEntry.getKey() + "|" + optionalEntry.getValue(), StringArgumentType.word()); + // We create an orderly stack of all args, required and optional, format them differently + List> stack = new ArrayList<>(); + for (String required : subCommand.requiredArgs) { + // Simply add the arg name as required + stack.add(RequiredArgumentBuilder.argument(required, StringArgumentType.word())); } - stack.add(optional); - } + for (Map.Entry optionalEntry : subCommand.optionalArgs.entrySet()) { + RequiredArgumentBuilder optional; + + // Optional without default + if (optionalEntry.getKey().equalsIgnoreCase(optionalEntry.getValue())) { + optional = RequiredArgumentBuilder.argument(":" + optionalEntry.getKey(), StringArgumentType.word()); + // Optional with default, explain + } else { + optional = RequiredArgumentBuilder.argument(optionalEntry.getKey() + "|" + optionalEntry.getValue(), StringArgumentType.word()); + } + + stack.add(optional); + } + + // Reverse the stack and apply .then() + RequiredArgumentBuilder previous = null; + for (int i = stack.size() - 1; i >= 0; i--) { + if (previous == null) { + previous = stack.get(i); + } else { + previous = stack.get(i).then(previous); + } + } - // Reverse the stack and apply .then() - RequiredArgumentBuilder previous = null; - for (int i = stack.size() - 1; i >= 0; i--) { if (previous == null) { - previous = stack.get(i); + brigadier.then(literal); } else { - previous = stack.get(i).then(previous); + brigadier.then(literal.then(previous)); } - } - - if (previous == null) { - brigadier.then(literal); - } else { - brigadier.then(literal.then(previous)); - } - } - } - } + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/BrigadierProvider.java b/src/main/java/com/massivecraft/factions/cmd/BrigadierProvider.java index 455b3877..e3e61269 100644 --- a/src/main/java/com/massivecraft/factions/cmd/BrigadierProvider.java +++ b/src/main/java/com/massivecraft/factions/cmd/BrigadierProvider.java @@ -4,6 +4,6 @@ import com.mojang.brigadier.builder.ArgumentBuilder; public interface BrigadierProvider { - ArgumentBuilder get(ArgumentBuilder parent); + ArgumentBuilder get(ArgumentBuilder parent); } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java b/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java index a7763eea..ccd6f2ba 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java @@ -8,40 +8,40 @@ 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"); + this.requiredArgs.add("player"); - this.requirements = new CommandRequirements.Builder(Permission.AHOME).noDisableOnLock().build(); - } + this.requirements = new CommandRequirements.Builder(Permission.AHOME).noDisableOnLock().build(); + } - @Override - public void perform(CommandContext context) { - FPlayer target = context.argAsBestFPlayerMatch(0); - if (target == null) { - context.msg(TL.GENERIC_NOPLAYERMATCH, context.argAsString(0)); - return; - } + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0); + if (target == null) { + context.msg(TL.GENERIC_NOPLAYERMATCH, context.argAsString(0)); + return; + } - if (target.isOnline()) { - Faction faction = target.getFaction(); - if (faction.hasHome()) { - target.getPlayer().teleport(faction.getHome(), PlayerTeleportEvent.TeleportCause.PLUGIN); - context.msg(TL.COMMAND_AHOME_SUCCESS, target.getName()); - target.msg(TL.COMMAND_AHOME_TARGET); - } else { - context.msg(TL.COMMAND_AHOME_NOHOME, target.getName()); - } - } else { - context.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); + context.msg(TL.COMMAND_AHOME_SUCCESS, target.getName()); + target.msg(TL.COMMAND_AHOME_TARGET); + } else { + context.msg(TL.COMMAND_AHOME_NOHOME, target.getName()); + } + } else { + context.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; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java index 3af1ef18..701cf808 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java @@ -11,77 +11,77 @@ 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"); + this.requiredArgs.add("player"); - this.requirements = new CommandRequirements.Builder(Permission.ADMIN).build(); - } + this.requirements = new CommandRequirements.Builder(Permission.ADMIN).build(); + } - @Override - public void perform(CommandContext context) { - // Allows admins bypass this. - if (!context.fPlayer.isAdminBypassing() && !context.fPlayer.getRole().equals(Role.LEADER)) { - context.msg(TL.COMMAND_ADMIN_NOTADMIN); - return; - } - FPlayer fyou = context.argAsBestFPlayerMatch(0); - if (fyou == null) { - return; - } + @Override + public void perform(CommandContext context) { + // Allows admins bypass this. + if (!context.fPlayer.isAdminBypassing() && !context.fPlayer.getRole().equals(Role.LEADER)) { + context.msg(TL.COMMAND_ADMIN_NOTADMIN); + return; + } + FPlayer fyou = context.argAsBestFPlayerMatch(0); + if (fyou == null) { + return; + } - boolean permAny = Permission.ADMIN_ANY.has(context.sender, false); - Faction targetFaction = fyou.getFaction(); + boolean permAny = Permission.ADMIN_ANY.has(context.sender, false); + Faction targetFaction = fyou.getFaction(); - if (targetFaction != context.faction && !permAny) { - context.msg(TL.COMMAND_ADMIN_NOTMEMBER, fyou.describeTo(context.fPlayer, true)); - return; - } + if (targetFaction != context.faction && !permAny) { + context.msg(TL.COMMAND_ADMIN_NOTMEMBER, fyou.describeTo(context.fPlayer, true)); + return; + } - if (fyou == context.fPlayer && !permAny) { - context.msg(TL.COMMAND_ADMIN_TARGETSELF); - return; - } + if (fyou == context.fPlayer && !permAny) { + context.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(context.player), 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(context.player), targetFaction, FPlayerJoinEvent.PlayerJoinReason.LEADER); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + } - FPlayer admin = targetFaction.getFPlayerAdmin(); + FPlayer admin = targetFaction.getFPlayerAdmin(); - // if target player is currently admin, demote and replace him - if (fyou == admin) { - targetFaction.promoteNewLeader(); - context.msg(TL.COMMAND_ADMIN_DEMOTES, fyou.describeTo(context.fPlayer, true)); - fyou.msg(TL.COMMAND_ADMIN_DEMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fyou, true)); - return; - } + // if target player is currently admin, demote and replace him + if (fyou == admin) { + targetFaction.promoteNewLeader(); + context.msg(TL.COMMAND_ADMIN_DEMOTES, fyou.describeTo(context.fPlayer, true)); + fyou.msg(TL.COMMAND_ADMIN_DEMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.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); - context.msg(TL.COMMAND_ADMIN_PROMOTES, fyou.describeTo(context.fPlayer, true)); + // promote target player, and demote existing admin if one exists + if (admin != null) { + admin.setRole(Role.COLEADER); + } + fyou.setRole(Role.LEADER); + context.msg(TL.COMMAND_ADMIN_PROMOTES, fyou.describeTo(context.fPlayer, true)); - // Inform all players - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer)); - } - } + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, context.player == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.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 91378e95..9a027676 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java @@ -12,46 +12,46 @@ 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.requiredArgs.add("message"); - this.requirements = new CommandRequirements.Builder(Permission.ANNOUNCE) - .playerOnly() - .memberOnly() - .brigadier(AnnounceBrigadier.class) - .noErrorOnManyArgs() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.ANNOUNCE) + .playerOnly() + .memberOnly() + .brigadier(AnnounceBrigadier.class) + .noErrorOnManyArgs() + .build(); + } - @Override - public void perform(CommandContext context) { - String prefix = ChatColor.GREEN + context.faction.getTag() + ChatColor.YELLOW + " [" + ChatColor.GRAY + context.player.getName() + ChatColor.YELLOW + "] " + ChatColor.RESET; - String message = StringUtils.join(context.args, " "); + @Override + public void perform(CommandContext context) { + String prefix = ChatColor.GREEN + context.faction.getTag() + ChatColor.YELLOW + " [" + ChatColor.GRAY + context.player.getName() + ChatColor.YELLOW + "] " + ChatColor.RESET; + String message = StringUtils.join(context.args, " "); - for (Player player : context.faction.getOnlinePlayers()) { - player.sendMessage(prefix + message); - } + for (Player player : context.faction.getOnlinePlayers()) { + player.sendMessage(prefix + message); + } - // Add for offline players. - for (FPlayer fp : context.faction.getFPlayersWhereOnline(false)) { - context.faction.addAnnouncement(fp, prefix + message); - } - } + // Add for offline players. + for (FPlayer fp : context.faction.getFPlayersWhereOnline(false)) { + context.faction.addAnnouncement(fp, prefix + message); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_ANNOUNCE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ANNOUNCE_DESCRIPTION; + } - protected class AnnounceBrigadier implements BrigadierProvider { - @Override - public ArgumentBuilder get(ArgumentBuilder parent) { - return parent.then(RequiredArgumentBuilder.argument("message", StringArgumentType.greedyString())); - } - } + protected class AnnounceBrigadier implements BrigadierProvider { + @Override + public ArgumentBuilder get(ArgumentBuilder parent) { + return parent.then(RequiredArgumentBuilder.argument("message", StringArgumentType.greedyString())); + } + } } \ 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 87884a5c..32de2fd8 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java @@ -8,37 +8,37 @@ import java.util.ArrayList; public class CmdAutoHelp extends FCommand { - public CmdAutoHelp() { - this.aliases.add("?"); - this.aliases.add("h"); - this.aliases.add("help"); + public CmdAutoHelp() { + this.aliases.add("?"); + this.aliases.add("h"); + this.aliases.add("help"); - this.setHelpShort(""); + this.setHelpShort(""); - this.optionalArgs.put("page", "1"); - } + this.optionalArgs.put("page", "1"); + } - @Override - public void perform(CommandContext context) { - if (context.commandChain.size() == 0) { - return; - } - FCommand pcmd = context.commandChain.get(context.commandChain.size() - 1); + @Override + public void perform(CommandContext context) { + if (context.commandChain.size() == 0) { + return; + } + FCommand pcmd = context.commandChain.get(context.commandChain.size() - 1); - ArrayList lines = new ArrayList<>(pcmd.helpLong); + ArrayList lines = new ArrayList<>(pcmd.helpLong); - for (FCommand scmd : pcmd.subCommands) { - if (scmd.visibility == CommandVisibility.VISIBLE) { - lines.add(scmd.getUseageTemplate(context, true)); - } - // TODO deal with other visibilities - } + for (FCommand scmd : pcmd.subCommands) { + if (scmd.visibility == CommandVisibility.VISIBLE) { + lines.add(scmd.getUseageTemplate(context, true)); + } + // TODO deal with other visibilities + } - context.sendMessage(FactionsPlugin.getInstance().txt.getPage(lines, context.argAsInt(0, 1), TL.COMMAND_AUTOHELP_HELPFOR.toString() + pcmd.aliases.get(0) + "\"")); - } + context.sendMessage(FactionsPlugin.getInstance().txt.getPage(lines, context.argAsInt(0, 1), TL.COMMAND_AUTOHELP_HELPFOR.toString() + pcmd.aliases.get(0) + "\"")); + } - @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/CmdBan.java b/src/main/java/com/massivecraft/factions/cmd/CmdBan.java index f9158d10..37f5fe63 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBan.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBan.java @@ -13,73 +13,73 @@ 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.requirements = new CommandRequirements.Builder(Permission.BAN) - .playerOnly() - .withAction(PermissableAction.BAN) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.BAN) + .playerOnly() + .withAction(PermissableAction.BAN) + .build(); + } - @Override - public void perform(CommandContext context) { + @Override + public void perform(CommandContext context) { - // Good on permission checks. Now lets just ban the player. - FPlayer target = context.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 = context.argAsFPlayer(0); + if (target == null) { + return; // the above method sends a message if fails to find someone. + } - if (context.fPlayer == target) { - // You may not ban yourself - context.msg(TL.COMMAND_BAN_SELF); - return; - } else if (target.getFaction() == context.faction && target.getRole().value >= context.fPlayer.getRole().value) { - // You may not ban someone that has same or higher faction rank - context.msg(TL.COMMAND_BAN_INSUFFICIENTRANK, target.getName()); - return; - } + if (context.fPlayer == target) { + // You may not ban yourself + context.msg(TL.COMMAND_BAN_SELF); + return; + } else if (target.getFaction() == context.faction && target.getRole().value >= context.fPlayer.getRole().value) { + // You may not ban someone that has same or higher faction rank + context.msg(TL.COMMAND_BAN_INSUFFICIENTRANK, target.getName()); + return; + } - for (BanInfo banInfo : context.faction.getBannedPlayers()) { - if (banInfo.getBanned().equals(target.getId())) { - context.msg(TL.COMMAND_BAN_ALREADYBANNED); - return; - } - } + for (BanInfo banInfo : context.faction.getBannedPlayers()) { + if (banInfo.getBanned().equals(target.getId())) { + context.msg(TL.COMMAND_BAN_ALREADYBANNED); + return; + } + } - // Ban the user. - context.faction.ban(target, context.fPlayer); - context.faction.deinvite(target); // can't hurt + // Ban the user. + context.faction.ban(target, context.fPlayer); + context.faction.deinvite(target); // can't hurt - // If in same Faction, lets make sure to kick them and throw an event. - if (target.getFaction() == context.faction) { + // If in same Faction, lets make sure to kick them and throw an event. + if (target.getFaction() == context.faction) { - FPlayerLeaveEvent event = new FPlayerLeaveEvent(target, context.faction, FPlayerLeaveEvent.PlayerLeaveReason.BANNED); - Bukkit.getServer().getPluginManager().callEvent(event); + FPlayerLeaveEvent event = new FPlayerLeaveEvent(target, context.faction, 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. - FactionsPlugin.getInstance().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. + FactionsPlugin.getInstance().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. - context.faction.removeFPlayer(target); - target.resetFactionData(); - } + // Didn't get cancelled so remove them and reset their invite. + context.faction.removeFPlayer(target); + target.resetFactionData(); + } - // Lets inform the people! - target.msg(TL.COMMAND_BAN_TARGET, context.faction.getTag(target.getFaction())); - context.faction.msg(TL.COMMAND_BAN_BANNED, context.fPlayer.getName(), target.getName()); - } + // Lets inform the people! + target.msg(TL.COMMAND_BAN_TARGET, context.faction.getTag(target.getFaction())); + context.faction.msg(TL.COMMAND_BAN_BANNED, context.fPlayer.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 41efc743..93e8f2d8 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java @@ -13,57 +13,57 @@ 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.requirements = new CommandRequirements.Builder(Permission.BAN) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.BAN) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Faction target = context.faction; - if (!context.args.isEmpty()) { - target = context.argAsFaction(0); - } + @Override + public void perform(CommandContext context) { + Faction target = context.faction; + if (!context.args.isEmpty()) { + target = context.argAsFaction(0); + } - if (target == Factions.getInstance().getWilderness()) { - context.sender.sendMessage(TL.COMMAND_BANLIST_NOFACTION.toString()); - return; - } + if (target == Factions.getInstance().getWilderness()) { + context.sender.sendMessage(TL.COMMAND_BANLIST_NOFACTION.toString()); + return; + } - if (target == null) { - context.sender.sendMessage(TL.COMMAND_BANLIST_INVALID.format(context.argAsString(0))); - return; - } + if (target == null) { + context.sender.sendMessage(TL.COMMAND_BANLIST_INVALID.format(context.argAsString(0))); + return; + } - List lines = new ArrayList<>(); - lines.add(TL.COMMAND_BANLIST_HEADER.format(target.getBannedPlayers().size(), target.getTag(context.faction))); - int i = 1; + List lines = new ArrayList<>(); + lines.add(TL.COMMAND_BANLIST_HEADER.format(target.getBannedPlayers().size(), target.getTag(context.faction))); + 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) { - context.fPlayer.getPlayer().sendMessage(s); - } - } + for (String s : lines) { + context.fPlayer.getPlayer().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 a73066c1..62607e18 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBanner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBanner.java @@ -6,113 +6,110 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; import net.milkbowl.vault.economy.Economy; import org.bukkit.Material; -import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; -import java.util.List; - public class CmdBanner extends FCommand { - public CmdBanner() { - this.aliases.add("banner"); - this.aliases.add("warbanner"); - this.requirements = new CommandRequirements.Builder(Permission.BANNER).playerOnly().memberOnly().build(); - } + public CmdBanner() { + this.aliases.add("banner"); + this.aliases.add("warbanner"); + this.requirements = new CommandRequirements.Builder(Permission.BANNER).playerOnly().memberOnly().build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Enabled")) { - context.msg(TL.COMMAND_BANNER_DISABLED); - return; - } - if (context.faction.getBanner() == null) { - context.msg(TL.COMMAND_BANNER_NOBANNER); - return; - } - if (!context.fPlayer.hasMoney(FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Cost", 5000))) { - context.msg(TL.COMMAND_BANNER_NOTENOUGHMONEY); - return; - } - this.takeMoney(context.fPlayer, FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Cost", 5000)); - this.takeMoney(context.fPlayer, FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Cost", 5000)); - ItemStack warBanner = context.fPlayer.getFaction().getBanner(); - ItemMeta warmeta = warBanner.getItemMeta(); - warmeta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.Item.Name"))); - warmeta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Item.Lore"))); - warBanner.setItemMeta(warmeta); - context.msg(TL.COMMAND_BANNER_SUCCESS); - warBanner.setAmount(1); - context.player.getInventory().addItem(warBanner); - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Enabled")) { + context.msg(TL.COMMAND_BANNER_DISABLED); + return; + } + if (context.faction.getBanner() == null) { + context.msg(TL.COMMAND_BANNER_NOBANNER); + return; + } + if (!context.fPlayer.hasMoney(FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Cost", 5000))) { + context.msg(TL.COMMAND_BANNER_NOTENOUGHMONEY); + return; + } + this.takeMoney(context.fPlayer, FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Cost", 5000)); + this.takeMoney(context.fPlayer, FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Cost", 5000)); + ItemStack warBanner = context.fPlayer.getFaction().getBanner(); + ItemMeta warmeta = warBanner.getItemMeta(); + warmeta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.Item.Name"))); + warmeta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Item.Lore"))); + warBanner.setItemMeta(warmeta); + context.msg(TL.COMMAND_BANNER_SUCCESS); + warBanner.setAmount(1); + context.player.getInventory().addItem(warBanner); + } - public boolean hasMoney(FPlayer fme, int amt) { - Economy econ = FactionsPlugin.getInstance().getEcon(); - if (econ.getBalance(fme.getPlayer()) >= amt) { - return true; - } - fme.msg(TL.COMMAND_BANNER_NOTENOUGHMONEY); - return false; - } + public boolean hasMoney(FPlayer fme, int amt) { + Economy econ = FactionsPlugin.getInstance().getEcon(); + if (econ.getBalance(fme.getPlayer()) >= amt) { + return true; + } + fme.msg(TL.COMMAND_BANNER_NOTENOUGHMONEY); + return false; + } - public void takeMoney(FPlayer fme, int amt) { - if (this.hasMoney(fme, amt)) { - Economy econ = FactionsPlugin.getInstance().getEcon(); - econ.withdrawPlayer(fme.getPlayer(), (double) amt); - fme.sendMessage(TL.COMMAND_BANNER_MONEYTAKE.toString().replace("{amount}", amt + "")); - } - } + public void takeMoney(FPlayer fme, int amt) { + if (this.hasMoney(fme, amt)) { + Economy econ = FactionsPlugin.getInstance().getEcon(); + econ.withdrawPlayer(fme.getPlayer(), (double) 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 (ItemStack item1 : items) { - if (item1 != null && item1.getType() == item.getType() && item1.getDurability() == item.getDurability()) { - count += item1.getAmount(); - } - if (count >= item.getAmount()) { - return true; - } - } - return false; - } + public boolean inventoryContains(Inventory inventory, ItemStack item) { + int count = 0; + ItemStack[] items = inventory.getContents(); + for (ItemStack item1 : items) { + if (item1 != null && item1.getType() == item.getType() && item1.getDurability() == item.getDurability()) { + count += item1.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; - } - if (items[i].getAmount() == amt) { + 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; + } + if (items[i].getAmount() == amt) { + items[i] = null; + break; + } + amt -= items[i].getAmount(); items[i] = null; - break; - } - amt -= items[i].getAmount(); - items[i] = null; - } - } - inventory.setContents(items); - } + } + } + 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 26a06943..37f2bbea 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java @@ -6,42 +6,42 @@ 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.requirements = new CommandRequirements.Builder(Permission.NO_BOOM) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.NO_BOOM) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!context.faction.isPeaceful()) { - context.msg(TL.COMMAND_BOOM_PEACEFULONLY); - return; - } + @Override + public void perform(CommandContext context) { + if (!context.faction.isPeaceful()) { + context.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 (!context.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 (!context.payForCommand(Conf.econCostNoBoom, TL.COMMAND_BOOM_TOTOGGLE, TL.COMMAND_BOOM_FORTOGGLE)) { + return; + } - context.faction.setPeacefulExplosionsEnabled(context.argAsBool(0, !context.faction.getPeacefulExplosionsEnabled())); + context.faction.setPeacefulExplosionsEnabled(context.argAsBool(0, !context.faction.getPeacefulExplosionsEnabled())); - String enabled = context.faction.noExplosionsInTerritory() ? TL.GENERIC_DISABLED.toString() : TL.GENERIC_ENABLED.toString(); + String enabled = context.faction.noExplosionsInTerritory() ? TL.GENERIC_DISABLED.toString() : TL.GENERIC_ENABLED.toString(); - // Inform - context.faction.msg(TL.COMMAND_BOOM_ENABLED, context.fPlayer.describeTo(context.faction), enabled); - } + // Inform + context.faction.msg(TL.COMMAND_BOOM_ENABLED, context.fPlayer.describeTo(context.faction), 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 b95a30a8..bacb7b64 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java @@ -6,34 +6,34 @@ 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.requirements = new CommandRequirements.Builder(Permission.BYPASS) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.BYPASS) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - context.fPlayer.setIsAdminBypassing(context.argAsBool(0, !context.fPlayer.isAdminBypassing())); + @Override + public void perform(CommandContext context) { + context.fPlayer.setIsAdminBypassing(context.argAsBool(0, !context.fPlayer.isAdminBypassing())); - // TODO: Move this to a transient field in the model?? - if (context.fPlayer.isAdminBypassing()) { - context.fPlayer.msg(TL.COMMAND_BYPASS_ENABLE.toString()); - FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_BYPASS_ENABLELOG.toString()); - } else { - context.fPlayer.msg(TL.COMMAND_BYPASS_DISABLE.toString()); - FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_BYPASS_DISABLELOG.toString()); - } - } + // TODO: Move this to a transient field in the model?? + if (context.fPlayer.isAdminBypassing()) { + context.fPlayer.msg(TL.COMMAND_BYPASS_ENABLE.toString()); + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_BYPASS_ENABLELOG.toString()); + } else { + context.fPlayer.msg(TL.COMMAND_BYPASS_DISABLE.toString()); + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_BYPASS_DISABLELOG.toString()); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_BYPASS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BYPASS_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdChat.java b/src/main/java/com/massivecraft/factions/cmd/CmdChat.java index d23946f5..c5a366ce 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChat.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChat.java @@ -10,88 +10,88 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; 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.requirements = new CommandRequirements.Builder(Permission.CHAT) - .playerOnly() - .memberOnly() - .brigadier(ChatBrigadier.class) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CHAT) + .playerOnly() + .memberOnly() + .brigadier(ChatBrigadier.class) + .build(); + } - @Override - public void perform(CommandContext context) { - if (!Conf.factionOnlyChat) { - context.msg(TL.COMMAND_CHAT_DISABLED.toString()); - return; - } + @Override + public void perform(CommandContext context) { + if (!Conf.factionOnlyChat) { + context.msg(TL.COMMAND_CHAT_DISABLED.toString()); + return; + } - String modeString = context.argAsString(0); - ChatMode modeTarget = context.fPlayer.getChatMode().getNext(); + String modeString = context.argAsString(0); + ChatMode modeTarget = context.fPlayer.getChatMode().getNext(); - if (modeString != null) { - modeString = modeString.toLowerCase(); - // Only allow Mods and higher rank to switch to this channel. - if (modeString.startsWith("m")) { - if (!context.fPlayer.getRole().isAtLeast(Role.MODERATOR)) { - context.msg(TL.COMMAND_CHAT_MOD_ONLY); + if (modeString != null) { + modeString = modeString.toLowerCase(); + // Only allow Mods and higher rank to switch to this channel. + if (modeString.startsWith("m")) { + if (!context.fPlayer.getRole().isAtLeast(Role.MODERATOR)) { + context.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 { + context.msg(TL.COMMAND_CHAT_INVALIDMODE); 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 { - context.msg(TL.COMMAND_CHAT_INVALIDMODE); - return; - } - } + } + } - context.fPlayer.setChatMode(modeTarget); + context.fPlayer.setChatMode(modeTarget); - switch (context.fPlayer.getChatMode()) { - case MOD: - context.msg(TL.COMMAND_CHAT_MODE_MOD); - break; - case PUBLIC: - context.msg(TL.COMMAND_CHAT_MODE_PUBLIC); - break; - case ALLIANCE: - context.msg(TL.COMMAND_CHAT_MODE_ALLIANCE); - break; - case TRUCE: - context.msg(TL.COMMAND_CHAT_MODE_TRUCE); - break; - default: - context.msg(TL.COMMAND_CHAT_MODE_FACTION); - break; - } - } + switch (context.fPlayer.getChatMode()) { + case MOD: + context.msg(TL.COMMAND_CHAT_MODE_MOD); + break; + case PUBLIC: + context.msg(TL.COMMAND_CHAT_MODE_PUBLIC); + break; + case ALLIANCE: + context.msg(TL.COMMAND_CHAT_MODE_ALLIANCE); + break; + case TRUCE: + context.msg(TL.COMMAND_CHAT_MODE_TRUCE); + break; + default: + context.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; + } - protected class ChatBrigadier implements BrigadierProvider { - @Override - public ArgumentBuilder get(ArgumentBuilder parent) { - return parent.then(LiteralArgumentBuilder.literal("public")) - .then(LiteralArgumentBuilder.literal("mod")) - .then(LiteralArgumentBuilder.literal("alliance")) - .then(LiteralArgumentBuilder.literal("faction")) - .then(LiteralArgumentBuilder.literal("truce")); - } - } + protected class ChatBrigadier implements BrigadierProvider { + @Override + public ArgumentBuilder get(ArgumentBuilder parent) { + return parent.then(LiteralArgumentBuilder.literal("public")) + .then(LiteralArgumentBuilder.literal("mod")) + .then(LiteralArgumentBuilder.literal("alliance")) + .then(LiteralArgumentBuilder.literal("faction")) + .then(LiteralArgumentBuilder.literal("truce")); + } + } } \ 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 7e56bbc4..7f33cb0f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java @@ -6,32 +6,32 @@ 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.requirements = new CommandRequirements.Builder(Permission.CHATSPY) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CHATSPY) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - context.fPlayer.setSpyingChat(context.argAsBool(0, !context.fPlayer.isSpyingChat())); + @Override + public void perform(CommandContext context) { + context.fPlayer.setSpyingChat(context.argAsBool(0, !context.fPlayer.isSpyingChat())); - if (context.fPlayer.isSpyingChat()) { - context.msg(TL.COMMAND_CHATSPY_ENABLE); - FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_CHATSPY_ENABLELOG.toString()); - } else { - context.msg(TL.COMMAND_CHATSPY_DISABLE); - FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_CHATSPY_DISABLELOG.toString()); - } - } + if (context.fPlayer.isSpyingChat()) { + context.msg(TL.COMMAND_CHATSPY_ENABLE); + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_CHATSPY_ENABLELOG.toString()); + } else { + context.msg(TL.COMMAND_CHATSPY_DISABLE); + FactionsPlugin.getInstance().log(context.fPlayer.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 20e08ad6..78bb35bc 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java @@ -6,60 +6,60 @@ 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.requirements = new CommandRequirements.Builder(Permission.CHECKPOINT) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CHECKPOINT) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("checkpoints.Enabled")) { - context.msg(TL.COMMAND_CHECKPOINT_DISABLED); - return; - } - if (context.args.size() == 1) { - FLocation myLocation = new FLocation(context.player.getLocation()); - Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); - if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) { - context.faction.setCheckpoint(context.player.getLocation()); - context.msg(TL.COMMAND_CHECKPOINT_SET); - return; - } else { - context.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION); - return; - } - } - if (context.faction.getCheckpoint() == null) { - context.msg(TL.COMMAND_CHECKPOINT_NOT_SET); - return; - } - FLocation checkLocation = new FLocation(context.faction.getCheckpoint()); - Faction checkfaction = Board.getInstance().getFactionAt(checkLocation); + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("checkpoints.Enabled")) { + context.msg(TL.COMMAND_CHECKPOINT_DISABLED); + return; + } + if (context.args.size() == 1) { + FLocation myLocation = new FLocation(context.player.getLocation()); + Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); + if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == context.faction) { + context.faction.setCheckpoint(context.player.getLocation()); + context.msg(TL.COMMAND_CHECKPOINT_SET); + return; + } else { + context.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION); + return; + } + } + if (context.faction.getCheckpoint() == null) { + context.msg(TL.COMMAND_CHECKPOINT_NOT_SET); + return; + } + FLocation checkLocation = new FLocation(context.faction.getCheckpoint()); + Faction checkfaction = Board.getInstance().getFactionAt(checkLocation); - if (checkfaction.getId().equals(Factions.getInstance().getWilderness().getId()) || checkfaction.getId().equals(context.faction.getId())) { - context.msg(TL.COMMAND_CHECKPOINT_GO); + if (checkfaction.getId().equals(Factions.getInstance().getWilderness().getId()) || checkfaction.getId().equals(context.faction.getId())) { + context.msg(TL.COMMAND_CHECKPOINT_GO); - context.doWarmUp(WarmUpUtil.Warmup.CHECKPOINT, TL.WARMUPS_NOTIFY_TELEPORT, "Checkpoint", () -> { - context.player.teleport(context.faction.getCheckpoint()); - }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-checkpoint", 0)); - } else { - context.msg(TL.COMMAND_CHECKPOINT_CLAIMED); - } + context.doWarmUp(WarmUpUtil.Warmup.CHECKPOINT, TL.WARMUPS_NOTIFY_TELEPORT, "Checkpoint", () -> { + context.player.teleport(context.faction.getCheckpoint()); + }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-checkpoint", 0)); + } else { + context.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/CmdColeader.java b/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java index d19f84a3..f48dd495 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java @@ -10,78 +10,78 @@ 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("player name", "name"); - this.requirements = new CommandRequirements.Builder(Permission.COLEADER) - .memberOnly() - .withRole(Role.LEADER) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.COLEADER) + .memberOnly() + .withRole(Role.LEADER) + .build(); + } - @Override - public void perform(CommandContext context) { - FPlayer you = context.argAsBestFPlayerMatch(0); - if (you == null) { - FancyMessage msg = new FancyMessage(TL.COMMAND_COLEADER_CANDIDATES.toString()).color(ChatColor.GOLD); - for (FPlayer player : context.faction.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 : context.faction.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(CommandContext context) { + FPlayer you = context.argAsBestFPlayerMatch(0); + if (you == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_COLEADER_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : context.faction.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 : context.faction.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); + } - context.sendFancyMessage(msg); - return; - } + context.sendFancyMessage(msg); + return; + } - boolean permAny = Permission.COLEADER_ANY.has(context.sender, false); - Faction targetFaction = you.getFaction(); + boolean permAny = Permission.COLEADER_ANY.has(context.sender, false); + Faction targetFaction = you.getFaction(); - if (targetFaction != context.faction && !permAny) { - context.msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(context.fPlayer, true)); - return; - } + if (targetFaction != context.faction && !permAny) { + context.msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(context.fPlayer, true)); + return; + } - if (context.fPlayer != null && context.fPlayer.getRole() != Role.LEADER && !permAny) { - context.msg(TL.COMMAND_COLEADER_NOTADMIN); - return; - } + if (context.fPlayer != null && context.fPlayer.getRole() != Role.LEADER && !permAny) { + context.msg(TL.COMMAND_COLEADER_NOTADMIN); + return; + } - if (you == context.fPlayer && !permAny) { - context.msg(TL.COMMAND_COLEADER_SELF); - return; - } + if (you == context.fPlayer && !permAny) { + context.msg(TL.COMMAND_COLEADER_SELF); + return; + } - if (you.getRole() == Role.LEADER) { - context.msg(TL.COMMAND_COLEADER_TARGETISADMIN); - return; - } + if (you.getRole() == Role.LEADER) { + context.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)); - context.msg(TL.COMMAND_COLEADER_REVOKES, you.describeTo(context.fPlayer, true)); - } else { - // Give - you.setRole(Role.COLEADER); - targetFaction.msg(TL.COMMAND_COLEADER_PROMOTED, you.describeTo(targetFaction, true)); - context.msg(TL.COMMAND_COLEADER_PROMOTES, you.describeTo(context.fPlayer, true)); - } - } + if (you.getRole() == Role.COLEADER) { + // Revoke + you.setRole(Role.MODERATOR); + targetFaction.msg(TL.COMMAND_COLEADER_REVOKED, you.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_COLEADER_REVOKES, you.describeTo(context.fPlayer, true)); + } else { + // Give + you.setRole(Role.COLEADER); + targetFaction.msg(TL.COMMAND_COLEADER_PROMOTED, you.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_COLEADER_PROMOTES, you.describeTo(context.fPlayer, 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 ea1a9824..816b471c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java @@ -16,228 +16,228 @@ 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.requiredArgs.add("setting"); + this.requiredArgs.add("value"); - this.requirements = new CommandRequirements.Builder(Permission.CONFIG) - .noErrorOnManyArgs() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CONFIG) + .noErrorOnManyArgs() + .build(); + } - @Override - public void perform(CommandContext context) { - // 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(CommandContext context) { + // 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 = context.argAsString(0).toLowerCase(); - if (field.startsWith("\"") && field.endsWith("\"")) { - field = field.substring(1, field.length() - 1); - } - String fieldName = properFieldNames.get(field); + String field = context.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()) { - context.msg(TL.COMMAND_CONFIG_NOEXIST, field); - return; - } + if (fieldName == null || fieldName.isEmpty()) { + context.msg(TL.COMMAND_CONFIG_NOEXIST, field); + return; + } - String success; + String success; - StringBuilder value = new StringBuilder(context.args.get(1)); - for (int i = 2; i < context.args.size(); i++) { - value.append(' ').append(context.args.get(i)); - } + StringBuilder value = new StringBuilder(context.args.get(1)); + for (int i = 2; i < context.args.size(); i++) { + value.append(' ').append(context.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 = context.strAsBool(value.toString()); - target.setBoolean(null, targetValue); + // boolean + if (target.getType() == boolean.class) { + boolean targetValue = context.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) { - context.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) { - context.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) { - context.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) { - context.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 + "\"."; - } - - // ChatColor - else if (target.getType() == ChatColor.class) { - ChatColor newColor = null; - try { - newColor = ChatColor.valueOf(value.toString().toUpperCase()); - } catch (IllegalArgumentException ex) { - - } - if (newColor == null) { - context.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]; - - // not a Set, somehow, and that should be the only collection we're using in Conf.java - if (targSet.getRawType() != Set.class) { - context.sendMessage(TL.COMMAND_CONFIG_INVALID_COLLECTION.format(fieldName)); - return; - } - - // Set - else if (innerType == Material.class) { - Material newMat = null; + // int + else if (target.getType() == int.class) { try { - newMat = Material.valueOf(value.toString().toUpperCase()); + int intVal = Integer.parseInt(value.toString()); + target.setInt(null, intVal); + success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + intVal + "."; + } catch (NumberFormatException ex) { + context.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) { + context.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) { + context.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) { + context.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 + "\"."; + } + + // ChatColor + else if (target.getType() == ChatColor.class) { + ChatColor newColor = null; + try { + newColor = ChatColor.valueOf(value.toString().toUpperCase()); } catch (IllegalArgumentException ex) { } - if (newMat == null) { - context.sendMessage(TL.COMMAND_CONFIG_INVALID_MATERIAL.format(fieldName, value.toString().toUpperCase())); - return; + if (newColor == null) { + context.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]; + + // not a Set, somehow, and that should be the only collection we're using in Conf.java + if (targSet.getRawType() != Set.class) { + context.sendMessage(TL.COMMAND_CONFIG_INVALID_COLLECTION.format(fieldName)); + return; } - @SuppressWarnings("unchecked") Set matSet = (Set) target.get(null); + // Set + else if (innerType == Material.class) { + Material newMat = null; + try { + newMat = Material.valueOf(value.toString().toUpperCase()); + } catch (IllegalArgumentException ex) { - // 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()); + } + if (newMat == null) { + context.sendMessage(TL.COMMAND_CONFIG_INVALID_MATERIAL.format(fieldName, value.toString().toUpperCase())); + return; + } + + @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 not present yet, add it + + // 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()); + } + } + + // Set of unknown type else { - matSet.add(newMat); - target.set(null, matSet); - success = TL.COMMAND_CONFIG_MATERIAL_ADDED.format(fieldName, value.toString().toUpperCase()); + context.sendMessage(TL.COMMAND_CONFIG_INVALID_TYPESET.format(fieldName)); + return; } - } + } - // 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()); - } - } - - // Set of unknown type - else { - context.sendMessage(TL.COMMAND_CONFIG_INVALID_TYPESET.format(fieldName)); + // unknown type + else { + context.sendMessage(TL.COMMAND_CONFIG_ERROR_TYPE.format(fieldName, target.getClass().getName())); return; - } - } + } + } catch (NoSuchFieldException ex) { + context.sendMessage(TL.COMMAND_CONFIG_ERROR_MATCHING.format(fieldName)); + return; + } catch (IllegalAccessException ex) { + context.sendMessage(TL.COMMAND_CONFIG_ERROR_SETTING.format(fieldName, value.toString())); + return; + } - // unknown type - else { - context.sendMessage(TL.COMMAND_CONFIG_ERROR_TYPE.format(fieldName, target.getClass().getName())); - return; - } - } catch (NoSuchFieldException ex) { - context.sendMessage(TL.COMMAND_CONFIG_ERROR_MATCHING.format(fieldName)); - return; - } catch (IllegalAccessException ex) { - context.sendMessage(TL.COMMAND_CONFIG_ERROR_SETTING.format(fieldName, value.toString())); - return; - } + if (!success.isEmpty()) { + if (context.sender instanceof Player) { + context.sendMessage(success); + FactionsPlugin.getInstance().log(success + TL.COMMAND_CONFIG_LOG.format((Player) context.sender)); + } else // using FactionsPlugin.getInstance().log() instead of sendMessage if run from server console so that "[Factions v#.#.#]" is prepended in server log + { + FactionsPlugin.getInstance().log(success); + } + } + // save change to disk + Conf.save(); + } - if (!success.isEmpty()) { - if (context.sender instanceof Player) { - context.sendMessage(success); - FactionsPlugin.getInstance().log(success + TL.COMMAND_CONFIG_LOG.format((Player) context.sender)); - } else // using FactionsPlugin.getInstance().log() instead of sendMessage if run from server console so that "[Factions v#.#.#]" is prepended in server log - { - FactionsPlugin.getInstance().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 b7a55a2e..ab51517c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdConvert.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdConvert.java @@ -9,36 +9,36 @@ import org.bukkit.command.ConsoleCommandSender; public class CmdConvert extends FCommand { - public CmdConvert() { - this.aliases.add("convert"); - this.requiredArgs.add("[MYSQL|JSON]"); + public CmdConvert() { + this.aliases.add("convert"); + this.requiredArgs.add("[MYSQL|JSON]"); - this.requirements = new CommandRequirements.Builder(Permission.CONVERT) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CONVERT) + .build(); + } - @Override - public void perform(CommandContext context) { - if (!(context.sender instanceof ConsoleCommandSender)) { - context.sender.sendMessage(TL.GENERIC_CONSOLEONLY.toString()); - } - Backend nb = Backend.valueOf(context.argAsString(0).toUpperCase()); - if (nb == Conf.backEnd) { - context.sender.sendMessage(TL.COMMAND_CONVERT_BACKEND_RUNNING.toString()); - return; - } - if (nb == Backend.JSON) { - FactionsJSON.convertTo(); - } else { - context.sender.sendMessage(TL.COMMAND_CONVERT_BACKEND_INVALID.toString()); - return; - } - Conf.backEnd = nb; - } + @Override + public void perform(CommandContext context) { + if (!(context.sender instanceof ConsoleCommandSender)) { + context.sender.sendMessage(TL.GENERIC_CONSOLEONLY.toString()); + } + Backend nb = Backend.valueOf(context.argAsString(0).toUpperCase()); + if (nb == Conf.backEnd) { + context.sender.sendMessage(TL.COMMAND_CONVERT_BACKEND_RUNNING.toString()); + return; + } + if (nb == Backend.JSON) { + FactionsJSON.convertTo(); + } else { + context.sender.sendMessage(TL.COMMAND_CONVERT_BACKEND_INVALID.toString()); + return; + } + Conf.backEnd = nb; + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CONVERT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CONVERT_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java b/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java index 33aae200..c47bc08f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java @@ -7,31 +7,31 @@ 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.requirements = new CommandRequirements.Builder(Permission.COORD) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.COORD) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Location location = context.player.getLocation(); - String message = TL.COMMAND_COORDS_MESSAGE.toString().replace("{player}", context.player.getDisplayName()).replace("{x}", (int) location.getX() + "") - .replace("{y}", (int) location.getY() + "").replace("{z}", (int) location.getZ() + "").replace("{world}", location.getWorld().getName()); - for (FPlayer fPlayer : context.faction.getFPlayers()) { - fPlayer.sendMessage(message); - } - } + @Override + public void perform(CommandContext context) { + Location location = context.player.getLocation(); + String message = TL.COMMAND_COORDS_MESSAGE.toString().replace("{player}", context.player.getDisplayName()).replace("{x}", (int) location.getX() + "") + .replace("{y}", (int) location.getY() + "").replace("{z}", (int) location.getZ() + "").replace("{world}", location.getWorld().getName()); + for (FPlayer fPlayer : context.faction.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 a38b5833..00969504 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java @@ -15,94 +15,94 @@ 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.requiredArgs.add("faction tag"); - this.requirements = new CommandRequirements.Builder(Permission.CREATE) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CREATE) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - String tag = context.argAsString(0); + @Override + public void perform(CommandContext context) { + String tag = context.argAsString(0); - if (context.fPlayer.hasFaction()) { - context.msg(TL.COMMAND_CREATE_MUSTLEAVE); - return; - } + if (context.fPlayer.hasFaction()) { + context.msg(TL.COMMAND_CREATE_MUSTLEAVE); + return; + } - if (Factions.getInstance().isTagTaken(tag)) { - context.msg(TL.COMMAND_CREATE_INUSE); - return; - } + if (Factions.getInstance().isTagTaken(tag)) { + context.msg(TL.COMMAND_CREATE_INUSE); + return; + } - ArrayList tagValidationErrors = MiscUtil.validateTag(tag); - if (tagValidationErrors.size() > 0) { - context.sendMessage(tagValidationErrors); - return; - } + ArrayList tagValidationErrors = MiscUtil.validateTag(tag); + if (tagValidationErrors.size() > 0) { + context.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 (!context.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 (!context.canAffordCommand(Conf.econCostCreate, TL.COMMAND_CREATE_TOCREATE.toString())) { + return; + } - // trigger the faction creation event (cancellable) - FactionCreateEvent createEvent = new FactionCreateEvent(context.player, tag); - Bukkit.getServer().getPluginManager().callEvent(createEvent); - if (createEvent.isCancelled()) { - return; - } + // trigger the faction creation event (cancellable) + FactionCreateEvent createEvent = new FactionCreateEvent(context.player, tag); + Bukkit.getServer().getPluginManager().callEvent(createEvent); + if (createEvent.isCancelled()) { + return; + } - // then make 'em pay (if applicable) - if (!context.payForCommand(Conf.econCostCreate, TL.COMMAND_CREATE_TOCREATE, TL.COMMAND_CREATE_FORCREATE)) { - return; - } + // then make 'em pay (if applicable) + if (!context.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) { - context.msg(TL.COMMAND_CREATE_ERROR); - return; - } + // TODO: Why would this even happen??? Auto increment clash?? + if (faction == null) { + context.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(context.player), 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(context.player), 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 - context.fPlayer.setFaction(faction, false); - // 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. - context.fPlayer.setRole(Role.LEADER); - if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-creation-broadcast", true)) { - for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { - follower.msg(TL.COMMAND_CREATE_CREATED, context.fPlayer.getName(), faction.getTag(follower)); - } - } - context.msg(TL.COMMAND_CREATE_YOUSHOULD, FactionsPlugin.getInstance().cmdBase.cmdDescription.getUseageTemplate(context)); - if (Conf.econEnabled) Econ.setBalance(faction.getAccountId(), Conf.econFactionStartingBalance); - if (Conf.logFactionCreate) - FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_CREATE_CREATEDLOG.toString() + tag); - if (FactionsPlugin.getInstance().getConfig().getBoolean("fpaypal.Enabled")) - context.msg(TL.COMMAND_PAYPALSET_CREATED); - if (Conf.useCustomDefaultPermissions) faction.setDefaultPerms(); - if (Conf.usePermissionHints) context.msg(TL.COMMAND_HINT_PERMISSION); - } + // finish setting up the FPlayer + context.fPlayer.setFaction(faction, false); + // 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. + context.fPlayer.setRole(Role.LEADER); + if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-creation-broadcast", true)) { + for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { + follower.msg(TL.COMMAND_CREATE_CREATED, context.fPlayer.getName(), faction.getTag(follower)); + } + } + context.msg(TL.COMMAND_CREATE_YOUSHOULD, FactionsPlugin.getInstance().cmdBase.cmdDescription.getUseageTemplate(context)); + if (Conf.econEnabled) Econ.setBalance(faction.getAccountId(), Conf.econFactionStartingBalance); + if (Conf.logFactionCreate) + FactionsPlugin.getInstance().log(context.fPlayer.getName() + TL.COMMAND_CREATE_CREATEDLOG.toString() + tag); + if (FactionsPlugin.getInstance().getConfig().getBoolean("fpaypal.Enabled")) + context.msg(TL.COMMAND_PAYPALSET_CREATED); + if (Conf.useCustomDefaultPermissions) faction.setDefaultPerms(); + if (Conf.usePermissionHints) context.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 284e5283..b8642f6d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java @@ -14,71 +14,71 @@ 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("player name", "name"); - this.requirements = new CommandRequirements.Builder(Permission.DEINVITE) - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.DEINVITE) + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { + @Override + public void perform(CommandContext context) { - // Check if arg 0 == null do you don't have - // `No player "null" could be found.` message. - if (context.args.get(0) == null) { - FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD); - for (String id : context.faction.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); - } - context.sendFancyMessage(msg); - return; - } + // Check if arg 0 == null do you don't have + // `No player "null" could be found.` message. + if (context.args.get(0) == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD); + for (String id : context.faction.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); + } + context.sendFancyMessage(msg); + return; + } - FPlayer you = context.argAsBestFPlayerMatch(0); - if (!context.fPlayer.isAdminBypassing()) { - Access access = context.faction.getAccess(context.fPlayer, PermissableAction.INVITE); - if (access != Access.ALLOW && context.fPlayer.getRole() != Role.LEADER) { - context.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage invites"); - return; - } - } + FPlayer you = context.argAsBestFPlayerMatch(0); + if (!context.fPlayer.isAdminBypassing()) { + Access access = context.faction.getAccess(context.fPlayer, PermissableAction.INVITE); + if (access != Access.ALLOW && context.fPlayer.getRole() != Role.LEADER) { + context.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 : context.faction.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); - } - context.sendFancyMessage(msg); - return; - } + if (you == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD); + for (String id : context.faction.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); + } + context.sendFancyMessage(msg); + return; + } - if (you.getFaction() == context.faction) { - context.msg(TL.COMMAND_DEINVITE_ALREADYMEMBER, you.getName(), context.faction.getTag()); - context.msg(TL.COMMAND_DEINVITE_MIGHTWANT, FactionsPlugin.getInstance().cmdBase.cmdKick.getUseageTemplate(context)); - return; - } + if (you.getFaction() == context.faction) { + context.msg(TL.COMMAND_DEINVITE_ALREADYMEMBER, you.getName(), context.faction.getTag()); + context.msg(TL.COMMAND_DEINVITE_MIGHTWANT, FactionsPlugin.getInstance().cmdBase.cmdKick.getUseageTemplate(context)); + return; + } - context.faction.deinvite(you); + context.faction.deinvite(you); - you.msg(TL.COMMAND_DEINVITE_REVOKED, context.fPlayer.describeTo(you), context.faction.describeTo(you)); + you.msg(TL.COMMAND_DEINVITE_REVOKED, context.fPlayer.describeTo(you), context.faction.describeTo(you)); - context.faction.msg(TL.COMMAND_DEINVITE_REVOKES, context.fPlayer.describeTo(context.faction), you.describeTo(context.faction)); - } + context.faction.msg(TL.COMMAND_DEINVITE_REVOKES, context.fPlayer.describeTo(context.faction), you.describeTo(context.faction)); + } - @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 7f9f2b4f..298309b3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDelFWarp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDelFWarp.java @@ -7,40 +7,40 @@ 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"); + public CmdDelFWarp() { + super(); + this.aliases.add("delwarp"); + this.aliases.add("dw"); + this.aliases.add("deletewarp"); + this.requiredArgs.add("warp name"); - this.requirements = new CommandRequirements.Builder(Permission.SETWARP) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETWARP) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - String warp = context.argAsString(0); - if (context.faction.isWarp(warp)) { - if (!transact(context.fPlayer, context)) { - return; - } - context.faction.removeWarp(warp); - context.msg(TL.COMMAND_DELFWARP_DELETED, warp); - } else { - context.msg(TL.COMMAND_DELFWARP_INVALID, warp); - } - } + @Override + public void perform(CommandContext context) { + String warp = context.argAsString(0); + if (context.faction.isWarp(warp)) { + if (!transact(context.fPlayer, context)) { + return; + } + context.faction.removeWarp(warp); + context.msg(TL.COMMAND_DELFWARP_DELETED, warp); + } else { + context.msg(TL.COMMAND_DELFWARP_INVALID, warp); + } + } - private boolean transact(FPlayer player, CommandContext context) { - return !FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().getConfig().getDouble("warp-cost.delwarp", 5), TL.COMMAND_DELFWARP_TODELETE.toString(), TL.COMMAND_DELFWARP_FORDELETE.toString()); - } + private boolean transact(FPlayer player, CommandContext context) { + return !FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().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/CmdDescription.java b/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java index c8142268..073e1a84 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java @@ -9,47 +9,47 @@ 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.requiredArgs.add("desc"); - this.requirements = new CommandRequirements.Builder(Permission.DESCRIPTION) - .playerOnly() - .memberOnly() - .noErrorOnManyArgs() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.DESCRIPTION) + .playerOnly() + .memberOnly() + .noErrorOnManyArgs() + .build(); + } - @Override - public void perform(CommandContext context) { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!context.payForCommand(Conf.econCostDesc, TL.COMMAND_DESCRIPTION_TOCHANGE, TL.COMMAND_DESCRIPTION_FORCHANGE)) { - return; - } + @Override + public void perform(CommandContext context) { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(Conf.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. - context.faction.setDescription(TextUtil.implode(context.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. + context.faction.setDescription(TextUtil.implode(context.args, " ").replaceAll("%", "").replaceAll("(&([a-f0-9klmnor]))", "& $2")); - if (!Conf.broadcastDescriptionChanges) { - context.msg(TL.COMMAND_DESCRIPTION_CHANGED, context.faction.describeTo(context.fPlayer)); - context.sendMessage(context.faction.getDescription()); - return; - } + if (!Conf.broadcastDescriptionChanges) { + context.msg(TL.COMMAND_DESCRIPTION_CHANGED, context.faction.describeTo(context.fPlayer)); + context.sendMessage(context.faction.getDescription()); + return; + } - // Broadcast the description to everyone - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - fplayer.msg(TL.COMMAND_DESCRIPTION_CHANGES, context.faction.describeTo(fplayer)); - fplayer.sendMessage(context.faction.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, context.faction.describeTo(fplayer)); + fplayer.sendMessage(context.faction.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; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java index 68b783cd..ee9badb9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java @@ -17,85 +17,85 @@ 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.optionalArgs.put("faction tag", "yours"); + this.optionalArgs.put("faction tag", "yours"); - this.requirements = new CommandRequirements.Builder(Permission.DISBAND) - .build(); + this.requirements = new CommandRequirements.Builder(Permission.DISBAND) + .build(); - } + } - @Override - public void perform(CommandContext context) { - // The faction, default to your own.. but null if console sender. - Faction faction = context.argAsFaction(0, context.fPlayer == null ? null : context.faction); - if (faction == null) return; + @Override + public void perform(CommandContext context) { + // The faction, default to your own.. but null if console sender. + Faction faction = context.argAsFaction(0, context.fPlayer == null ? null : context.faction); + if (faction == null) return; - boolean isMyFaction = context.fPlayer != null && faction == context.faction; + boolean isMyFaction = context.fPlayer != null && faction == context.faction; - if (!isMyFaction) { - if (!Permission.DISBAND_ANY.has(context.sender, true)) { - return; - } - } + if (!isMyFaction) { + if (!Permission.DISBAND_ANY.has(context.sender, true)) { + return; + } + } - if (context.fPlayer != null && !context.fPlayer.isAdminBypassing()) { - Access access = faction.getAccess(context.fPlayer, PermissableAction.DISBAND); - if (context.fPlayer.getRole() != Role.LEADER && faction.getFPlayerLeader() != context.fPlayer && access != Access.ALLOW) { - context.msg(TL.GENERIC_FPERM_NOPERMISSION, "disband " + faction.getTag()); - return; - } - } + if (context.fPlayer != null && !context.fPlayer.isAdminBypassing()) { + Access access = faction.getAccess(context.fPlayer, PermissableAction.DISBAND); + if (context.fPlayer.getRole() != Role.LEADER && faction.getFPlayerLeader() != context.fPlayer && access != Access.ALLOW) { + context.msg(TL.GENERIC_FPERM_NOPERMISSION, "disband " + faction.getTag()); + return; + } + } - if (!faction.isNormal()) { - context.msg(TL.COMMAND_DISBAND_IMMUTABLE.toString()); - return; - } - if (faction.isPermanent()) { - context.msg(TL.COMMAND_DISBAND_MARKEDPERMANENT.toString()); - return; - } + if (!faction.isNormal()) { + context.msg(TL.COMMAND_DISBAND_IMMUTABLE.toString()); + return; + } + if (faction.isPermanent()) { + context.msg(TL.COMMAND_DISBAND_MARKEDPERMANENT.toString()); + return; + } - // THis means they are a console command sender. - if (context.player == null) { - faction.disband(null, PlayerDisbandReason.PLUGIN); - return; - } + // THis means they are a console command sender. + if (context.player == null) { + faction.disband(null, PlayerDisbandReason.PLUGIN); + return; + } - // check for tnt before disbanding. - if (!disbandMap.containsKey(context.player.getUniqueId().toString()) && faction.getTnt() > 0) { - context.msg(TL.COMMAND_DISBAND_CONFIRM.toString().replace("{tnt}", faction.getTnt() + "")); - disbandMap.put(context.player.getUniqueId().toString(), faction.getId()); - Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> disbandMap.remove(context.player.getUniqueId().toString()), 200L); - } else if (faction.getId().equals(disbandMap.get(context.player.getUniqueId().toString())) || faction.getTnt() == 0) { - if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-disband-broadcast", true)) { - for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { - String amountString = context.sender instanceof ConsoleCommandSender ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(follower); - UtilFly.checkFly(context.fPlayer, 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)); + // check for tnt before disbanding. + if (!disbandMap.containsKey(context.player.getUniqueId().toString()) && faction.getTnt() > 0) { + context.msg(TL.COMMAND_DISBAND_CONFIRM.toString().replace("{tnt}", faction.getTnt() + "")); + disbandMap.put(context.player.getUniqueId().toString(), faction.getId()); + Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> disbandMap.remove(context.player.getUniqueId().toString()), 200L); + } else if (faction.getId().equals(disbandMap.get(context.player.getUniqueId().toString())) || faction.getTnt() == 0) { + if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-disband-broadcast", true)) { + for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { + String amountString = context.sender instanceof ConsoleCommandSender ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(follower); + UtilFly.checkFly(context.fPlayer, 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(context.player, PlayerDisbandReason.COMMAND); - } else { - faction.disband(context.player, PlayerDisbandReason.COMMAND); - context.player.sendMessage(String.valueOf(TL.COMMAND_DISBAND_PLAYER)); - } - } - } + faction.disband(context.player, PlayerDisbandReason.COMMAND); + } else { + faction.disband(context.player, PlayerDisbandReason.COMMAND); + context.player.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/CmdFGlobal.java b/src/main/java/com/massivecraft/factions/cmd/CmdFGlobal.java index 8fee8817..b2f87c3d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFGlobal.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFGlobal.java @@ -9,36 +9,36 @@ import java.util.UUID; public class CmdFGlobal extends FCommand { - public static List toggled = new ArrayList<>(); + public static List toggled = new ArrayList<>(); - public CmdFGlobal() { - super(); - this.aliases.add("gchat"); - this.aliases.add("global"); - this.aliases.add("globalchat"); + public CmdFGlobal() { + super(); + this.aliases.add("gchat"); + this.aliases.add("global"); + this.aliases.add("globalchat"); - this.requirements = new CommandRequirements.Builder(Permission.GLOBALCHAT) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.GLOBALCHAT) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - // /f global + @Override + public void perform(CommandContext context) { + // /f global - if (toggled.contains(context.player.getUniqueId())) { - toggled.remove(context.player.getUniqueId()); - } else { - toggled.add(context.player.getUniqueId()); - } + if (toggled.contains(context.player.getUniqueId())) { + toggled.remove(context.player.getUniqueId()); + } else { + toggled.add(context.player.getUniqueId()); + } - context.msg(TL.COMMAND_F_GLOBAL_TOGGLE, toggled.contains(context.player.getUniqueId()) ? "disabled" : "enabled"); - } + context.msg(TL.COMMAND_F_GLOBAL_TOGGLE, toggled.contains(context.player.getUniqueId()) ? "disabled" : "enabled"); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_F_GLOBAL_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_F_GLOBAL_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdFWarp.java b/src/main/java/com/massivecraft/factions/cmd/CmdFWarp.java index 19c38699..ea6402cd 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFWarp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFWarp.java @@ -14,63 +14,63 @@ 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.requirements = new CommandRequirements.Builder(Permission.WARP) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.WARP) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.WARP) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.WARP) + .build(); + } - @Override - public void perform(CommandContext context) { + @Override + public void perform(CommandContext context) { - if (context.args.size() == 0) { - new FactionWarpsFrame(context.faction).buildGUI(context.fPlayer); - } else if (context.args.size() > 2) { - context.msg(TL.COMMAND_FWARP_COMMANDFORMAT); - } else { - final String warpName = context.argAsString(0); - final String passwordAttempt = context.argAsString(1); + if (context.args.size() == 0) { + new FactionWarpsFrame(context.faction).buildGUI(context.fPlayer); + } else if (context.args.size() > 2) { + context.msg(TL.COMMAND_FWARP_COMMANDFORMAT); + } else { + final String warpName = context.argAsString(0); + final String passwordAttempt = context.argAsString(1); - if (context.faction.isWarp(context.argAsString(0))) { + if (context.faction.isWarp(context.argAsString(0))) { - // Check if requires password and if so, check if valid. CASE SENSITIVE - if (context.faction.hasWarpPassword(warpName) && !context.faction.isWarpPassword(warpName, passwordAttempt)) { - context.faction.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); - return; - } - - // Check transaction AFTER password check. - if (!transact(context.fPlayer, context)) return; - - final FPlayer fPlayer = context.fPlayer; - final UUID uuid = context.player.getUniqueId(); - context.doWarmUp(WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warpName, () -> { - Player player = Bukkit.getPlayer(uuid); - if (player != null) { - player.teleport(fPlayer.getFaction().getWarp(warpName).getLocation()); - fPlayer.msg(TL.COMMAND_FWARP_WARPED, warpName); + // Check if requires password and if so, check if valid. CASE SENSITIVE + if (context.faction.hasWarpPassword(warpName) && !context.faction.isWarpPassword(warpName, passwordAttempt)) { + context.faction.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); + return; } - }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-warp", 0)); - } else { - context.msg(TL.COMMAND_FWARP_INVALID_WARP, warpName); - } - } - } - private boolean transact(FPlayer player, CommandContext context) { - return !FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().getConfig().getDouble("warp-cost.warp", 5), TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); - } + // Check transaction AFTER password check. + if (!transact(context.fPlayer, context)) return; - @Override - public TL getUsageTranslation() { - return TL.COMMAND_FWARP_DESCRIPTION; - } + final FPlayer fPlayer = context.fPlayer; + final UUID uuid = context.player.getUniqueId(); + context.doWarmUp(WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warpName, () -> { + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + player.teleport(fPlayer.getFaction().getWarp(warpName).getLocation()); + fPlayer.msg(TL.COMMAND_FWARP_WARPED, warpName); + } + }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-warp", 0)); + } else { + context.msg(TL.COMMAND_FWARP_INVALID_WARP, warpName); + } + } + } + + private boolean transact(FPlayer player, CommandContext context) { + return !FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().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; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdFly.java b/src/main/java/com/massivecraft/factions/cmd/CmdFly.java index a5df7056..b3e36d65 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFly.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFly.java @@ -19,186 +19,186 @@ 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"); - this.optionalArgs.put("on/off", "flip"); + public CmdFly() { + super(); + this.aliases.add("fly"); + this.optionalArgs.put("on/off", "flip"); - this.requirements = new CommandRequirements.Builder(Permission.FLY) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.FLY) + .playerOnly() + .memberOnly() + .build(); + } - public static void startParticles() { + public static void startParticles() { - id = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { - for (String name : flyMap.keySet()) { - Player player = Bukkit.getPlayer(name); - if (player == null) continue; - if (!player.isFlying()) continue; - if (!FactionsPlugin.getInstance().mc17) { - if (player.getGameMode() == GameMode.SPECTATOR) continue; - } - - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - fplayer.isVanished(); - - } - if (flyMap.keySet().size() == 0) { - Bukkit.getScheduler().cancelTask(id); - id = -1; - } - }, 10L, 3L); - } - - public static void startFlyCheck() { - flyid = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { //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; - } + id = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { + for (String name : flyMap.keySet()) { Player player = Bukkit.getPlayer(name); - if (player == null - || !player.isFlying() - || player.getGameMode() == GameMode.CREATIVE - || !FactionsPlugin.getInstance().mc17 && player.getGameMode() == GameMode.SPECTATOR) { - continue; - } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - Faction myFaction = fPlayer.getFaction(); - if (myFaction.isWilderness()) { - fPlayer.setFlying(false); - flyMap.remove(name); - continue; - } - if (player.hasPermission("factions.fly.bypassnearbyenemycheck") || fPlayer.checkIfNearbyEnemies()) { - continue; - } - FLocation myFloc = new FLocation(player.getLocation()); - if (Board.getInstance().getFactionAt(myFloc) != myFaction) { - if (!checkBypassPerms(fPlayer, player, Board.getInstance().getFactionAt(myFloc))) { - fPlayer.setFlying(false); - flyMap.remove(name); - } + if (player == null) continue; + if (!player.isFlying()) continue; + if (!FactionsPlugin.getInstance().mc17) { + if (player.getGameMode() == GameMode.SPECTATOR) continue; } - } - } + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + fplayer.isVanished(); - }, 20L, 20L); - } + } + if (flyMap.keySet().size() == 0) { + Bukkit.getScheduler().cancelTask(id); + id = -1; + } + }, 10L, 3L); + } - 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; - } + public static void startFlyCheck() { + flyid = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { //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 + || !player.isFlying() + || player.getGameMode() == GameMode.CREATIVE + || !FactionsPlugin.getInstance().mc17 && player.getGameMode() == GameMode.SPECTATOR) { + continue; + } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + Faction myFaction = fPlayer.getFaction(); + if (myFaction.isWilderness()) { + fPlayer.setFlying(false); + flyMap.remove(name); + continue; + } + if (player.hasPermission("factions.fly.bypassnearbyenemycheck") || fPlayer.checkIfNearbyEnemies()) { + continue; + } + FLocation myFloc = new FLocation(player.getLocation()); + if (Board.getInstance().getFactionAt(myFloc) != myFaction) { + if (!checkBypassPerms(fPlayer, player, Board.getInstance().getFactionAt(myFloc))) { + fPlayer.setFlying(false); + flyMap.remove(name); + } + } - 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(); - } + }, 20L, 20L); + } - public static void checkTaskState() { - if (flyMap.keySet().size() == 0) { - Bukkit.getScheduler().cancelTask(flyid); - flyid = -1; - } - } + 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; + } - public static void disableFlight(final FPlayer fme) { - fme.setFlying(false); - flyMap.remove(fme.getPlayer().getName()); - } + 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 boolean isInFlightChecker(Player player) { - return flyMap.containsKey(player.getName()); - } + public static Boolean isSystemFaction(Faction faction) { + return faction.isSafeZone() || + faction.isWarZone() || + faction.isWilderness(); + } - @Override - public void perform(CommandContext context) { - // Disabled by default. - if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight", false)) { - context.fPlayer.msg(TL.COMMAND_FLY_DISABLED); - return; - } + public static void checkTaskState() { + if (flyMap.keySet().size() == 0) { + Bukkit.getScheduler().cancelTask(flyid); + flyid = -1; + } + } - FLocation myfloc = new FLocation(context.player.getLocation()); - Faction toFac = Board.getInstance().getFactionAt(myfloc); - if (!checkBypassPerms(context.fPlayer, context.player, toFac)) return; - List entities = context.player.getNearbyEntities(16.0D, 256.0D, 16.0D); + public static void disableFlight(final FPlayer fme) { + fme.setFlying(false); + flyMap.remove(fme.getPlayer().getName()); + } - 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(context.fPlayer) == Relation.ENEMY && !efplayer.isStealthEnabled()) { - context.msg(TL.COMMAND_FLY_CHECK_ENEMY); - return; - } - } - } + public boolean isInFlightChecker(Player player) { + return flyMap.containsKey(player.getName()); + } + + @Override + public void perform(CommandContext context) { + // Disabled by default. + if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight", false)) { + context.fPlayer.msg(TL.COMMAND_FLY_DISABLED); + return; + } + + FLocation myfloc = new FLocation(context.player.getLocation()); + Faction toFac = Board.getInstance().getFactionAt(myfloc); + if (!checkBypassPerms(context.fPlayer, context.player, toFac)) return; + List entities = context.player.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(context.fPlayer) == Relation.ENEMY && !efplayer.isStealthEnabled()) { + context.msg(TL.COMMAND_FLY_CHECK_ENEMY); + return; + } + } + } - if (context.args.size() == 0) { - toggleFlight(context.fPlayer.isFlying(), context.fPlayer, context); - } else if (context.args.size() == 1) { - toggleFlight(context.argAsBool(0), context.fPlayer, context); - } - } + if (context.args.size() == 0) { + toggleFlight(context.fPlayer.isFlying(), context.fPlayer, context); + } else if (context.args.size() == 1) { + toggleFlight(context.argAsBool(0), context.fPlayer, context); + } + } - private void toggleFlight(final boolean toggle, final FPlayer fme, CommandContext context) { - if (toggle) { - fme.setFlying(false); - flyMap.remove(fme.getPlayer().getName()); - return; - } + private void toggleFlight(final boolean toggle, final FPlayer fme, CommandContext context) { + if (toggle) { + fme.setFlying(false); + flyMap.remove(fme.getPlayer().getName()); + return; + } - if (fme.canFlyAtLocation()) - context.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", () -> { - fme.setFlying(true); - flyMap.put(fme.getPlayer().getName(), true); - if (flyid == -1) { - startFlyCheck(); - } - }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-fly", 0)); - } + if (fme.canFlyAtLocation()) + context.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", () -> { + fme.setFlying(true); + flyMap.put(fme.getPlayer().getName(), true); + if (flyid == -1) { + startFlyCheck(); + } + }, FactionsPlugin.getInstance().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 56ce1f18..b014c55e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFocus.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFocus.java @@ -7,43 +7,43 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdFocus extends FCommand { - public CmdFocus() { - aliases.add("focus"); + public CmdFocus() { + aliases.add("focus"); - requiredArgs.add("player"); + requiredArgs.add("player"); - this.requirements = new CommandRequirements.Builder(Permission.FOCUS) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.FOCUS) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("ffocus.Enabled")) { - context.msg(TL.GENERIC_DISABLED); - return; - } - FPlayer target = context.argAsFPlayer(0); - if (target == null) { - return; - } - if (target.getFaction().getId().equalsIgnoreCase(context.faction.getId())) { - context.msg(TL.COMMAND_FOCUS_SAMEFACTION); - return; - } - if ((context.faction.getFocused() != null) && (context.faction.getFocused().equalsIgnoreCase(target.getName()))) { - context.faction.setFocused(null); - context.faction.msg(TL.COMMAND_FOCUS_NO_LONGER, target.getName()); - FTeamWrapper.updatePrefixes(target.getFaction()); - return; - } - context.faction.msg(TL.COMMAND_FOCUS_FOCUSING, target.getName()); - context.faction.setFocused(target.getName()); - FTeamWrapper.updatePrefixes(target.getFaction()); - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("ffocus.Enabled")) { + context.msg(TL.GENERIC_DISABLED); + return; + } + FPlayer target = context.argAsFPlayer(0); + if (target == null) { + return; + } + if (target.getFaction().getId().equalsIgnoreCase(context.faction.getId())) { + context.msg(TL.COMMAND_FOCUS_SAMEFACTION); + return; + } + if ((context.faction.getFocused() != null) && (context.faction.getFocused().equalsIgnoreCase(target.getName()))) { + context.faction.setFocused(null); + context.faction.msg(TL.COMMAND_FOCUS_NO_LONGER, target.getName()); + FTeamWrapper.updatePrefixes(target.getFaction()); + return; + } + context.faction.msg(TL.COMMAND_FOCUS_FOCUSING, target.getName()); + context.faction.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 eaf6c798..2c538296 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdGetVault.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdGetVault.java @@ -9,64 +9,64 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class CmdGetVault extends FCommand { - public CmdGetVault() { - super(); - this.aliases.add("getvault"); + public CmdGetVault() { + super(); + this.aliases.add("getvault"); - this.requirements = new CommandRequirements.Builder(Permission.GETVAULT) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.GETVAULT) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fvault.Enabled")) { - context.fPlayer.sendMessage("This command is disabled!"); - return; - } - Location vaultLocation = context.faction.getVault(); - ItemStack vault = FactionsPlugin.getInstance().createItem(Material.CHEST, 1, (short) 0, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fvault.Item.Name")), FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fvault.Item.Lore"))); + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fvault.Enabled")) { + context.fPlayer.sendMessage("This command is disabled!"); + return; + } + Location vaultLocation = context.faction.getVault(); + ItemStack vault = FactionsPlugin.getInstance().createItem(Material.CHEST, 1, (short) 0, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fvault.Item.Name")), FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fvault.Item.Lore"))); - //check if vault is set - if (vaultLocation != null) { - context.msg(TL.COMMAND_GETVAULT_ALREADYSET); - return; - } + //check if vault is set + if (vaultLocation != null) { + context.msg(TL.COMMAND_GETVAULT_ALREADYSET); + return; + } - //has enough money? - int amount = FactionsPlugin.getInstance().getConfig().getInt("fvault.Price"); - if (!context.fPlayer.hasMoney(amount)) { - return; - } + //has enough money? + int amount = FactionsPlugin.getInstance().getConfig().getInt("fvault.Price"); + if (!context.fPlayer.hasMoney(amount)) { + return; + } - //success :) - context.fPlayer.takeMoney(amount); - context.player.getInventory().addItem(vault); - context.fPlayer.msg(TL.COMMAND_GETVAULT_RECEIVE); + //success :) + context.fPlayer.takeMoney(amount); + context.player.getInventory().addItem(vault); + context.fPlayer.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 e1081b04..fb4067ab 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java @@ -13,201 +13,201 @@ 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.requirements = new CommandRequirements.Builder(Permission.HELP) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.HELP) + .build(); + } - //----------------------------------------------// - // Build the help pages - //----------------------------------------------// + //----------------------------------------------// + // Build the help pages + //----------------------------------------------// - @Override - public void perform(CommandContext context) { - if (FactionsPlugin.getInstance().getConfig().getBoolean("use-old-help", true)) { - if (helpPages == null) { - updateHelp(context); - } + @Override + public void perform(CommandContext context) { + if (FactionsPlugin.getInstance().getConfig().getBoolean("use-old-help", true)) { + if (helpPages == null) { + updateHelp(context); + } - int page = context.argAsInt(0, 1); - context.sendMessage(FactionsPlugin.getInstance().txt.titleize("Factions Help (" + page + "/" + helpPages.size() + ")")); + int page = context.argAsInt(0, 1); + context.sendMessage(FactionsPlugin.getInstance().txt.titleize("Factions Help (" + page + "/" + helpPages.size() + ")")); - page -= 1; + page -= 1; - if (page < 0 || page >= helpPages.size()) { - context.msg(TL.COMMAND_HELP_404.format(String.valueOf(page))); - return; - } - context.sendMessage(helpPages.get(page)); - return; - } - ConfigurationSection help = FactionsPlugin.getInstance().getConfig().getConfigurationSection("help"); - if (help == null) { - help = FactionsPlugin.getInstance().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 = context.argAsString(0, "1"); - List page = help.getStringList(pageArg); - if (page == null || page.isEmpty()) { - context.msg(TL.COMMAND_HELP_404.format(pageArg)); - return; - } - for (String helpLine : page) { - context.sendMessage(FactionsPlugin.getInstance().txt.parse(helpLine)); - } - } + if (page < 0 || page >= helpPages.size()) { + context.msg(TL.COMMAND_HELP_404.format(String.valueOf(page))); + return; + } + context.sendMessage(helpPages.get(page)); + return; + } + ConfigurationSection help = FactionsPlugin.getInstance().getConfig().getConfigurationSection("help"); + if (help == null) { + help = FactionsPlugin.getInstance().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 = context.argAsString(0, "1"); + List page = help.getStringList(pageArg); + if (page == null || page.isEmpty()) { + context.msg(TL.COMMAND_HELP_404.format(pageArg)); + return; + } + for (String helpLine : page) { + context.sendMessage(FactionsPlugin.getInstance().txt.parse(helpLine)); + } + } - public void updateHelp(CommandContext context) { - helpPages = new ArrayList<>(); - ArrayList pageLines; + public void updateHelp(CommandContext context) { + helpPages = new ArrayList<>(); + ArrayList pageLines; - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdHelp.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdList.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdShow.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPower.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdJoin.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdLeave.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdChat.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdToggleAllianceChat.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdHome.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_NEXTCREATE.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdHelp.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdList.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdShow.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPower.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdJoin.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdLeave.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdChat.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdToggleAllianceChat.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdHome.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_NEXTCREATE.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdCreate.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdDescription.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdTag.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_INVITATIONS.toString())); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdOpen.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdInvite.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdDeinvite.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_HOME.toString())); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSethome.getUseageTemplate(context)); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdCreate.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdDescription.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdTag.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_INVITATIONS.toString())); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdOpen.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdInvite.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdDeinvite.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_HOME.toString())); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSethome.getUseageTemplate(context)); + helpPages.add(pageLines); - if (Econ.isSetup() && Conf.econEnabled && Conf.bankEnabled) { - pageLines = new ArrayList<>(); - pageLines.add(""); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_BANK_1.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_BANK_2.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_BANK_3.toString())); - pageLines.add(""); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdMoney.getUseageTemplate(context)); - pageLines.add(""); - pageLines.add(""); - pageLines.add(""); - helpPages.add(pageLines); - } + if (Econ.isSetup() && Conf.econEnabled && Conf.bankEnabled) { + pageLines = new ArrayList<>(); + pageLines.add(""); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_BANK_1.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_BANK_2.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_BANK_3.toString())); + pageLines.add(""); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdMoney.getUseageTemplate(context)); + pageLines.add(""); + pageLines.add(""); + pageLines.add(""); + helpPages.add(pageLines); + } - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdClaim.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdAutoClaim.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdUnclaim.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdUnclaimall.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdKick.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdMod.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdAdmin.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdTitle.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSB.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSeeChunk.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdStatus.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PLAYERTITLES.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdClaim.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdAutoClaim.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdUnclaim.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdUnclaimall.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdKick.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdMod.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdAdmin.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdTitle.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSB.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSeeChunk.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdStatus.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PLAYERTITLES.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdMap.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdBoom.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdOwner.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdOwnerList.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_OWNERSHIP_1.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_OWNERSHIP_2.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_OWNERSHIP_3.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdMap.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdBoom.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdOwner.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdOwnerList.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_OWNERSHIP_1.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_OWNERSHIP_2.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_OWNERSHIP_3.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdDisband.getUseageTemplate(context)); - pageLines.add(""); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdRelationAlly.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdRelationNeutral.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdRelationEnemy.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_1.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_2.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_3.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_4.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdDisband.getUseageTemplate(context)); + pageLines.add(""); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdRelationAlly.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdRelationNeutral.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdRelationEnemy.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_1.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_2.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_3.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_4.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_5.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_6.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_7.toString())); - pageLines.add(TL.COMMAND_HELP_RELATIONS_8.toString()); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_9.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_10.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_11.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_12.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_13.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_5.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_6.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_7.toString())); + pageLines.add(TL.COMMAND_HELP_RELATIONS_8.toString()); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_9.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_10.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_11.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_12.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_RELATIONS_13.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_1.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_2.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_3.toString())); - pageLines.add(TL.COMMAND_HELP_PERMISSIONS_4.toString()); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_5.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_6.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_7.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_8.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_9.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_1.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_2.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_3.toString())); + pageLines.add(TL.COMMAND_HELP_PERMISSIONS_4.toString()); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_5.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_6.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_7.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_8.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_PERMISSIONS_9.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(TL.COMMAND_HELP_MOAR_1.toString()); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdBypass.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_ADMIN_1.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_ADMIN_2.toString())); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_ADMIN_3.toString())); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSafeunclaimall.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdWarunclaimall.getUseageTemplate(context)); - //TODO:TL - pageLines.add(FactionsPlugin.getInstance().txt.parse("Note: " + FactionsPlugin.getInstance().cmdBase.cmdUnclaim.getUseageTemplate(context) + FactionsPlugin.getInstance().txt.parse("") + " works on safe/war zones as well.")); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPeaceful.getUseageTemplate(context)); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(TL.COMMAND_HELP_MOAR_1.toString()); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdBypass.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_ADMIN_1.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_ADMIN_2.toString())); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_ADMIN_3.toString())); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSafeunclaimall.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdWarunclaimall.getUseageTemplate(context)); + //TODO:TL + pageLines.add(FactionsPlugin.getInstance().txt.parse("Note: " + FactionsPlugin.getInstance().cmdBase.cmdUnclaim.getUseageTemplate(context) + FactionsPlugin.getInstance().txt.parse("") + " works on safe/war zones as well.")); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPeaceful.getUseageTemplate(context)); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_MOAR_2.toString())); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdChatSpy.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPermanent.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPermanentPower.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPowerBoost.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdConfig.getUseageTemplate(context)); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_MOAR_2.toString())); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdChatSpy.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPermanent.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPermanentPower.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdPowerBoost.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdConfig.getUseageTemplate(context)); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_MOAR_3.toString())); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdLock.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdReload.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSaveAll.getUseageTemplate(context)); - pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdVersion.getUseageTemplate(context)); - helpPages.add(pageLines); - } + pageLines = new ArrayList<>(); + pageLines.add(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_HELP_MOAR_3.toString())); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdLock.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdReload.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdSaveAll.getUseageTemplate(context)); + pageLines.add(FactionsPlugin.getInstance().cmdBase.cmdVersion.getUseageTemplate(context)); + 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 36d838ad..4377f5d7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdHome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdHome.java @@ -20,118 +20,118 @@ import java.util.List; public class CmdHome extends FCommand { - public CmdHome() { - super(); - this.aliases.add("home"); + public CmdHome() { + super(); + this.aliases.add("home"); - this.requirements = new CommandRequirements.Builder(Permission.HOME) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.HOME) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.HOME) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.HOME) + .build(); + } - @Override - public void perform(CommandContext context) { - // TODO: Hide this command on help also. - if (!Conf.homesEnabled) { - context.msg(TL.COMMAND_HOME_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + // TODO: Hide this command on help also. + if (!Conf.homesEnabled) { + context.msg(TL.COMMAND_HOME_DISABLED); + return; + } - if (!Conf.homesTeleportCommandEnabled) { - context.msg(TL.COMMAND_HOME_TELEPORTDISABLED); - return; - } + if (!Conf.homesTeleportCommandEnabled) { + context.msg(TL.COMMAND_HOME_TELEPORTDISABLED); + return; + } - if (!context.faction.hasHome()) { - context.msg(TL.COMMAND_HOME_NOHOME.toString() + (context.fPlayer.getRole().value < Role.MODERATOR.value ? TL.GENERIC_ASKYOURLEADER.toString() : TL.GENERIC_YOUSHOULD.toString())); - context.sendMessage(FactionsPlugin.getInstance().cmdBase.cmdSethome.getUseageTemplate(context)); - return; - } + if (!context.faction.hasHome()) { + context.msg(TL.COMMAND_HOME_NOHOME.toString() + (context.fPlayer.getRole().value < Role.MODERATOR.value ? TL.GENERIC_ASKYOURLEADER.toString() : TL.GENERIC_YOUSHOULD.toString())); + context.sendMessage(FactionsPlugin.getInstance().cmdBase.cmdSethome.getUseageTemplate(context)); + return; + } - if (!Conf.homesTeleportAllowedFromEnemyTerritory && context.fPlayer.isInEnemyTerritory()) { - context.msg(TL.COMMAND_HOME_INENEMY); - return; - } + if (!Conf.homesTeleportAllowedFromEnemyTerritory && context.fPlayer.isInEnemyTerritory()) { + context.msg(TL.COMMAND_HOME_INENEMY); + return; + } - if (!Conf.homesTeleportAllowedFromDifferentWorld && context.player.getWorld().getUID() != context.faction.getHome().getWorld().getUID()) { - context.msg(TL.COMMAND_HOME_WRONGWORLD); - return; - } + if (!Conf.homesTeleportAllowedFromDifferentWorld && context.player.getWorld().getUID() != context.faction.getHome().getWorld().getUID()) { + context.msg(TL.COMMAND_HOME_WRONGWORLD); + return; + } - if (!context.fPlayer.isAdminBypassing()) { - Access access = context.faction.getAccess(context.fPlayer, PermissableAction.HOME); - if (access != Access.ALLOW && context.fPlayer.getRole() != Role.LEADER) { - context.fPlayer.msg(TL.GENERIC_FPERM_NOPERMISSION, "teleport home"); - return; - } - } + if (!context.fPlayer.isAdminBypassing()) { + Access access = context.faction.getAccess(context.fPlayer, PermissableAction.HOME); + if (access != Access.ALLOW && context.fPlayer.getRole() != Role.LEADER) { + context.fPlayer.msg(TL.GENERIC_FPERM_NOPERMISSION, "teleport home"); + return; + } + } - Faction faction = Board.getInstance().getFactionAt(new FLocation(context.player.getLocation())); - final Location loc = context.player.getLocation().clone(); + Faction faction = Board.getInstance().getFactionAt(new FLocation(context.player.getLocation())); + final Location loc = context.player.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() && (!context.fPlayer.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() && (!context.fPlayer.isInOwnTerritory() || !Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory)) { + World w = loc.getWorld(); + double x = loc.getX(); + double y = loc.getY(); + double z = loc.getZ(); - for (Player p : context.player.getServer().getOnlinePlayers()) { - if (p == null || !p.isOnline() || p.isDead() || p == context.player || p.getWorld() != w) { - continue; - } + for (Player p : context.player.getServer().getOnlinePlayers()) { + if (p == null || !p.isOnline() || p.isDead() || p == context.player || p.getWorld() != w) { + continue; + } - FPlayer fp = FPlayers.getInstance().getByPlayer(p); - if (context.fPlayer.getRelationTo(fp) != Relation.ENEMY || fp.isVanished()) { - continue; - } + FPlayer fp = FPlayers.getInstance().getByPlayer(p); + if (context.fPlayer.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; + } - context.msg(TL.COMMAND_HOME_ENEMYNEAR, String.valueOf(Conf.homesTeleportAllowedEnemyDistance)); - return; - } - } + context.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 (!context.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 (!context.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(context.player, context.faction.getHome())) { - return; - } + // if Essentials teleport handling is enabled and available, pass the teleport off to it (for delay and cooldown) + if (Essentials.handleTeleport(context.player, context.faction.getHome())) { + return; + } - context.doWarmUp(WarmUpUtil.Warmup.HOME, TL.WARMUPS_NOTIFY_TELEPORT, "Home", () -> { - // Create a smoke effect - if (Conf.homesTeleportCommandSmokeEffectEnabled) { - List smokeLocations = new ArrayList<>(); - smokeLocations.add(loc); - smokeLocations.add(loc.add(0, 1, 0)); - smokeLocations.add(context.faction.getHome()); - smokeLocations.add(context.faction.getHome().clone().add(0, 1, 0)); - SmokeUtil.spawnCloudRandom(smokeLocations, Conf.homesTeleportCommandSmokeEffectThickness); - } - context.player.teleport(context.faction.getHome()); - }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-home", 0)); - } + context.doWarmUp(WarmUpUtil.Warmup.HOME, TL.WARMUPS_NOTIFY_TELEPORT, "Home", () -> { + // Create a smoke effect + if (Conf.homesTeleportCommandSmokeEffectEnabled) { + List smokeLocations = new ArrayList<>(); + smokeLocations.add(loc); + smokeLocations.add(loc.add(0, 1, 0)); + smokeLocations.add(context.faction.getHome()); + smokeLocations.add(context.faction.getHome().clone().add(0, 1, 0)); + SmokeUtil.spawnCloudRandom(smokeLocations, Conf.homesTeleportCommandSmokeEffectThickness); + } + context.player.teleport(context.faction.getHome()); + }, FactionsPlugin.getInstance().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 4972bed0..56e2001d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java @@ -4,33 +4,33 @@ 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.requirements = new CommandRequirements.Builder(Permission.INSPECT) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.INSPECT) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (context.fPlayer.isInspectMode()) { - context.fPlayer.setInspectMode(false); - context.msg(TL.COMMAND_INSPECT_DISABLED_MSG); - } else { - context.fPlayer.setInspectMode(true); - context.msg(TL.COMMAND_INSPECT_ENABLED); - } + @Override + public void perform(CommandContext context) { + if (context.fPlayer.isInspectMode()) { + context.fPlayer.setInspectMode(false); + context.msg(TL.COMMAND_INSPECT_DISABLED_MSG); + } else { + context.fPlayer.setInspectMode(true); + context.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/CmdInventorySee.java b/src/main/java/com/massivecraft/factions/cmd/CmdInventorySee.java index fce45aa7..5b01bf0f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdInventorySee.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdInventorySee.java @@ -16,50 +16,50 @@ import java.util.Objects; public class CmdInventorySee extends FCommand { - public CmdInventorySee() { - super(); + public CmdInventorySee() { + super(); - this.aliases.add("invsee"); - this.aliases.add("inventorysee"); + this.aliases.add("invsee"); + this.aliases.add("inventorysee"); - this.requiredArgs.add("member name"); + this.requiredArgs.add("member name"); - this.requirements = new CommandRequirements.Builder(Permission.INVSEE) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.INVSEE) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-inventory-see.Enabled")) { - context.msg(TL.GENERIC_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-inventory-see.Enabled")) { + context.msg(TL.GENERIC_DISABLED); + return; + } - Access use = context.fPlayer.getFaction().getAccess(context.fPlayer, PermissableAction.TERRITORY); - if (use == Access.DENY || (use == Access.UNDEFINED && !context.assertMinRole(Role.MODERATOR))) { - context.msg(TL.GENERIC_NOPERMISSION, "territory"); - return; - } + Access use = context.fPlayer.getFaction().getAccess(context.fPlayer, PermissableAction.TERRITORY); + if (use == Access.DENY || (use == Access.UNDEFINED && !context.assertMinRole(Role.MODERATOR))) { + context.msg(TL.GENERIC_NOPERMISSION, "territory"); + return; + } - ArrayList fplayers = context.fPlayer.getFaction().getOnlinePlayers(); + ArrayList fplayers = context.fPlayer.getFaction().getOnlinePlayers(); - FPlayer targetInv = context.argAsFPlayer(0); - if (targetInv == null || !fplayers.contains(targetInv.getPlayer())) { - context.msg(TL.PLAYER_NOT_FOUND, Objects.requireNonNull(targetInv).toString()); - return; - } + FPlayer targetInv = context.argAsFPlayer(0); + if (targetInv == null || !fplayers.contains(targetInv.getPlayer())) { + context.msg(TL.PLAYER_NOT_FOUND, Objects.requireNonNull(targetInv).toString()); + return; + } - Inventory inventory = Bukkit.createInventory(context.player, 36, targetInv.getName() + "'s Inventory"); - for (int i = 0; i < 36; i++) - if (targetInv.getPlayer().getInventory().getItem(i) != null) - inventory.setItem(i, targetInv.getPlayer().getInventory().getItem(i)); + Inventory inventory = Bukkit.createInventory(context.player, 36, targetInv.getName() + "'s Inventory"); + for (int i = 0; i < 36; i++) + if (targetInv.getPlayer().getInventory().getItem(i) != null) + inventory.setItem(i, targetInv.getPlayer().getInventory().getItem(i)); - context.player.openInventory(inventory); - } + context.player.openInventory(inventory); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_INVENTORYSEE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_INVENTORYSEE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java index fdaf6e57..d4c3741b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java @@ -11,69 +11,69 @@ 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.requiredArgs.add("player name"); - this.requirements = new CommandRequirements.Builder(Permission.INVITE) - .playerOnly() - .withAction(PermissableAction.INVITE) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.INVITE) + .playerOnly() + .withAction(PermissableAction.INVITE) + .build(); + } - @Override - public void perform(CommandContext context) { - FPlayer target = context.argAsBestFPlayerMatch(0); - if (target == null) { - return; - } + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0); + if (target == null) { + return; + } - if (target.getFaction() == context.faction) { - context.msg(TL.COMMAND_INVITE_ALREADYMEMBER, target.getName(), context.faction.getTag()); - context.msg(TL.GENERIC_YOUMAYWANT.toString() + FactionsPlugin.getInstance().cmdBase.cmdKick.getUseageTemplate(context)); - return; - } + if (target.getFaction() == context.faction) { + context.msg(TL.COMMAND_INVITE_ALREADYMEMBER, target.getName(), context.faction.getTag()); + context.msg(TL.GENERIC_YOUMAYWANT.toString() + FactionsPlugin.getInstance().cmdBase.cmdKick.getUseageTemplate(context)); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!context.payForCommand(Conf.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 (!context.payForCommand(Conf.econCostInvite, TL.COMMAND_INVITE_TOINVITE.toString(), TL.COMMAND_INVITE_FORINVITE.toString())) { + return; + } - if (context.faction.isInvited(target)) { - context.msg(TL.COMMAND_INVITE_ALREADYINVITED, target.getName()); - return; - } - if (context.faction.isBanned(target)) { - context.msg(TL.COMMAND_INVITE_BANNED, target.getName()); - return; - } + if (context.faction.isInvited(target)) { + context.msg(TL.COMMAND_INVITE_ALREADYINVITED, target.getName()); + return; + } + if (context.faction.isBanned(target)) { + context.msg(TL.COMMAND_INVITE_BANNED, target.getName()); + return; + } - context.faction.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(context.fPlayer.describeTo(target, true)) - .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()) - .then(TL.COMMAND_INVITE_INVITEDYOU.toString()) - .color(ChatColor.YELLOW) - .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()) - .then(context.faction.describeTo(target)).tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()); + context.faction.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(context.fPlayer.describeTo(target, true)) + .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()) + .then(TL.COMMAND_INVITE_INVITEDYOU.toString()) + .color(ChatColor.YELLOW) + .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()) + .then(context.faction.describeTo(target)).tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()); - message.send(target.getPlayer()); - } + message.send(target.getPlayer()); + } - context.faction.msg(TL.COMMAND_INVITE_INVITED, context.fPlayer.describeTo(context.faction, true), target.describeTo(context.faction)); - } + context.faction.msg(TL.COMMAND_INVITE_INVITED, context.fPlayer.describeTo(context.faction, true), target.describeTo(context.faction)); + } - @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 1fb9718c..5b5e319c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java @@ -9,132 +9,132 @@ import org.bukkit.Bukkit; public class CmdJoin extends FCommand { - public CmdJoin() { - super(); - this.aliases.add("join"); - this.requiredArgs.add("faction name"); - this.optionalArgs.put("player", "you"); + public CmdJoin() { + super(); + this.aliases.add("join"); + this.requiredArgs.add("faction name"); + this.optionalArgs.put("player", "you"); - this.requirements = new CommandRequirements.Builder(Permission.JOIN) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.JOIN) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Faction faction = context.argAsFaction(0); - if (faction == null) { - return; - } + @Override + public void perform(CommandContext context) { + Faction faction = context.argAsFaction(0); + if (faction == null) { + return; + } - FPlayer fplayer = context.argAsBestFPlayerMatch(1, context.fPlayer, false); - boolean samePlayer = fplayer == context.fPlayer; + FPlayer fplayer = context.argAsBestFPlayerMatch(1, context.fPlayer, false); + boolean samePlayer = fplayer == context.fPlayer; - if (!samePlayer && !Permission.JOIN_OTHERS.has(context.sender, false)) { - context.msg(TL.COMMAND_JOIN_CANNOTFORCE); - return; - } + if (!samePlayer && !Permission.JOIN_OTHERS.has(context.sender, false)) { + context.msg(TL.COMMAND_JOIN_CANNOTFORCE); + return; + } - if (!faction.isNormal()) { - context.msg(TL.COMMAND_JOIN_SYSTEMFACTION); - return; - } + if (!faction.isNormal()) { + context.msg(TL.COMMAND_JOIN_SYSTEMFACTION); + return; + } - if (faction == fplayer.getFaction()) { - context.msg(TL.COMMAND_JOIN_ALREADYMEMBER, fplayer.describeTo(context.fPlayer, true), (samePlayer ? "are" : "is"), faction.getTag(context.fPlayer)); - return; - } + if (faction == fplayer.getFaction()) { + context.msg(TL.COMMAND_JOIN_ALREADYMEMBER, fplayer.describeTo(context.fPlayer, true), (samePlayer ? "are" : "is"), faction.getTag(context.fPlayer)); + return; + } - if (Conf.factionMemberLimit > 0 && faction.getFPlayers().size() >= getFactionMemberLimit(faction)) { - context.msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(context.fPlayer), getFactionMemberLimit(faction), fplayer.describeTo(context.fPlayer, false)); - return; - } + if (Conf.factionMemberLimit > 0 && faction.getFPlayers().size() >= getFactionMemberLimit(faction)) { + context.msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(context.fPlayer), getFactionMemberLimit(faction), fplayer.describeTo(context.fPlayer, false)); + return; + } - if (fplayer.hasFaction()) { - context.msg(TL.COMMAND_JOIN_INOTHERFACTION, fplayer.describeTo(context.fPlayer, true), (samePlayer ? "your" : "their")); - return; - } + if (fplayer.hasFaction()) { + context.msg(TL.COMMAND_JOIN_INOTHERFACTION, fplayer.describeTo(context.fPlayer, true), (samePlayer ? "your" : "their")); + return; + } - if (!Conf.canLeaveWithNegativePower && fplayer.getPower() < 0) { - context.msg(TL.COMMAND_JOIN_NEGATIVEPOWER, fplayer.describeTo(context.fPlayer, true)); - return; - } + if (!Conf.canLeaveWithNegativePower && fplayer.getPower() < 0) { + context.msg(TL.COMMAND_JOIN_NEGATIVEPOWER, fplayer.describeTo(context.fPlayer, true)); + return; + } - if (!(faction.getOpen() || faction.isInvited(fplayer) || context.fPlayer.isAdminBypassing() || Permission.JOIN_ANY.has(context.sender, false))) { - context.msg(TL.COMMAND_JOIN_REQUIRESINVITATION); - if (samePlayer) { - faction.msg(TL.COMMAND_JOIN_ATTEMPTEDJOIN, fplayer.describeTo(faction, true)); - } - return; - } + if (!(faction.getOpen() || faction.isInvited(fplayer) || context.fPlayer.isAdminBypassing() || Permission.JOIN_ANY.has(context.sender, false))) { + context.msg(TL.COMMAND_JOIN_REQUIRESINVITATION); + if (samePlayer) { + faction.msg(TL.COMMAND_JOIN_ATTEMPTEDJOIN, fplayer.describeTo(faction, true)); + } + return; + } - int altLimit = Conf.factionAltMemberLimit; + int altLimit = Conf.factionAltMemberLimit; - if (altLimit > 0 && faction.getAltPlayers().size() >= altLimit && !faction.altInvited(context.fPlayer)) { - context.msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(context.fPlayer), altLimit, fplayer.describeTo(context.fPlayer, false)); - return; - } + if (altLimit > 0 && faction.getAltPlayers().size() >= altLimit && !faction.altInvited(context.fPlayer)) { + context.msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(context.fPlayer), altLimit, fplayer.describeTo(context.fPlayer, false)); + 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 && !context.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 && !context.canAffordCommand(Conf.econCostJoin, TL.COMMAND_JOIN_TOJOIN.toString())) { + return; + } - // Check for ban - if (!context.fPlayer.isAdminBypassing() && faction.isBanned(context.fPlayer)) { - context.msg(TL.COMMAND_JOIN_BANNED, faction.getTag(context.fPlayer)); - return; - } + // Check for ban + if (!context.fPlayer.isAdminBypassing() && faction.isBanned(context.fPlayer)) { + context.msg(TL.COMMAND_JOIN_BANNED, faction.getTag(context.fPlayer)); + return; + } - // trigger the join event (cancellable) - FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(context.player), 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(context.player), faction, FPlayerJoinEvent.PlayerJoinReason.COMMAND); + Bukkit.getServer().getPluginManager().callEvent(joinEvent); + if (joinEvent.isCancelled()) { + return; + } - // then make 'em pay (if applicable) - if (samePlayer && !context.payForCommand(Conf.econCostJoin, TL.COMMAND_JOIN_TOJOIN.toString(), TL.COMMAND_JOIN_FORJOIN.toString())) { - return; - } + // then make 'em pay (if applicable) + if (samePlayer && !context.payForCommand(Conf.econCostJoin, TL.COMMAND_JOIN_TOJOIN.toString(), TL.COMMAND_JOIN_FORJOIN.toString())) { + return; + } - context.msg(TL.COMMAND_JOIN_SUCCESS, fplayer.describeTo(context.fPlayer, true), faction.getTag(context.fPlayer)); + context.msg(TL.COMMAND_JOIN_SUCCESS, fplayer.describeTo(context.fPlayer, true), faction.getTag(context.fPlayer)); - if (!samePlayer) { - fplayer.msg(TL.COMMAND_JOIN_MOVED, context.fPlayer.describeTo(fplayer, true), faction.getTag(fplayer)); - } + if (!samePlayer) { + fplayer.msg(TL.COMMAND_JOIN_MOVED, context.fPlayer.describeTo(fplayer, true), faction.getTag(fplayer)); + } - faction.msg(TL.COMMAND_JOIN_JOINED, fplayer.describeTo(faction, true)); + faction.msg(TL.COMMAND_JOIN_JOINED, fplayer.describeTo(faction, true)); - fplayer.resetFactionData(); + fplayer.resetFactionData(); - if (faction.altInvited(fplayer)) { - fplayer.setAlt(true); - fplayer.setFaction(faction, true); - } else { - fplayer.setFaction(faction, false); - } + if (faction.altInvited(fplayer)) { + fplayer.setAlt(true); + fplayer.setFaction(faction, true); + } else { + fplayer.setFaction(faction, false); + } - faction.deinvite(fplayer); - context.fPlayer.setRole(faction.getDefaultRole()); + faction.deinvite(fplayer); + context.fPlayer.setRole(faction.getDefaultRole()); - if (Conf.logFactionJoin) { - if (samePlayer) { - FactionsPlugin.getInstance().log(TL.COMMAND_JOIN_JOINEDLOG.toString(), fplayer.getName(), faction.getTag()); - } else { - FactionsPlugin.getInstance().log(TL.COMMAND_JOIN_MOVEDLOG.toString(), context.fPlayer.getName(), fplayer.getName(), faction.getTag()); - } - } - } + if (Conf.logFactionJoin) { + if (samePlayer) { + FactionsPlugin.getInstance().log(TL.COMMAND_JOIN_JOINEDLOG.toString(), fplayer.getName(), faction.getTag()); + } else { + FactionsPlugin.getInstance().log(TL.COMMAND_JOIN_MOVEDLOG.toString(), context.fPlayer.getName(), fplayer.getName(), faction.getTag()); + } + } + } - private int getFactionMemberLimit(Faction f) { - if (f.getUpgrade(UpgradeType.MEMBERS) == 0) return Conf.factionMemberLimit; - return Conf.factionMemberLimit + FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Members.Member-Boost.level-" + f.getUpgrade(UpgradeType.MEMBERS)); - } + private int getFactionMemberLimit(Faction f) { + if (f.getUpgrade(UpgradeType.MEMBERS) == 0) return Conf.factionMemberLimit; + return Conf.factionMemberLimit + FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Members.Member-Boost.level-" + f.getUpgrade(UpgradeType.MEMBERS)); + } - @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 b7662261..cfd5f9c1 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java @@ -16,115 +16,115 @@ import org.bukkit.command.ConsoleCommandSender; public class CmdKick extends FCommand { - public CmdKick() { - super(); - this.aliases.add("kick"); - this.optionalArgs.put("player name", "player name"); + public CmdKick() { + super(); + this.aliases.add("kick"); + this.optionalArgs.put("player name", "player name"); - this.requirements = new CommandRequirements.Builder(Permission.KICK) - .playerOnly() - .withAction(PermissableAction.KICK) - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.KICK) + .playerOnly() + .withAction(PermissableAction.KICK) + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - FPlayer toKick = context.argIsSet(0) ? context.argAsBestFPlayerMatch(0) : null; - if (toKick == null) { - FancyMessage msg = new FancyMessage(TL.COMMAND_KICK_CANDIDATES.toString()).color(ChatColor.GOLD); - for (FPlayer player : context.faction.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 (context.fPlayer.getRole().isAtLeast(Role.COLEADER)) { - // For both coleader and admin, add mods. - for (FPlayer player : context.faction.getFPlayersWhereRole(Role.MODERATOR)) { + @Override + public void perform(CommandContext context) { + FPlayer toKick = context.argIsSet(0) ? context.argAsBestFPlayerMatch(0) : null; + if (toKick == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_KICK_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : context.faction.getFPlayersWhereRole(Role.NORMAL)) { 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 (context.fPlayer.getRole() == Role.LEADER) { - // Only add coleader to this for the leader. - for (FPlayer player : context.faction.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); + msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " kick " + s); + } + if (context.fPlayer.getRole().isAtLeast(Role.COLEADER)) { + // For both coleader and admin, add mods. + for (FPlayer player : context.faction.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 (context.fPlayer.getRole() == Role.LEADER) { + // Only add coleader to this for the leader. + for (FPlayer player : context.faction.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); + } + } + } - context.sendFancyMessage(msg); - return; - } + context.sendFancyMessage(msg); + return; + } - if (context.fPlayer == toKick) { - context.msg(TL.COMMAND_KICK_SELF); - context.msg(TL.GENERIC_YOUMAYWANT.toString() + FactionsPlugin.getInstance().cmdBase.cmdLeave.getUseageTemplate(context)); - return; - } + if (context.fPlayer == toKick) { + context.msg(TL.COMMAND_KICK_SELF); + context.msg(TL.GENERIC_YOUMAYWANT.toString() + FactionsPlugin.getInstance().cmdBase.cmdLeave.getUseageTemplate(context)); + return; + } - Faction toKickFaction = toKick.getFaction(); + Faction toKickFaction = toKick.getFaction(); - if (toKickFaction.isWilderness()) { - context.sender.sendMessage(TL.COMMAND_KICK_NONE.toString()); - return; - } + if (toKickFaction.isWilderness()) { + context.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 (!context.fPlayer.isAdminBypassing()) { - if (toKickFaction != context.faction) { - context.msg(TL.COMMAND_KICK_NOTMEMBER, toKick.describeTo(context.fPlayer, true), context.faction.describeTo(context.fPlayer)); - return; - } - if (toKick.getRole().value >= context.fPlayer.getRole().value) { - context.msg(TL.COMMAND_KICK_INSUFFICIENTRANK); - return; - } - if (!Conf.canLeaveWithNegativePower && toKick.getPower() < 0) { - context.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 (!context.fPlayer.isAdminBypassing()) { + if (toKickFaction != context.faction) { + context.msg(TL.COMMAND_KICK_NOTMEMBER, toKick.describeTo(context.fPlayer, true), context.faction.describeTo(context.fPlayer)); + return; + } + if (toKick.getRole().value >= context.fPlayer.getRole().value) { + context.msg(TL.COMMAND_KICK_INSUFFICIENTRANK); + return; + } + if (!Conf.canLeaveWithNegativePower && toKick.getPower() < 0) { + context.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 (!context.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 (!context.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 (!context.payForCommand(Conf.econCostKick, TL.COMMAND_KICK_TOKICK.toString(), TL.COMMAND_KICK_FORKICK.toString())) { - return; - } + // then make 'em pay (if applicable) + if (!context.payForCommand(Conf.econCostKick, TL.COMMAND_KICK_TOKICK.toString(), TL.COMMAND_KICK_FORKICK.toString())) { + return; + } - toKickFaction.msg(TL.COMMAND_KICK_FACTION, context.fPlayer.describeTo(toKickFaction, true), toKick.describeTo(toKickFaction, true)); + toKickFaction.msg(TL.COMMAND_KICK_FACTION, context.fPlayer.describeTo(toKickFaction, true), toKick.describeTo(toKickFaction, true)); - toKick.msg(TL.COMMAND_KICK_KICKED, context.fPlayer.describeTo(toKick, true), toKickFaction.describeTo(toKick)); - if (toKickFaction != context.faction) { - context.fPlayer.msg(TL.COMMAND_KICK_KICKS, toKick.describeTo(context.fPlayer), toKickFaction.describeTo(context.fPlayer)); - } - if (Conf.logFactionKick) { - FactionsPlugin.getInstance().log((context.sender instanceof ConsoleCommandSender ? "A console command" : context.fPlayer.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, context.fPlayer.describeTo(toKick, true), toKickFaction.describeTo(toKick)); + if (toKickFaction != context.faction) { + context.fPlayer.msg(TL.COMMAND_KICK_KICKS, toKick.describeTo(context.fPlayer), toKickFaction.describeTo(context.fPlayer)); + } + if (Conf.logFactionKick) { + FactionsPlugin.getInstance().log((context.sender instanceof ConsoleCommandSender ? "A console command" : context.fPlayer.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 3b1d7ceb..cd8a3df6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdKillHolograms.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdKillHolograms.java @@ -4,26 +4,26 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdKillHolograms extends FCommand { - public CmdKillHolograms() { - super(); - this.aliases.add("killholos"); - this.requiredArgs.add("radius"); + public CmdKillHolograms() { + super(); + this.aliases.add("killholos"); + this.requiredArgs.add("radius"); - this.requirements = new CommandRequirements.Builder(Permission.KILLHOLOS) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.KILLHOLOS) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - context.player.sendMessage("Killing Invisible Armor Stands.."); - context.player.chat("/minecraft:kill @e[type=ArmorStand,r=" + context.argAsInt(0) + "]"); + @Override + public void perform(CommandContext context) { + context.player.sendMessage("Killing Invisible Armor Stands.."); + context.player.chat("/minecraft:kill @e[type=ArmorStand,r=" + context.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 a7a1d9c9..8e4d988d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java @@ -5,24 +5,24 @@ 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.requirements = new CommandRequirements.Builder(Permission.LEAVE) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.LEAVE) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - context.fPlayer.leave(true); - } + @Override + public void perform(CommandContext context) { + context.fPlayer.leave(true); + } - @Override - public TL getUsageTranslation() { - return TL.LEAVE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.LEAVE_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdList.java b/src/main/java/com/massivecraft/factions/cmd/CmdList.java index 2daffc04..994c419a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdList.java @@ -14,103 +14,103 @@ import java.util.List; 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.requirements = new CommandRequirements.Builder(Permission.LIST) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.LIST) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!context.payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) - return; + @Override + public void perform(CommandContext context) { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) + return; - 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 (context.fPlayer != null && context.fPlayer.getPlayer() != null && !context.fPlayer.getPlayer().hasPermission("factions.show.bypassexempt")) { - List exemptFactions = FactionsPlugin.getInstance().getConfig().getStringList("show-exempt"); + // remove exempt factions + if (context.fPlayer != null && context.fPlayer.getPlayer() != null && !context.fPlayer.getPlayer().hasPermission("factions.show.bypassexempt")) { + List exemptFactions = FactionsPlugin.getInstance().getConfig().getStringList("show-exempt"); - factionList.removeIf(next -> exemptFactions.contains(next.getTag())); - } + factionList.removeIf(next -> exemptFactions.contains(next.getTag())); + } - // Sort by total followers first - factionList.sort((f1, f2) -> { - int f1Size = f1.getFPlayers().size(); - int f2Size = f2.getFPlayers().size(); - if (f1Size < f2Size) { - return 1; - } else if (f1Size > f2Size) { - return -1; - } - return 0; - }); + // Sort by total followers first + factionList.sort((f1, f2) -> { + int f1Size = f1.getFPlayers().size(); + int f2Size = f2.getFPlayers().size(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); - // Then sort by how many members are online now - factionList.sort((f1, f2) -> { - int f1Size = f1.getFPlayersWhereOnline(true).size(); - int f2Size = f2.getFPlayersWhereOnline(true).size(); - if (f1Size < f2Size) { - return 1; - } else if (f1Size > f2Size) { - return -1; - } - return 0; - }); + // Then sort by how many members are online now + factionList.sort((f1, f2) -> { + int f1Size = f1.getFPlayersWhereOnline(true).size(); + int f2Size = f2.getFPlayersWhereOnline(true).size(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); - ArrayList lines = new ArrayList<>(); + ArrayList lines = new ArrayList<>(); - factionList.add(0, Factions.getInstance().getWilderness()); + factionList.add(0, Factions.getInstance().getWilderness()); - final int pageheight = 9; - int pagenumber = context.argAsInt(0, 1); - int pagecount = (factionList.size() / pageheight) + 1; - if (pagenumber > pagecount) { - pagenumber = pagecount; - } else if (pagenumber < 1) { - pagenumber = 1; - } - int start = (pagenumber - 1) * pageheight; - int end = start + pageheight; - if (end > factionList.size()) { - end = factionList.size(); - } + final int pageheight = 9; + int pagenumber = context.argAsInt(0, 1); + int pagecount = (factionList.size() / pageheight) + 1; + if (pagenumber > pagecount) { + pagenumber = pagecount; + } else if (pagenumber < 1) { + pagenumber = 1; + } + int start = (pagenumber - 1) * pageheight; + int end = start + pageheight; + if (end > factionList.size()) { + end = factionList.size(); + } - String header = FactionsPlugin.getInstance().getConfig().getString("list.header", defaults[0]); - header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount)); - lines.add(FactionsPlugin.getInstance().txt.parse(header)); + String header = FactionsPlugin.getInstance().getConfig().getString("list.header", defaults[0]); + header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount)); + lines.add(FactionsPlugin.getInstance().txt.parse(header)); - for (Faction faction : factionList.subList(start, end)) { - if (faction.isWilderness()) { - lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, FactionsPlugin.getInstance().getConfig().getString("list.factionless", defaults[1])))); - continue; - } - lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, context.fPlayer, FactionsPlugin.getInstance().getConfig().getString("list.entry", defaults[2])))); - } - context.sendMessage(lines); - } + for (Faction faction : factionList.subList(start, end)) { + if (faction.isWilderness()) { + lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, FactionsPlugin.getInstance().getConfig().getString("list.factionless", defaults[1])))); + continue; + } + lines.add(FactionsPlugin.getInstance().txt.parse(TagUtil.parsePlain(faction, context.fPlayer, FactionsPlugin.getInstance().getConfig().getString("list.entry", defaults[2])))); + } + context.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 d0fe8b5e..ef25532f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLock.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLock.java @@ -6,33 +6,33 @@ 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"); - this.optionalArgs.put("on/off", "flip"); + public CmdLock() { + super(); + this.aliases.add("lock"); + this.optionalArgs.put("on/off", "flip"); - this.requirements = new CommandRequirements.Builder(Permission.LOCK) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.LOCK) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - FactionsPlugin.getInstance().setLocked(context.argAsBool(0, !FactionsPlugin.getInstance().getLocked())); - context.msg(FactionsPlugin.getInstance().getLocked() ? TL.COMMAND_LOCK_LOCKED : TL.COMMAND_LOCK_UNLOCKED); - } + @Override + public void perform(CommandContext context) { + FactionsPlugin.getInstance().setLocked(context.argAsBool(0, !FactionsPlugin.getInstance().getLocked())); + context.msg(FactionsPlugin.getInstance().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 8176fd7e..3effca1c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java @@ -5,28 +5,28 @@ 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"); + public CmdLogins() { + super(); + this.aliases.add("login"); + this.aliases.add("logins"); + this.aliases.add("logout"); + this.aliases.add("logouts"); - this.requirements = new CommandRequirements.Builder(Permission.MONITOR_LOGINS) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MONITOR_LOGINS) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - boolean monitor = context.fPlayer.isMonitoringJoins(); - context.msg(TL.COMMAND_LOGINS_TOGGLE, String.valueOf(!monitor)); - context.fPlayer.setMonitorJoins(!monitor); - } + @Override + public void perform(CommandContext context) { + boolean monitor = context.fPlayer.isMonitoringJoins(); + context.msg(TL.COMMAND_LOGINS_TOGGLE, String.valueOf(!monitor)); + context.fPlayer.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 88fbf29d..0a12d6be 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLowPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLowPower.java @@ -7,33 +7,33 @@ 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.requirements = new CommandRequirements.Builder(Permission.POWER_ANY) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.POWER_ANY) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - double maxPower = Conf.powerPlayerMax; - String format = TL.COMMAND_LOWPOWER_FORMAT.toString(); - context.msg(TL.COMMAND_LOWPOWER_HEADER.toString().replace("{maxpower}", (int) maxPower + "")); - for (FPlayer fPlayer : context.faction.getFPlayers()) { - if (fPlayer.getPower() < maxPower) { - context.sendMessage(format.replace("{player}", fPlayer.getName()).replace("{player_power}", (int) fPlayer.getPower() + "").replace("{maxpower}", (int) maxPower + "")); - } - } - } + @Override + public void perform(CommandContext context) { + double maxPower = Conf.powerPlayerMax; + String format = TL.COMMAND_LOWPOWER_FORMAT.toString(); + context.msg(TL.COMMAND_LOWPOWER_HEADER.toString().replace("{maxpower}", (int) maxPower + "")); + for (FPlayer fPlayer : context.faction.getFPlayers()) { + if (fPlayer.getPower() < maxPower) { + context.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; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMap.java b/src/main/java/com/massivecraft/factions/cmd/CmdMap.java index 3c86e48c..c389b203 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMap.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMap.java @@ -9,55 +9,55 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdMap extends FCommand { - public CmdMap() { - super(); - this.aliases.add("map"); - this.optionalArgs.put("on/off", "once"); + public CmdMap() { + super(); + this.aliases.add("map"); + this.optionalArgs.put("on/off", "once"); - this.requirements = new CommandRequirements.Builder(Permission.MAP) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MAP) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (context.argIsSet(0)) { - if (context.argAsBool(0, !context.fPlayer.isMapAutoUpdating())) { - // Turn on + @Override + public void perform(CommandContext context) { + if (context.argIsSet(0)) { + if (context.argAsBool(0, !context.fPlayer.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 (!context.payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) { + return; + } + + context.fPlayer.setMapAutoUpdating(true); + context.msg(TL.COMMAND_MAP_UPDATE_ENABLED); + + // And show the map once + showMap(context); + } else { + // Turn off + context.fPlayer.setMapAutoUpdating(false); + context.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 (!context.payForCommand(Conf.econCostMap, TL.COMMAND_MAP_TOSHOW, TL.COMMAND_MAP_FORSHOW)) { return; - } + } - context.fPlayer.setMapAutoUpdating(true); - context.msg(TL.COMMAND_MAP_UPDATE_ENABLED); + showMap(context); + } + } - // And show the map once - showMap(context); - } else { - // Turn off - context.fPlayer.setMapAutoUpdating(false); - context.msg(TL.COMMAND_MAP_UPDATE_DISABLED); + public void showMap(CommandContext context) { + context.sendFancyMessage(Board.getInstance().getMap(context.fPlayer, new FLocation(context.fPlayer), context.player.getLocation().getYaw())); + } - } - } else { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!context.payForCommand(Conf.econCostMap, TL.COMMAND_MAP_TOSHOW, TL.COMMAND_MAP_FORSHOW)) { - return; - } - - showMap(context); - } - } - - public void showMap(CommandContext context) { - context.sendFancyMessage(Board.getInstance().getMap(context.fPlayer, new FLocation(context.fPlayer), context.player.getLocation().getYaw())); - } - - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MAP_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MAP_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java b/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java index c09157bd..92752c2c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java @@ -5,34 +5,34 @@ 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.optionalArgs.put("height", "height"); + this.aliases.add("mapheight"); + this.aliases.add("mh"); + this.optionalArgs.put("height", "height"); - this.requirements = new CommandRequirements.Builder(Permission.MAPHEIGHT) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MAPHEIGHT) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (context.args.size() == 0) { - context.fPlayer.sendMessage(TL.COMMAND_MAPHEIGHT_CURRENT.format(context.fPlayer.getMapHeight())); - return; - } + @Override + public void perform(CommandContext context) { + if (context.args.size() == 0) { + context.fPlayer.sendMessage(TL.COMMAND_MAPHEIGHT_CURRENT.format(context.fPlayer.getMapHeight())); + return; + } - int height = context.argAsInt(0); + int height = context.argAsInt(0); - context.fPlayer.setMapHeight(height); - context.msg(TL.COMMAND_MAPHEIGHT_SET.format(context.fPlayer.getMapHeight())); - } + context.fPlayer.setMapHeight(height); + context.msg(TL.COMMAND_MAPHEIGHT_SET.format(context.fPlayer.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 d325119d..bca15395 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java @@ -11,73 +11,73 @@ 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("player name", "name"); - this.requirements = new CommandRequirements.Builder(Permission.MOD) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MOD) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - FPlayer you = context.argAsBestFPlayerMatch(0); - if (you == null) { - FancyMessage msg = new FancyMessage(TL.COMMAND_MOD_CANDIDATES.toString()).color(ChatColor.GOLD); - for (FPlayer player : context.faction.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(CommandContext context) { + FPlayer you = context.argAsBestFPlayerMatch(0); + if (you == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_MOD_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : context.faction.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); + } - context.sendFancyMessage(msg); - return; - } + context.sendFancyMessage(msg); + return; + } - boolean permAny = Permission.MOD_ANY.has(context.sender, false); - Faction targetFaction = you.getFaction(); - if (targetFaction != context.faction && !permAny) { - context.msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(context.fPlayer, true)); - return; - } + boolean permAny = Permission.MOD_ANY.has(context.sender, false); + Faction targetFaction = you.getFaction(); + if (targetFaction != context.faction && !permAny) { + context.msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(context.fPlayer, true)); + return; + } - if (context.fPlayer != null && context.fPlayer.getRole() != Role.LEADER && !permAny) { - context.msg(TL.COMMAND_MOD_NOTADMIN); - return; - } + if (context.fPlayer != null && context.fPlayer.getRole() != Role.LEADER && !permAny) { + context.msg(TL.COMMAND_MOD_NOTADMIN); + return; + } - if (you == context.fPlayer && !permAny) { - context.msg(TL.COMMAND_MOD_SELF); - return; - } + if (you == context.fPlayer && !permAny) { + context.msg(TL.COMMAND_MOD_SELF); + return; + } - if (you.getRole() == Role.LEADER) { - context.msg(TL.COMMAND_MOD_TARGETISADMIN); - return; - } + if (you.getRole() == Role.LEADER) { + context.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)); - context.msg(TL.COMMAND_MOD_REVOKES, you.describeTo(context.fPlayer, true)); - } else { - // Give - you.setRole(Role.MODERATOR); - targetFaction.msg(TL.COMMAND_MOD_PROMOTED, you.describeTo(targetFaction, true)); - context.msg(TL.COMMAND_MOD_PROMOTES, you.describeTo(context.fPlayer, true)); - } - } + if (you.getRole() == Role.MODERATOR) { + // Revoke + you.setRole(Role.NORMAL); + targetFaction.msg(TL.COMMAND_MOD_REVOKED, you.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_MOD_REVOKES, you.describeTo(context.fPlayer, true)); + } else { + // Give + you.setRole(Role.MODERATOR); + targetFaction.msg(TL.COMMAND_MOD_PROMOTED, you.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_MOD_PROMOTES, you.describeTo(context.fPlayer, 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 4e5e18d2..b280818d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java @@ -6,39 +6,39 @@ 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.requirements = new CommandRequirements.Builder(Permission.MODIFY_POWER) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MODIFY_POWER) + .build(); + } - @Override - public void perform(CommandContext context) { - // /f modify # - FPlayer player = context.argAsBestFPlayerMatch(0); - Double number = context.argAsDouble(1); // returns null if not a Double. + @Override + public void perform(CommandContext context) { + // /f modify # + FPlayer player = context.argAsBestFPlayerMatch(0); + Double number = context.argAsDouble(1); // returns null if not a Double. - if (player == null || number == null) { - context.sender.sendMessage(getHelpShort()); - return; - } + if (player == null || number == null) { + context.sender.sendMessage(getHelpShort()); + return; + } - player.alterPower(number); - int newPower = player.getPowerRounded(); // int so we don't have super long doubles. - context.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. + context.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/CmdNear.java b/src/main/java/com/massivecraft/factions/cmd/CmdNear.java index 3317f8ef..76b7cc29 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdNear.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdNear.java @@ -9,42 +9,42 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; public class CmdNear extends FCommand { - public CmdNear() { - super(); - this.aliases.add("near"); - this.aliases.add("nearby"); + public CmdNear() { + super(); + this.aliases.add("near"); + this.aliases.add("nearby"); - this.requirements = new CommandRequirements.Builder(Permission.NEAR) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.NEAR) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fnear.Enabled")) { - context.msg(TL.COMMAND_NEAR_DISABLED_MSG); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fnear.Enabled")) { + context.msg(TL.COMMAND_NEAR_DISABLED_MSG); + return; + } - double range = FactionsPlugin.getInstance().getConfig().getInt("fnear.Radius"); - String format = TL.COMMAND_NEAR_FORMAT.toString(); - context.msg(TL.COMMAND_NEAR_USE_MSG); - for (Entity e : context.player.getNearbyEntities(range, 255, range)) { - if (e instanceof Player) { - Player player = (((Player) e).getPlayer()); - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - if (context.faction == fplayer.getFaction()) { - double distance = context.player.getLocation().distance(player.getLocation()); - context.sendMessage(format.replace("{playername}", player.getDisplayName()).replace("{distance}", (int) distance + "")); - } - } + double range = FactionsPlugin.getInstance().getConfig().getInt("fnear.Radius"); + String format = TL.COMMAND_NEAR_FORMAT.toString(); + context.msg(TL.COMMAND_NEAR_USE_MSG); + for (Entity e : context.player.getNearbyEntities(range, 255, range)) { + if (e instanceof Player) { + Player player = (((Player) e).getPlayer()); + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (context.faction == fplayer.getFaction()) { + double distance = context.player.getLocation().distance(player.getLocation()); + context.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 373ed801..84f2ea53 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java @@ -9,42 +9,42 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdOpen extends FCommand { - public CmdOpen() { - super(); - this.aliases.add("open"); - this.optionalArgs.put("yes/no", "flip"); + public CmdOpen() { + super(); + this.aliases.add("open"); + this.optionalArgs.put("yes/no", "flip"); - this.requirements = new CommandRequirements.Builder(Permission.OPEN) - .withRole(Role.COLEADER) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.OPEN) + .withRole(Role.COLEADER) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!context.payForCommand(Conf.econCostOpen, TL.COMMAND_OPEN_TOOPEN, TL.COMMAND_OPEN_FOROPEN)) { - return; - } + @Override + public void perform(CommandContext context) { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(Conf.econCostOpen, TL.COMMAND_OPEN_TOOPEN, TL.COMMAND_OPEN_FOROPEN)) { + return; + } - context.faction.setOpen(context.argAsBool(0, !context.faction.getOpen())); + context.faction.setOpen(context.argAsBool(0, !context.faction.getOpen())); - String open = context.faction.getOpen() ? TL.COMMAND_OPEN_OPEN.toString() : TL.COMMAND_OPEN_CLOSED.toString(); + String open = context.faction.getOpen() ? TL.COMMAND_OPEN_OPEN.toString() : TL.COMMAND_OPEN_CLOSED.toString(); - // Inform - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - if (fplayer.getFactionId().equals(context.faction.getId())) { - fplayer.msg(TL.COMMAND_OPEN_CHANGES, context.fPlayer.getName(), open); - continue; - } - fplayer.msg(TL.COMMAND_OPEN_CHANGED, context.faction.getTag(fplayer.getFaction()), open); - } - } + // Inform + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fplayer.getFactionId().equals(context.faction.getId())) { + fplayer.msg(TL.COMMAND_OPEN_CHANGES, context.fPlayer.getName(), open); + continue; + } + fplayer.msg(TL.COMMAND_OPEN_CHANGED, context.faction.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 05c3ec14..02e4a547 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java @@ -8,94 +8,94 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdOwner extends FCommand { - public CmdOwner() { - super(); - this.aliases.add("owner"); - this.optionalArgs.put("player name", "you"); + public CmdOwner() { + super(); + this.aliases.add("owner"); + this.optionalArgs.put("player name", "you"); - this.requirements = new CommandRequirements.Builder(Permission.OWNER) - .withRole(Role.LEADER) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.OWNER) + .withRole(Role.LEADER) + .playerOnly() + .memberOnly() + .build(); + } - // TODO: Fix colors! + // TODO: Fix colors! - @Override - public void perform(CommandContext context) { - boolean hasBypass = context.fPlayer.isAdminBypassing(); + @Override + public void perform(CommandContext context) { + boolean hasBypass = context.fPlayer.isAdminBypassing(); - if (!hasBypass && !context.assertHasFaction()) { - return; - } + if (!hasBypass && !context.assertHasFaction()) { + return; + } - if (!Conf.ownedAreasEnabled) { - context.msg(TL.COMMAND_OWNER_DISABLED); - return; - } + if (!Conf.ownedAreasEnabled) { + context.msg(TL.COMMAND_OWNER_DISABLED); + return; + } - if (!hasBypass && Conf.ownedAreasLimitPerFaction > 0 && context.faction.getCountOfClaimsWithOwners() >= Conf.ownedAreasLimitPerFaction) { - context.msg(TL.COMMAND_OWNER_LIMIT, Conf.ownedAreasLimitPerFaction); - return; - } + if (!hasBypass && Conf.ownedAreasLimitPerFaction > 0 && context.faction.getCountOfClaimsWithOwners() >= Conf.ownedAreasLimitPerFaction) { + context.msg(TL.COMMAND_OWNER_LIMIT, Conf.ownedAreasLimitPerFaction); + return; + } - if (!hasBypass && !context.assertMinRole(Conf.ownedAreasModeratorsCanSet ? Role.MODERATOR : Role.LEADER)) { - return; - } + if (!hasBypass && !context.assertMinRole(Conf.ownedAreasModeratorsCanSet ? Role.MODERATOR : Role.LEADER)) { + return; + } - FLocation flocation = new FLocation(context.fPlayer); + FLocation flocation = new FLocation(context.fPlayer); - Faction factionHere = Board.getInstance().getFactionAt(flocation); - if (factionHere != context.faction) { - if (!factionHere.isNormal()) { - context.msg(TL.COMMAND_OWNER_NOTCLAIMED); - return; - } + Faction factionHere = Board.getInstance().getFactionAt(flocation); + if (factionHere != context.faction) { + if (!factionHere.isNormal()) { + context.msg(TL.COMMAND_OWNER_NOTCLAIMED); + return; + } - if (!hasBypass) { - context.msg(TL.COMMAND_OWNER_WRONGFACTION); - return; - } - } + if (!hasBypass) { + context.msg(TL.COMMAND_OWNER_WRONGFACTION); + return; + } + } - FPlayer target = context.argAsBestFPlayerMatch(0, context.fPlayer); - if (target == null) { - return; - } + FPlayer target = context.argAsBestFPlayerMatch(0, context.fPlayer); + if (target == null) { + return; + } - String playerName = target.getName(); + String playerName = target.getName(); - if (target.getFaction() != context.faction) { - context.msg(TL.COMMAND_OWNER_NOTMEMBER, playerName); - return; - } + if (target.getFaction() != context.faction) { + context.msg(TL.COMMAND_OWNER_NOTMEMBER, playerName); + return; + } - // if no player name was passed, and this claim does already have owners set, clear them - if (context.args.isEmpty() && context.faction.doesLocationHaveOwnersSet(flocation)) { - context.faction.clearClaimOwnership(flocation); - context.msg(TL.COMMAND_OWNER_CLEARED); - return; - } + // if no player name was passed, and this claim does already have owners set, clear them + if (context.args.isEmpty() && context.faction.doesLocationHaveOwnersSet(flocation)) { + context.faction.clearClaimOwnership(flocation); + context.msg(TL.COMMAND_OWNER_CLEARED); + return; + } - if (context.faction.isPlayerInOwnerList(target, flocation)) { - context.faction.removePlayerAsOwner(target, flocation); - context.msg(TL.COMMAND_OWNER_REMOVED, playerName); - return; - } + if (context.faction.isPlayerInOwnerList(target, flocation)) { + context.faction.removePlayerAsOwner(target, flocation); + context.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 (!context.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 (!context.payForCommand(Conf.econCostOwner, TL.COMMAND_OWNER_TOSET, TL.COMMAND_OWNER_FORSET)) { + return; + } - context.faction.setPlayerAsOwner(target, flocation); + context.faction.setPlayerAsOwner(target, flocation); - context.msg(TL.COMMAND_OWNER_ADDED, playerName); - } + context.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 94ce0830..3a9c58d5 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java @@ -9,56 +9,56 @@ 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.requirements = new CommandRequirements.Builder(Permission.OWNERLIST) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.OWNERLIST) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - boolean hasBypass = context.fPlayer.isAdminBypassing(); + @Override + public void perform(CommandContext context) { + boolean hasBypass = context.fPlayer.isAdminBypassing(); - if (!hasBypass && !context.assertHasFaction()) { - return; - } + if (!hasBypass && !context.assertHasFaction()) { + return; + } - if (!Conf.ownedAreasEnabled) { - context.msg(TL.COMMAND_OWNERLIST_DISABLED); - return; - } + if (!Conf.ownedAreasEnabled) { + context.msg(TL.COMMAND_OWNERLIST_DISABLED); + return; + } - FLocation flocation = new FLocation(context.fPlayer); + FLocation flocation = new FLocation(context.fPlayer); - if (Board.getInstance().getFactionAt(flocation) != context.faction) { - if (!hasBypass) { - context.msg(TL.COMMAND_OWNERLIST_WRONGFACTION); - return; - } - //TODO: This code won't ever be called. - context.faction = Board.getInstance().getFactionAt(flocation); - if (!context.faction.isNormal()) { - context.msg(TL.COMMAND_OWNERLIST_NOTCLAIMED); - return; - } - } + if (Board.getInstance().getFactionAt(flocation) != context.faction) { + if (!hasBypass) { + context.msg(TL.COMMAND_OWNERLIST_WRONGFACTION); + return; + } + //TODO: This code won't ever be called. + context.faction = Board.getInstance().getFactionAt(flocation); + if (!context.faction.isNormal()) { + context.msg(TL.COMMAND_OWNERLIST_NOTCLAIMED); + return; + } + } - String owners = context.faction.getOwnerListString(flocation); + String owners = context.faction.getOwnerListString(flocation); - if (owners == null || owners.isEmpty()) { - context.msg(TL.COMMAND_OWNERLIST_NONE); - return; - } + if (owners == null || owners.isEmpty()) { + context.msg(TL.COMMAND_OWNERLIST_NONE); + return; + } - context.msg(TL.COMMAND_OWNERLIST_OWNERS, owners); - } + context.msg(TL.COMMAND_OWNERLIST_OWNERS, owners); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_OWNERLIST_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_OWNERLIST_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSee.java b/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSee.java index cf06d90a..886b9ffd 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSee.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSee.java @@ -6,52 +6,52 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdPaypalSee extends FCommand { - public CmdPaypalSee() { - this.aliases.add("seepaypal"); - this.aliases.add("paypal"); + public CmdPaypalSee() { + this.aliases.add("seepaypal"); + this.aliases.add("paypal"); - this.optionalArgs.put("faction", "yours"); + this.optionalArgs.put("faction", "yours"); - this.requirements = new CommandRequirements.Builder(Permission.PAYPAL) - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.PAYPAL) + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fpaypal.Enabled")) { - context.msg(TL.GENERIC_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fpaypal.Enabled")) { + context.msg(TL.GENERIC_DISABLED); + return; + } - if (context.args.size() == 0) { - if (context.fPlayer.getFaction().getPaypal().isEmpty()) { - context.msg(TL.COMMAND_PAYPAL_NOTSET); - } else { - context.msg(TL.PAYPALSEE_PLAYER_PAYPAL, context.fPlayer.getFaction().getPaypal()); - } - } else if (context.args.size() == 1) { - if (context.fPlayer.isAdminBypassing()) { - Faction faction = context.argAsFaction(0); - if (faction != null) { - if (faction.getPaypal().isEmpty()) { - context.msg(TL.COMMAND_PAYPALSEE_FACTION_NOTSET, faction.getTag()); - } else { - context.msg(TL.COMMAND_PAYPALSEE_FACTION_PAYPAL.toString(), faction.getTag(), faction.getPaypal()); + if (context.args.size() == 0) { + if (context.fPlayer.getFaction().getPaypal().isEmpty()) { + context.msg(TL.COMMAND_PAYPAL_NOTSET); + } else { + context.msg(TL.PAYPALSEE_PLAYER_PAYPAL, context.fPlayer.getFaction().getPaypal()); + } + } else if (context.args.size() == 1) { + if (context.fPlayer.isAdminBypassing()) { + Faction faction = context.argAsFaction(0); + if (faction != null) { + if (faction.getPaypal().isEmpty()) { + context.msg(TL.COMMAND_PAYPALSEE_FACTION_NOTSET, faction.getTag()); + } else { + context.msg(TL.COMMAND_PAYPALSEE_FACTION_PAYPAL.toString(), faction.getTag(), faction.getPaypal()); + } } - } - } else { - context.msg(TL.GENERIC_NOPERMISSION, "see another factions paypal."); - } - } else { - context.msg(FactionsPlugin.getInstance().cmdBase.cmdPaypalSee.getUseageTemplate(context)); - } - } + } else { + context.msg(TL.GENERIC_NOPERMISSION, "see another factions paypal."); + } + } else { + context.msg(FactionsPlugin.getInstance().cmdBase.cmdPaypalSee.getUseageTemplate(context)); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_PAYPALSEE_DESCRIPTION; - } + @Override + 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 0fd58f83..96311085 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSet.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSet.java @@ -7,60 +7,60 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPaypalSet extends FCommand { - public CmdPaypalSet() { - this.aliases.add("setpaypal"); + public CmdPaypalSet() { + this.aliases.add("setpaypal"); - this.optionalArgs.put("faction", "yours"); + this.optionalArgs.put("faction", "yours"); - this.requiredArgs.add("email"); + this.requiredArgs.add("email"); - this.requirements = new CommandRequirements.Builder(Permission.PAYPALSET) - .playerOnly() - .memberOnly() - .build(); + this.requirements = new CommandRequirements.Builder(Permission.PAYPALSET) + .playerOnly() + .memberOnly() + .build(); - } + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fpaypal.Enabled")) { - context.fPlayer.msg(TL.GENERIC_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fpaypal.Enabled")) { + context.fPlayer.msg(TL.GENERIC_DISABLED); + return; + } - if (context.args.size() == 1) { - if (isEmail(context.argAsString(0))) { - context.fPlayer.getFaction().paypalSet(context.argAsString(0)); - context.msg(TL.COMMAND_PAYPALSET_SUCCESSFUL, context.argAsString(0)); - } else { - context.msg(TL.COMMAND_PAYPALSET_NOTEMAIL, context.argAsString(0)); - } - } else if (context.args.size() == 2) { - if (context.fPlayer.isAdminBypassing()) { - Faction faction = context.argAsFaction(1); - if (faction != null) { - if (isEmail(context.argAsString(0))) { - context.fPlayer.getFaction().paypalSet(context.argAsString(0)); - context.msg(TL.COMMAND_PAYPALSET_ADMIN_SUCCESSFUL, faction.getTag(), context.argAsString(0)); - } else { - context.msg(TL.COMMAND_PAYPALSET_ADMIN_FAILED, context.argAsString(0)); + if (context.args.size() == 1) { + if (isEmail(context.argAsString(0))) { + context.fPlayer.getFaction().paypalSet(context.argAsString(0)); + context.msg(TL.COMMAND_PAYPALSET_SUCCESSFUL, context.argAsString(0)); + } else { + context.msg(TL.COMMAND_PAYPALSET_NOTEMAIL, context.argAsString(0)); + } + } else if (context.args.size() == 2) { + if (context.fPlayer.isAdminBypassing()) { + Faction faction = context.argAsFaction(1); + if (faction != null) { + if (isEmail(context.argAsString(0))) { + context.fPlayer.getFaction().paypalSet(context.argAsString(0)); + context.msg(TL.COMMAND_PAYPALSET_ADMIN_SUCCESSFUL, faction.getTag(), context.argAsString(0)); + } else { + context.msg(TL.COMMAND_PAYPALSET_ADMIN_FAILED, context.argAsString(0)); + } } - } - } else { - context.msg(TL.GENERIC_NOPERMISSION, "set another factions paypal!"); - } - } else { - context.msg(FactionsPlugin.getInstance().cmdBase.cmdPaypalSet.getUseageTemplate(context)); - } - } + } else { + context.msg(TL.GENERIC_NOPERMISSION, "set another factions paypal!"); + } + } else { + context.msg(FactionsPlugin.getInstance().cmdBase.cmdPaypalSet.getUseageTemplate(context)); + } + } - private boolean isEmail(String email) { - return email.contains("@") && email.contains("."); - } + private boolean isEmail(String email) { + return email.contains("@") && email.contains("."); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_PAYPALSET_DESCRIPTION; - } + @Override + 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 967b7023..ebd0f911 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java @@ -8,47 +8,47 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPeaceful extends FCommand { - public CmdPeaceful() { - super(); - this.aliases.add("peaceful"); - this.requiredArgs.add("faction tag"); + public CmdPeaceful() { + super(); + this.aliases.add("peaceful"); + this.requiredArgs.add("faction tag"); - this.requirements = new CommandRequirements.Builder(Permission.SET_PEACEFUL) - .build(); + this.requirements = new CommandRequirements.Builder(Permission.SET_PEACEFUL) + .build(); - } + } - @Override - public void perform(CommandContext context) { - Faction faction = context.argAsFaction(0); - if (faction == null) { - return; - } + @Override + public void perform(CommandContext context) { + Faction faction = context.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 = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.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 = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.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 608cc55a..6d4019a7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java @@ -17,102 +17,102 @@ 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.requirements = new CommandRequirements.Builder(Permission.PERMISSIONS) - .playerOnly() - .memberOnly() - .withRole(Role.LEADER) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.PERMISSIONS) + .playerOnly() + .memberOnly() + .withRole(Role.LEADER) + .build(); + } - @Override - public void perform(CommandContext context) { + @Override + public void perform(CommandContext context) { - if (context.args.size() == 0) { - new PermissableRelationFrame(context.faction).buildGUI(context.fPlayer); - return; - } else if (context.args.size() == 1 && getPermissable(context.argAsString(0)) != null) { - new PermissableActionFrame(context.faction).buildGUI(context.fPlayer, getPermissable(context.argAsString(0))); - return; - } + if (context.args.size() == 0) { + new PermissableRelationFrame(context.faction).buildGUI(context.fPlayer); + return; + } else if (context.args.size() == 1 && getPermissable(context.argAsString(0)) != null) { + new PermissableActionFrame(context.faction).buildGUI(context.fPlayer, getPermissable(context.argAsString(0))); + return; + } - // If not opening GUI, then setting the permission manually. - if (context.args.size() != 3) { - context.msg(TL.COMMAND_PERM_DESCRIPTION); - return; - } + // If not opening GUI, then setting the permission manually. + if (context.args.size() != 3) { + context.msg(TL.COMMAND_PERM_DESCRIPTION); + return; + } - Set permissables = new HashSet<>(); - Set permissableActions = new HashSet<>(); + Set permissables = new HashSet<>(); + Set permissableActions = new HashSet<>(); - boolean allRelations = context.argAsString(0).equalsIgnoreCase("all"); - boolean allActions = context.argAsString(1).equalsIgnoreCase("all"); + boolean allRelations = context.argAsString(0).equalsIgnoreCase("all"); + boolean allActions = context.argAsString(1).equalsIgnoreCase("all"); - if (allRelations) { - permissables.addAll(context.faction.getPermissions().keySet()); - } else { - Permissable permissable = getPermissable(context.argAsString(0)); + if (allRelations) { + permissables.addAll(context.faction.getPermissions().keySet()); + } else { + Permissable permissable = getPermissable(context.argAsString(0)); - if (permissable == null) { - context.msg(TL.COMMAND_PERM_INVALID_RELATION); - return; - } + if (permissable == null) { + context.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(context.argAsString(1)); - if (permissableAction == null) { - context.msg(TL.COMMAND_PERM_INVALID_ACTION); - return; - } + if (allActions) { + permissableActions.addAll(Arrays.asList(PermissableAction.values())); + } else { + PermissableAction permissableAction = PermissableAction.fromString(context.argAsString(1)); + if (permissableAction == null) { + context.msg(TL.COMMAND_PERM_INVALID_ACTION); + return; + } - permissableActions.add(permissableAction); - } + permissableActions.add(permissableAction); + } - Access access = Access.fromString(context.argAsString(2)); + Access access = Access.fromString(context.argAsString(2)); - if (access == null) { - context.msg(TL.COMMAND_PERM_INVALID_ACCESS); - return; - } + if (access == null) { + context.msg(TL.COMMAND_PERM_INVALID_ACCESS); + return; + } - for (Permissable permissable : permissables) { - for (PermissableAction permissableAction : permissableActions) { - context.faction.setPermission(permissable, permissableAction, access); - } - } + for (Permissable permissable : permissables) { + for (PermissableAction permissableAction : permissableActions) { + context.faction.setPermission(permissable, permissableAction, access); + } + } - context.msg(TL.COMMAND_PERM_SET, context.argAsString(1), access.name(), context.argAsString(0)); - FactionsPlugin.getInstance().log(String.format(TL.COMMAND_PERM_SET.toString(), context.argAsString(1), access.name(), context.argAsString(0)) + " for faction " + context.fPlayer.getTag()); - } + context.msg(TL.COMMAND_PERM_SET, context.argAsString(1), access.name(), context.argAsString(0)); + FactionsPlugin.getInstance().log(String.format(TL.COMMAND_PERM_SET.toString(), context.argAsString(1), access.name(), context.argAsString(0)) + " for faction " + context.fPlayer.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 58084ca8..41bd8272 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java @@ -10,47 +10,47 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPermanent extends FCommand { - public CmdPermanent() { - super(); - this.aliases.add("permanent"); - this.requiredArgs.add("faction tag"); + public CmdPermanent() { + super(); + this.aliases.add("permanent"); + this.requiredArgs.add("faction tag"); - this.requirements = new CommandRequirements.Builder(Permission.SET_PERMANENT) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SET_PERMANENT) + .build(); + } - @Override - public void perform(CommandContext context) { - Faction faction = context.argAsFaction(0); - if (faction == null) { - return; - } + @Override + public void perform(CommandContext context) { + Faction faction = context.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); - } + String change; + if (faction.isPermanent()) { + change = TL.COMMAND_PERMANENT_REVOKE.toString(); + faction.setPermanent(false); + } else { + change = TL.COMMAND_PERMANENT_GRANT.toString(); + faction.setPermanent(true); + } - FactionsPlugin.getInstance().log((context.fPlayer == null ? "A server admin" : context.fPlayer.getName()) + " " + change + " the faction \"" + faction.getTag() + "\"."); + FactionsPlugin.getInstance().log((context.fPlayer == null ? "A server admin" : context.fPlayer.getName()) + " " + change + " the faction \"" + faction.getTag() + "\"."); - // Inform all players - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - String blame = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.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)); - } - } - } + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + String blame = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.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; - } + @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 8b39c60e..c128dfc2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java @@ -6,47 +6,47 @@ 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"); + public CmdPermanentPower() { + super(); + this.aliases.add("permanentpower"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("power"); - this.requirements = new CommandRequirements.Builder(Permission.SET_PERMANENTPOWER) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SET_PERMANENTPOWER) + .build(); + } - @Override - public void perform(CommandContext context) { - Faction targetFaction = context.argAsFaction(0); - if (targetFaction == null) { - return; - } + @Override + public void perform(CommandContext context) { + Faction targetFaction = context.argAsFaction(0); + if (targetFaction == null) { + return; + } - Integer targetPower = context.argAsInt(1); + Integer targetPower = context.argAsInt(1); - targetFaction.setPermanentPower(targetPower); + targetFaction.setPermanentPower(targetPower); - String change = TL.COMMAND_PERMANENTPOWER_REVOKE.toString(); - if (targetFaction.hasPermanentPower()) { - change = TL.COMMAND_PERMANENTPOWER_GRANT.toString(); - } + String change = TL.COMMAND_PERMANENTPOWER_REVOKE.toString(); + if (targetFaction.hasPermanentPower()) { + change = TL.COMMAND_PERMANENTPOWER_GRANT.toString(); + } - // Inform sender - context.msg(TL.COMMAND_PERMANENTPOWER_SUCCESS, change, targetFaction.describeTo(context.fPlayer)); + // Inform sender + context.msg(TL.COMMAND_PERMANENTPOWER_SUCCESS, change, targetFaction.describeTo(context.fPlayer)); - // Inform all other players - for (FPlayer fplayer : targetFaction.getFPlayersWhereOnline(true)) { - if (fplayer == context.fPlayer) { - continue; - } - String blame = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true)); - fplayer.msg(TL.COMMAND_PERMANENTPOWER_FACTION, blame, change); - } - } + // Inform all other players + for (FPlayer fplayer : targetFaction.getFPlayersWhereOnline(true)) { + if (fplayer == context.fPlayer) { + continue; + } + String blame = (context.fPlayer == null ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(fplayer, true)); + fplayer.msg(TL.COMMAND_PERMANENTPOWER_FACTION, blame, change); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_PERMANENTPOWER_DESCRIPTION; - } + @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 1807df3a..eebdbf72 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPower.java @@ -7,42 +7,42 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPower extends FCommand { - public CmdPower() { - super(); - this.aliases.add("power"); - this.aliases.add("pow"); - this.optionalArgs.put("player name", "you"); + public CmdPower() { + super(); + this.aliases.add("power"); + this.aliases.add("pow"); + this.optionalArgs.put("player name", "you"); - this.requirements = new CommandRequirements.Builder(Permission.POWER) - .build(); + this.requirements = new CommandRequirements.Builder(Permission.POWER) + .build(); - } + } - @Override - public void perform(CommandContext context) { - FPlayer target = context.argAsBestFPlayerMatch(0, context.fPlayer); - if (target == null) { - return; - } + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0, context.fPlayer); + if (target == null) { + return; + } - if (target != context.fPlayer && !Permission.POWER_ANY.has(context.sender, true)) { - return; - } + if (target != context.fPlayer && !Permission.POWER_ANY.has(context.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 (!context.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 (!context.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 + ")"; - context.msg(TL.COMMAND_POWER_POWER, target.describeTo(context.fPlayer, 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 + ")"; + context.msg(TL.COMMAND_POWER_POWER, target.describeTo(context.fPlayer, 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 3872bf76..238217d4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java @@ -9,74 +9,74 @@ import org.bukkit.command.ConsoleCommandSender; 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"); + public CmdPowerBoost() { + super(); + this.aliases.add("powerboost"); + this.requiredArgs.add("plugin|f|player|faction"); + this.requiredArgs.add("name"); + this.requiredArgs.add("# or reset"); - this.requirements = new CommandRequirements.Builder(Permission.POWERBOOST) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.POWERBOOST) + .build(); + } - @Override - public void perform(CommandContext context) { - String type = context.argAsString(0).toLowerCase(); - boolean doPlayer = true; - if (type.equals("f") || type.equals("faction")) { - doPlayer = false; - } else if (!type.equals("plugin") && !type.equals("player")) { - context.msg(TL.COMMAND_POWERBOOST_HELP_1); - context.msg(TL.COMMAND_POWERBOOST_HELP_2); - return; - } + @Override + public void perform(CommandContext context) { + String type = context.argAsString(0).toLowerCase(); + boolean doPlayer = true; + if (type.equals("f") || type.equals("faction")) { + doPlayer = false; + } else if (!type.equals("plugin") && !type.equals("player")) { + context.msg(TL.COMMAND_POWERBOOST_HELP_1); + context.msg(TL.COMMAND_POWERBOOST_HELP_2); + return; + } - Double targetPower = context.argAsDouble(2); - if (targetPower == null) { - if (context.argAsString(2).equalsIgnoreCase("reset")) { - targetPower = 0D; - } else { - context.msg(TL.COMMAND_POWERBOOST_INVALIDNUM); - return; - } - } + Double targetPower = context.argAsDouble(2); + if (targetPower == null) { + if (context.argAsString(2).equalsIgnoreCase("reset")) { + targetPower = 0D; + } else { + context.msg(TL.COMMAND_POWERBOOST_INVALIDNUM); + return; + } + } - String target; + String target; - if (doPlayer) { - FPlayer targetPlayer = context.argAsBestFPlayerMatch(1); - if (targetPlayer == null) { - return; - } + if (doPlayer) { + FPlayer targetPlayer = context.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 = context.argAsFaction(1); - if (targetFaction == null) { - return; - } + if (targetPower != 0) { + targetPower += targetPlayer.getPowerBoost(); + } + targetPlayer.setPowerBoost(targetPower); + target = TL.COMMAND_POWERBOOST_PLAYER.format(targetPlayer.getName()); + } else { + Faction targetFaction = context.argAsFaction(1); + if (targetFaction == null) { + return; + } - if (targetPower != 0) { - targetPower += targetFaction.getPowerBoost(); - } - targetFaction.setPowerBoost(targetPower); - target = TL.COMMAND_POWERBOOST_FACTION.format(targetFaction.getTag()); - } + if (targetPower != 0) { + targetPower += targetFaction.getPowerBoost(); + } + targetFaction.setPowerBoost(targetPower); + target = TL.COMMAND_POWERBOOST_FACTION.format(targetFaction.getTag()); + } - int roundedPower = (int) Math.round(targetPower); - context.msg(TL.COMMAND_POWERBOOST_BOOST, target, roundedPower); - if (!(context.sender instanceof ConsoleCommandSender)) { - FactionsPlugin.getInstance().log(TL.COMMAND_POWERBOOST_BOOSTLOG.toString(), context.fPlayer.getName(), target, roundedPower); - } - } + int roundedPower = (int) Math.round(targetPower); + context.msg(TL.COMMAND_POWERBOOST_BOOST, target, roundedPower); + if (!(context.sender instanceof ConsoleCommandSender)) { + FactionsPlugin.getInstance().log(TL.COMMAND_POWERBOOST_BOOSTLOG.toString(), context.fPlayer.getName(), target, roundedPower); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_POWERBOOST_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_POWERBOOST_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdReload.java b/src/main/java/com/massivecraft/factions/cmd/CmdReload.java index 0ae7517e..b494b5de 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdReload.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdReload.java @@ -7,32 +7,32 @@ 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.requirements = new CommandRequirements.Builder(Permission.RELOAD).build(); - } + this.requirements = new CommandRequirements.Builder(Permission.RELOAD).build(); + } - @Override - public void perform(CommandContext context) { - long timeInitStart = System.currentTimeMillis(); - Conf.load(); - Conf.save(); - FactionsPlugin.getInstance().reloadConfig(); - FactionsPlugin.getInstance().loadLang(); + @Override + public void perform(CommandContext context) { + long timeInitStart = System.currentTimeMillis(); + Conf.load(); + Conf.save(); + FactionsPlugin.getInstance().reloadConfig(); + FactionsPlugin.getInstance().loadLang(); - if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) { - FactionsPlugin.getInstance().factionsFlight = true; - } - long timeReload = (System.currentTimeMillis() - timeInitStart); + if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) { + FactionsPlugin.getInstance().factionsFlight = true; + } + long timeReload = (System.currentTimeMillis() - timeInitStart); - context.msg(TL.COMMAND_RELOAD_TIME, timeReload); - } + context.msg(TL.COMMAND_RELOAD_TIME, timeReload); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_RELOAD_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_RELOAD_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRules.java b/src/main/java/com/massivecraft/factions/cmd/CmdRules.java index 0fce2952..788e2561 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRules.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRules.java @@ -8,80 +8,80 @@ 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.optionalArgs.put("add/remove/set/clear", ""); - this.requirements = new CommandRequirements.Builder(Permission.RULES) - .playerOnly() - .memberOnly() - .noErrorOnManyArgs() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.RULES) + .playerOnly() + .memberOnly() + .noErrorOnManyArgs() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("frules.Enabled")) { - context.msg(TL.COMMAND_RULES_DISABLED_MSG); - return; - } - if (context.args.size() == 0) { - HashMap rules = context.faction.getRulesMap(); - if (rules.size() == 0) { - List ruleList = FactionsPlugin.getInstance().getConfig().getStringList("frules.default-rules"); - context.sendMessage(FactionsPlugin.getInstance().colorList(ruleList)); + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("frules.Enabled")) { + context.msg(TL.COMMAND_RULES_DISABLED_MSG); + return; + } + if (context.args.size() == 0) { + HashMap rules = context.faction.getRulesMap(); + if (rules.size() == 0) { + List ruleList = FactionsPlugin.getInstance().getConfig().getStringList("frules.default-rules"); + context.sendMessage(FactionsPlugin.getInstance().colorList(ruleList)); - } else { - for (int i = 0; i <= rules.size() - 1; i++) { - context.sendMessage(FactionsPlugin.getInstance().color(rules.get(i))); - } - } + } else { + for (int i = 0; i <= rules.size() - 1; i++) { + context.sendMessage(FactionsPlugin.getInstance().color(rules.get(i))); + } + } - } - if (context.args.size() == 1) { - if (context.args.get(0).equalsIgnoreCase("add")) { - context.msg(TL.COMMAND_RULES_ADD_INVALIDARGS); - } - if (context.args.get(0).equalsIgnoreCase("set")) { - context.msg(TL.COMMAND_RULES_SET_INVALIDARGS); - } - if (context.args.get(0).equalsIgnoreCase("remove")) { - context.msg(TL.COMMAND_RULES_REMOVE_INVALIDARGS); - } - if (context.args.get(0).equalsIgnoreCase("clear")) { - context.faction.clearRules(); - context.msg(TL.COMMAND_RULES_CLEAR_SUCCESS); - } + } + if (context.args.size() == 1) { + if (context.args.get(0).equalsIgnoreCase("add")) { + context.msg(TL.COMMAND_RULES_ADD_INVALIDARGS); + } + if (context.args.get(0).equalsIgnoreCase("set")) { + context.msg(TL.COMMAND_RULES_SET_INVALIDARGS); + } + if (context.args.get(0).equalsIgnoreCase("remove")) { + context.msg(TL.COMMAND_RULES_REMOVE_INVALIDARGS); + } + if (context.args.get(0).equalsIgnoreCase("clear")) { + context.faction.clearRules(); + context.msg(TL.COMMAND_RULES_CLEAR_SUCCESS); + } - } - if (context.args.size() >= 2) { - if (context.args.get(0).equalsIgnoreCase("add")) { - String message = ""; - StringBuilder string = new StringBuilder(message); - for (int i = 1; i <= context.args.size() - 1; i++) { - string.append(" " + context.args.get(i)); - } - context.faction.addRule(string.toString()); - context.msg(TL.COMMAND_RULES_ADD_SUCCESS); - } + } + if (context.args.size() >= 2) { + if (context.args.get(0).equalsIgnoreCase("add")) { + String message = ""; + StringBuilder string = new StringBuilder(message); + for (int i = 1; i <= context.args.size() - 1; i++) { + string.append(" " + context.args.get(i)); + } + context.faction.addRule(string.toString()); + context.msg(TL.COMMAND_RULES_ADD_SUCCESS); + } - if (context.args.size() == 2) { - if (context.args.get(0).equalsIgnoreCase("remove")) { - int index = context.argAsInt(1); - context.faction.removeRule(index - 1); - context.msg(TL.COMMAND_RULES_REMOVE_SUCCESS); - } - } + if (context.args.size() == 2) { + if (context.args.get(0).equalsIgnoreCase("remove")) { + int index = context.argAsInt(1); + context.faction.removeRule(index - 1); + context.msg(TL.COMMAND_RULES_REMOVE_SUCCESS); + } + } - } - } + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_RULES_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_RULES_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSB.java b/src/main/java/com/massivecraft/factions/cmd/CmdSB.java index 513bd35e..91bac448 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSB.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSB.java @@ -6,30 +6,30 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSB extends FCommand { - public CmdSB() { - this.aliases.add("sb"); - this.aliases.add("scoreboard"); + public CmdSB() { + this.aliases.add("sb"); + this.aliases.add("scoreboard"); - this.requirements = new CommandRequirements.Builder(Permission.SCOREBOARD) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SCOREBOARD) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - boolean toggleTo = !context.fPlayer.showScoreboard(); - FScoreboard board = FScoreboard.get(context.fPlayer); - if (board == null) { - context.msg(TL.COMMAND_TOGGLESB_DISABLED.toString()); - } else { - context.msg(TL.TOGGLE_SB.toString().replace("{value}", String.valueOf(toggleTo))); - board.setSidebarVisibility(toggleTo); - } - context.fPlayer.setShowScoreboard(toggleTo); - } + @Override + public void perform(CommandContext context) { + boolean toggleTo = !context.fPlayer.showScoreboard(); + FScoreboard board = FScoreboard.get(context.fPlayer); + if (board == null) { + context.msg(TL.COMMAND_TOGGLESB_DISABLED.toString()); + } else { + context.msg(TL.TOGGLE_SB.toString().replace("{value}", String.valueOf(toggleTo))); + board.setSidebarVisibility(toggleTo); + } + context.fPlayer.setShowScoreboard(toggleTo); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SCOREBOARD_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SCOREBOARD_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java b/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java index 32f56822..b0b0ac76 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java @@ -10,28 +10,28 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSaveAll extends FCommand { - public CmdSaveAll() { - super(); - this.aliases.add("saveall"); - this.aliases.add("save"); + public CmdSaveAll() { + super(); + this.aliases.add("saveall"); + this.aliases.add("save"); - this.requirements = new CommandRequirements.Builder(Permission.SAVE) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SAVE) + .build(); + } - @Override - public void perform(CommandContext context) { - FPlayers.getInstance().forceSave(false); - Factions.getInstance().forceSave(false); - Board.getInstance().forceSave(false); - Conf.save(); - ShopConfig.saveShop(); - context.msg(TL.COMMAND_SAVEALL_SUCCESS); - } + @Override + public void perform(CommandContext context) { + FPlayers.getInstance().forceSave(false); + Factions.getInstance().forceSave(false); + Board.getInstance().forceSave(false); + Conf.save(); + ShopConfig.saveShop(); + context.msg(TL.COMMAND_SAVEALL_SUCCESS); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SAVEALL_DESCRIPTION; - } + @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 5c930be5..4d08a473 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java @@ -15,127 +15,127 @@ import java.util.HashMap; 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<>(); - private long interval; - private boolean useParticles; - 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<>(); + private long interval; + private boolean useParticles; + 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"); - this.useParticles = FactionsPlugin.getInstance().getConfig().getBoolean("see-chunk.particles", true); - interval = FactionsPlugin.getInstance().getConfig().getLong("see-chunk.interval", 10L); - if (effect == null) { - effect = ParticleEffect.REDSTONE; - } + this.useParticles = FactionsPlugin.getInstance().getConfig().getBoolean("see-chunk.particles", true); + interval = FactionsPlugin.getInstance().getConfig().getLong("see-chunk.interval", 10L); + if (effect == null) { + effect = ParticleEffect.REDSTONE; + } - this.requirements = new CommandRequirements.Builder(Permission.SEECHUNK) - .playerOnly() - .build(); + this.requirements = new CommandRequirements.Builder(Permission.SEECHUNK) + .playerOnly() + .build(); - } + } - @Override - public void perform(CommandContext context) { - if (seeChunkMap.containsKey(context.player.getName())) { - seeChunkMap.remove(context.player.getName()); - context.msg(TL.COMMAND_SEECHUNK_DISABLED); - } else { - seeChunkMap.put(context.player.getName(), true); - context.msg(TL.COMMAND_SEECHUNK_ENABLED); - manageTask(); - } - } + @Override + public void perform(CommandContext context) { + if (seeChunkMap.containsKey(context.player.getName())) { + seeChunkMap.remove(context.player.getName()); + context.msg(TL.COMMAND_SEECHUNK_DISABLED); + } else { + seeChunkMap.put(context.player.getName(), true); + context.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(FactionsPlugin.getInstance(), () -> { - for (Object nameObject : seeChunkMap.keySet()) { - String name = nameObject + ""; - Player player = Bukkit.getPlayer(name); - showBorders(player); - } - manageTask(); - }, 0, interval); - } + private void startTask() { + taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { + for (Object nameObject : seeChunkMap.keySet()) { + 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 (FactionsPlugin.getInstance().useNonPacketParticles) { + // Dust options only exists in the 1.13 API, so we use an + // alternative method to achieve this in lower versions. + if (FactionsPlugin.getInstance().mc113 || FactionsPlugin.getInstance().mc114) { + 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 (FactionsPlugin.getInstance().useNonPacketParticles) { - // Dust options only exists in the 1.13 API, so we use an - // alternative method to achieve this in lower versions. - if (FactionsPlugin.getInstance().mc113 || FactionsPlugin.getInstance().mc114) { - player.spawnParticle(Particle.REDSTONE, loc, 0, new Particle.DustOptions(Color.RED, 1)); } else { - player.getWorld().spawnParticle(Particle.REDSTONE, loc, 0, 255, 0, 0, 1); + 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 ? XMaterial.REDSTONE_LAMP.parseMaterial() : XMaterial.BLACK_STAINED_GLASS.parseMaterial(); + VisualizeUtil.addLocation(player, loc, type); + } + } + } - } else { - Material type = blockY % 5 == 0 ? XMaterial.REDSTONE_LAMP.parseMaterial() : XMaterial.BLACK_STAINED_GLASS.parseMaterial(); - 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 e5003b77..3d4b1a30 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSetBanner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSetBanner.java @@ -5,31 +5,31 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSetBanner extends FCommand { - public CmdSetBanner() { - super(); - aliases.add("setbanner"); + public CmdSetBanner() { + super(); + aliases.add("setbanner"); - this.requirements = new CommandRequirements.Builder(Permission.BANNER) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.BANNER) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!context.player.getItemInHand().getType().toString().contains("BANNER")) { - context.msg(TL.COMMAND_SETBANNER_NOTBANNER); - return; - } + @Override + public void perform(CommandContext context) { + if (!context.player.getItemInHand().getType().toString().contains("BANNER")) { + context.msg(TL.COMMAND_SETBANNER_NOTBANNER); + return; + } - context.faction.setBannerPattern(context.player.getItemInHand()); - context.msg(TL.COMMAND_SETBANNER_SUCCESS); + context.faction.setBannerPattern(context.player.getItemInHand()); + context.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 ec5464e7..36f69d2a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java @@ -6,41 +6,41 @@ 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.requirements = new CommandRequirements.Builder(Permission.DEFAULTRANK) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.DEFAULTRANK) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Role target = Role.fromString(context.argAsString(0).toUpperCase()); - if (target == null) { - context.msg(TL.COMMAND_SETDEFAULTROLE_INVALIDROLE, context.argAsString(0)); - return; - } + @Override + public void perform(CommandContext context) { + Role target = Role.fromString(context.argAsString(0).toUpperCase()); + if (target == null) { + context.msg(TL.COMMAND_SETDEFAULTROLE_INVALIDROLE, context.argAsString(0)); + return; + } - if (target == Role.LEADER) { - context.msg(TL.COMMAND_SETDEFAULTROLE_NOTTHATROLE, context.argAsString(0)); - return; - } + if (target == Role.LEADER) { + context.msg(TL.COMMAND_SETDEFAULTROLE_NOTTHATROLE, context.argAsString(0)); + return; + } - context.faction.setDefaultRole(target); - context.msg(TL.COMMAND_SETDEFAULTROLE_SUCCESS, target.nicename); - } + context.faction.setDefaultRole(target); + context.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 4986ac9d..70f39883 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSetFWarp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSetFWarp.java @@ -10,61 +10,61 @@ 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.requiredArgs.add("warp name"); - this.optionalArgs.put("password", "password"); + this.aliases.add("setwarp"); + this.aliases.add("sw"); + this.requiredArgs.add("warp name"); + this.optionalArgs.put("password", "password"); - this.requirements = new CommandRequirements.Builder(Permission.SETWARP) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.SETWARP) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETWARP) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.SETWARP) + .build(); + } - @Override - public void perform(CommandContext context) { - if (!(context.fPlayer.getRelationToLocation() == Relation.MEMBER)) { - context.msg(TL.COMMAND_SETFWARP_NOTCLAIMED); - return; - } + @Override + public void perform(CommandContext context) { + if (!(context.fPlayer.getRelationToLocation() == Relation.MEMBER)) { + context.msg(TL.COMMAND_SETFWARP_NOTCLAIMED); + return; + } - String warp = context.argAsString(0); + String warp = context.argAsString(0); - // Checks if warp with same name already exists and ignores maxWarp check if it does. - boolean warpExists = context.faction.isWarp(warp); + // Checks if warp with same name already exists and ignores maxWarp check if it does. + boolean warpExists = context.faction.isWarp(warp); - int maxWarps = FactionsPlugin.getInstance().getConfig().getInt("max-warps", 5); - boolean tooManyWarps = maxWarps <= context.faction.getWarps().size(); - if (tooManyWarps && !warpExists) { - context.msg(TL.COMMAND_SETFWARP_LIMIT, maxWarps); - return; - } + int maxWarps = FactionsPlugin.getInstance().getConfig().getInt("max-warps", 5); + boolean tooManyWarps = maxWarps <= context.faction.getWarps().size(); + if (tooManyWarps && !warpExists) { + context.msg(TL.COMMAND_SETFWARP_LIMIT, maxWarps); + return; + } - if (!transact(context.fPlayer, context)) { - return; - } + if (!transact(context.fPlayer, context)) { + return; + } - String password = context.argAsString(1); + String password = context.argAsString(1); - LazyLocation loc = new LazyLocation(context.player.getLocation()); - context.faction.setWarp(warp, loc); - if (password != null) { - context.faction.setWarpPassword(warp, password); - } - context.msg(TL.COMMAND_SETFWARP_SET, warp, password != null ? password : ""); - } + LazyLocation loc = new LazyLocation(context.player.getLocation()); + context.faction.setWarp(warp, loc); + if (password != null) { + context.faction.setWarpPassword(warp, password); + } + context.msg(TL.COMMAND_SETFWARP_SET, warp, password != null ? password : ""); + } - private boolean transact(FPlayer player, CommandContext context) { - return !FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().getConfig().getDouble("warp-cost.setwarp", 5), TL.COMMAND_SETFWARP_TOSET.toString(), TL.COMMAND_SETFWARP_FORSET.toString()); - } + private boolean transact(FPlayer player, CommandContext context) { + return !FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || context.payForCommand(FactionsPlugin.getInstance().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 0a1e1793..ba981c45 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java @@ -7,36 +7,36 @@ import org.bukkit.ChatColor; public class CmdSetMaxVaults extends FCommand { - public CmdSetMaxVaults() { - this.aliases.add("setmaxvaults"); - this.aliases.add("smv"); - this.requiredArgs.add("faction"); - this.requiredArgs.add("number"); + public CmdSetMaxVaults() { + this.aliases.add("setmaxvaults"); + this.aliases.add("smv"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("number"); - this.requirements = new CommandRequirements.Builder(Permission.SETMAXVAULTS) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETMAXVAULTS) + .build(); + } - @Override - public void perform(CommandContext context) { - Faction targetFaction = context.argAsFaction(0); - int value = context.argAsInt(1, -1); - if (value < 0) { - context.sender.sendMessage(ChatColor.RED + "Number must be greater than 0."); - return; - } + @Override + public void perform(CommandContext context) { + Faction targetFaction = context.argAsFaction(0); + int value = context.argAsInt(1, -1); + if (value < 0) { + context.sender.sendMessage(ChatColor.RED + "Number must be greater than 0."); + return; + } - if (targetFaction == null) { - context.sender.sendMessage(ChatColor.RED + "Couldn't find Faction: " + ChatColor.YELLOW + context.argAsString(0)); - return; - } + if (targetFaction == null) { + context.sender.sendMessage(ChatColor.RED + "Couldn't find Faction: " + ChatColor.YELLOW + context.argAsString(0)); + return; + } - targetFaction.setMaxVaults(value); - context.sender.sendMessage(TL.COMMAND_SETMAXVAULTS_SUCCESS.format(targetFaction.getTag(), value)); - } + targetFaction.setMaxVaults(value); + context.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 4e9785c8..949e268f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java @@ -7,54 +7,54 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSethome extends FCommand { - public CmdSethome() { - this.aliases.add("sethome"); - this.optionalArgs.put("faction tag", "mine"); + public CmdSethome() { + this.aliases.add("sethome"); + this.optionalArgs.put("faction tag", "mine"); - this.requirements = new CommandRequirements.Builder(Permission.SETHOME) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.SETHOME) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETHOME) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.SETHOME) + .build(); + } - @Override - public void perform(CommandContext context) { - if (!Conf.homesEnabled) { - context.msg(TL.COMMAND_SETHOME_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + if (!Conf.homesEnabled) { + context.msg(TL.COMMAND_SETHOME_DISABLED); + return; + } - Faction faction = context.argAsFaction(0, context.faction); - if (faction == null) { - return; - } + Faction faction = context.argAsFaction(0, context.faction); + if (faction == null) { + return; + } - // Can the player set the faction home HERE? - if (!Permission.BYPASS.has(context.player) && - Conf.homesMustBeInClaimedTerritory && - Board.getInstance().getFactionAt(new FLocation(context.player)) != faction) { - context.msg(TL.COMMAND_SETHOME_NOTCLAIMED); - return; - } + // Can the player set the faction home HERE? + if (!Permission.BYPASS.has(context.player) && + Conf.homesMustBeInClaimedTerritory && + Board.getInstance().getFactionAt(new FLocation(context.player)) != faction) { + context.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 (!context.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 (!context.payForCommand(Conf.econCostSethome, TL.COMMAND_SETHOME_TOSET, TL.COMMAND_SETHOME_FORSET)) { + return; + } - faction.setHome(context.player.getLocation()); + faction.setHome(context.player.getLocation()); - faction.msg(TL.COMMAND_SETHOME_SET, context.fPlayer.describeTo(context.faction, true)); - faction.sendMessage(FactionsPlugin.getInstance().cmdBase.cmdHome.getUseageTemplate(context)); - if (faction != context.faction) { - context.msg(TL.COMMAND_SETHOME_SETOTHER, faction.getTag(context.fPlayer)); - } - } + faction.msg(TL.COMMAND_SETHOME_SET, context.fPlayer.describeTo(context.faction, true)); + faction.sendMessage(FactionsPlugin.getInstance().cmdBase.cmdHome.getUseageTemplate(context)); + if (faction != context.faction) { + context.msg(TL.COMMAND_SETHOME_SETOTHER, faction.getTag(context.fPlayer)); + } + } - @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 d3a6e3f1..4775a1a3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdShow.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdShow.java @@ -14,100 +14,100 @@ 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.requirements = new CommandRequirements.Builder(Permission.SHOW).build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SHOW).build(); + } - @Override - public void perform(CommandContext context) { - Faction faction = context.faction; - if (context.argIsSet(0)) - faction = context.argAsFaction(0); + @Override + public void perform(CommandContext context) { + Faction faction = context.faction; + if (context.argIsSet(0)) + faction = context.argAsFaction(0); - if (faction == null) - return; + if (faction == null) + return; - if (context.fPlayer != null && !context.player.getPlayer().hasPermission("factions.show.bypassexempt") - && FactionsPlugin.getInstance().getConfig().getStringList("show-exempt").contains(faction.getTag())) { - context.msg(TL.COMMAND_SHOW_EXEMPT); - return; - } + if (context.fPlayer != null && !context.player.getPlayer().hasPermission("factions.show.bypassexempt") + && FactionsPlugin.getInstance().getConfig().getStringList("show-exempt").contains(faction.getTag())) { + context.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 (!context.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 (!context.payForCommand(Conf.econCostShow, TL.COMMAND_SHOW_TOSHOW, TL.COMMAND_SHOW_FORSHOW)) { + return; + } - List show = FactionsPlugin.getInstance().getConfig().getStringList("show"); - if (show == null || show.isEmpty()) - show = defaults; + List show = FactionsPlugin.getInstance().getConfig().getStringList("show"); + if (show == null || show.isEmpty()) + show = defaults; - if (!faction.isNormal()) { - String tag = faction.getTag(context.fPlayer); - // send header and that's all - String header = show.get(0); - if (TagReplacer.HEADER.contains(header)) { - context.msg(FactionsPlugin.getInstance().txt.titleize(tag)); - } else { - context.msg(FactionsPlugin.getInstance().txt.parse(TagReplacer.FACTION.replace(header, tag))); - } - return; // we only show header for non-normal factions - } + if (!faction.isNormal()) { + String tag = faction.getTag(context.fPlayer); + // send header and that's all + String header = show.get(0); + if (TagReplacer.HEADER.contains(header)) { + context.msg(FactionsPlugin.getInstance().txt.titleize(tag)); + } else { + context.msg(FactionsPlugin.getInstance().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, context.fPlayer, raw); // use relations - if (parsed == null) { - continue; // Due to minimal f show. - } + for (String raw : show) { + String parsed = TagUtil.parsePlain(faction, context.fPlayer, raw); // use relations + if (parsed == null) { + continue; // Due to minimal f show. + } - if (context.fPlayer != null) { - parsed = TagUtil.parsePlaceholders(context.fPlayer.getPlayer(), parsed); - } + if (context.fPlayer != null) { + parsed = TagUtil.parsePlaceholders(context.fPlayer.getPlayer(), parsed); + } - if (TagUtil.hasFancy(parsed)) { - List fancy = TagUtil.parseFancy(faction, context.fPlayer, parsed); - if (fancy != null) - context.sendFancyMessage(fancy); + if (TagUtil.hasFancy(parsed)) { + List fancy = TagUtil.parseFancy(faction, context.fPlayer, parsed); + if (fancy != null) + context.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. - } - context.msg(FactionsPlugin.getInstance().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. + } + context.msg(FactionsPlugin.getInstance().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 9b444895..b2a288aa 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdShowClaims.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdShowClaims.java @@ -8,47 +8,47 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdShowClaims extends FCommand { - public CmdShowClaims() { - this.aliases.add("showclaims"); - this.aliases.add("showclaim"); + public CmdShowClaims() { + this.aliases.add("showclaims"); + this.aliases.add("showclaim"); - this.requirements = new CommandRequirements.Builder(Permission.SHOWCLAIMS) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SHOWCLAIMS) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - context.sendMessage(TL.COMMAND_SHOWCLAIMS_HEADER.toString().replace("{faction}", context.faction.describeTo(context.fPlayer))); - ListMultimap chunkMap = ArrayListMultimap.create(); - String format = TL.COMMAND_SHOWCLAIMS_CHUNKSFORMAT.toString(); - for (FLocation fLocation : context.faction.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); - // made {chunks} blank as I removed the placeholder and people wont update their config :shrug: - context.sendMessage(message.replace("{chunks}", "")); - StringBuilder chunks = new StringBuilder(); - for (String chunkString : chunkMap.get(world)) { - chunks.append(chunkString).append(", "); - if (chunks.toString().length() >= 2000) { - context.sendMessage(chunks.toString()); - chunks.setLength(0); - } - } - if (chunks.length() != 0) context.sendMessage(chunks.toString()); - context.sendMessage(""); - } + @Override + public void perform(CommandContext context) { + context.sendMessage(TL.COMMAND_SHOWCLAIMS_HEADER.toString().replace("{faction}", context.faction.describeTo(context.fPlayer))); + ListMultimap chunkMap = ArrayListMultimap.create(); + String format = TL.COMMAND_SHOWCLAIMS_CHUNKSFORMAT.toString(); + for (FLocation fLocation : context.faction.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); + // made {chunks} blank as I removed the placeholder and people wont update their config :shrug: + context.sendMessage(message.replace("{chunks}", "")); + StringBuilder chunks = new StringBuilder(); + for (String chunkString : chunkMap.get(world)) { + chunks.append(chunkString).append(", "); + if (chunks.toString().length() >= 2000) { + context.sendMessage(chunks.toString()); + chunks.setLength(0); + } + } + if (chunks.length() != 0) context.sendMessage(chunks.toString()); + context.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 fec89067..c02c2ba9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java @@ -10,33 +10,33 @@ import org.bukkit.ChatColor; public class CmdShowInvites extends FCommand { - public CmdShowInvites() { - super(); - aliases.add("showinvites"); + public CmdShowInvites() { + super(); + aliases.add("showinvites"); - this.requirements = new CommandRequirements.Builder(Permission.SHOW_INVITES) - .playerOnly() - .memberOnly() - .build(); + this.requirements = new CommandRequirements.Builder(Permission.SHOW_INVITES) + .playerOnly() + .memberOnly() + .build(); - } + } - @Override - public void perform(CommandContext context) { - FancyMessage msg = new FancyMessage(TL.COMMAND_SHOWINVITES_PENDING.toString()).color(ChatColor.GOLD); - for (String id : context.faction.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(CommandContext context) { + FancyMessage msg = new FancyMessage(TL.COMMAND_SHOWINVITES_PENDING.toString()).color(ChatColor.GOLD); + for (String id : context.faction.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); + } - context.sendFancyMessage(msg); - } + context.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 c961fcce..185b4b5a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java @@ -10,32 +10,32 @@ 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.requirements = new CommandRequirements.Builder(Permission.STATUS) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.STATUS) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - ArrayList ret = new ArrayList<>(); - for (FPlayer fp : context.faction.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()); - } - context.fPlayer.sendMessage(ret); - } + @Override + public void perform(CommandContext context) { + ArrayList ret = new ArrayList<>(); + for (FPlayer fp : context.faction.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()); + } + context.fPlayer.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 89c560dd..71d23962 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java @@ -4,26 +4,26 @@ 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"); + public CmdStealth() { + this.aliases.add("ninja"); + this.aliases.add("stealth"); - this.requirements = new CommandRequirements.Builder(Permission.STEALTH) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.STEALTH) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (context.faction != null && !context.faction.getId().equalsIgnoreCase("0") && !context.faction.getId().equalsIgnoreCase("none") && !context.faction.getId().equalsIgnoreCase("safezone") && !context.faction.getId().equalsIgnoreCase("warzone")) { - context.fPlayer.setStealth(!context.fPlayer.isStealthEnabled()); - context.msg(context.fPlayer.isStealthEnabled() ? TL.COMMAND_STEALTH_ENABLE : TL.COMMAND_STEALTH_DISABLE); - } else { - context.msg(TL.COMMAND_STEALTH_MUSTBEMEMBER); - } - } + @Override + public void perform(CommandContext context) { + if (context.faction != null && !context.faction.getId().equalsIgnoreCase("0") && !context.faction.getId().equalsIgnoreCase("none") && !context.faction.getId().equalsIgnoreCase("safezone") && !context.faction.getId().equalsIgnoreCase("warzone")) { + context.fPlayer.setStealth(!context.fPlayer.isStealthEnabled()); + context.msg(context.fPlayer.isStealthEnabled() ? TL.COMMAND_STEALTH_ENABLE : TL.COMMAND_STEALTH_DISABLE); + } else { + context.msg(TL.COMMAND_STEALTH_MUSTBEMEMBER); + } + } - public TL getUsageTranslation() { - return TL.COMMAND_STEALTH_DESCRIPTION; - } + public TL getUsageTranslation() { + return TL.COMMAND_STEALTH_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStrikes.java b/src/main/java/com/massivecraft/factions/cmd/CmdStrikes.java index 27f8589c..12a6a499 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStrikes.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStrikes.java @@ -7,35 +7,35 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdStrikes extends FCommand { - public CmdStrikesGive cmdStrikesGive = new CmdStrikesGive(); - public CmdStrikesInfo cmdStrikesInfo = new CmdStrikesInfo(); - public CmdStrikesSet cmdStrikesSet = new CmdStrikesSet(); - public CmdStrikesTake cmdStrikesTake = new CmdStrikesTake(); + public CmdStrikesGive cmdStrikesGive = new CmdStrikesGive(); + public CmdStrikesInfo cmdStrikesInfo = new CmdStrikesInfo(); + public CmdStrikesSet cmdStrikesSet = new CmdStrikesSet(); + public CmdStrikesTake cmdStrikesTake = new CmdStrikesTake(); - public CmdStrikes() { - super(); + public CmdStrikes() { + super(); - this.aliases.add("strikes"); + this.aliases.add("strikes"); - this.addSubCommand(cmdStrikesGive); - this.addSubCommand(cmdStrikesInfo); - this.addSubCommand(cmdStrikesSet); - this.addSubCommand(cmdStrikesTake); + this.addSubCommand(cmdStrikesGive); + this.addSubCommand(cmdStrikesInfo); + this.addSubCommand(cmdStrikesSet); + this.addSubCommand(cmdStrikesTake); - this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - context.commandChain.add(this); - FactionsPlugin.getInstance().cmdAutoHelp.execute(context); - } + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + FactionsPlugin.getInstance().cmdAutoHelp.execute(context); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_STRIKES_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKES_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStrikesGive.java b/src/main/java/com/massivecraft/factions/cmd/CmdStrikesGive.java index dff72694..9e02ad1b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStrikesGive.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStrikesGive.java @@ -7,31 +7,31 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdStrikesGive extends FCommand { - public CmdStrikesGive() { - super(); - this.aliases.add("give"); - this.requiredArgs.add(0, "faction"); + public CmdStrikesGive() { + super(); + this.aliases.add("give"); + this.requiredArgs.add(0, "faction"); - this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Faction target = context.argAsFaction(0); - if (target == null || target.isSystemFaction()) { - context.msg(TL.COMMAND_STRIKES_TARGET_INVALID, context.argAsString(0)); - return; - } - target.setStrikes(target.getStrikes() + 1); - context.msg(TL.COMMAND_STRIKES_CHANGED, target.getTag(), target.getStrikes()); - } + @Override + public void perform(CommandContext context) { + Faction target = context.argAsFaction(0); + if (target == null || target.isSystemFaction()) { + context.msg(TL.COMMAND_STRIKES_TARGET_INVALID, context.argAsString(0)); + return; + } + target.setStrikes(target.getStrikes() + 1); + context.msg(TL.COMMAND_STRIKES_CHANGED, target.getTag(), target.getStrikes()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_STRIKESGIVE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKESGIVE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStrikesInfo.java b/src/main/java/com/massivecraft/factions/cmd/CmdStrikesInfo.java index f6d61a5b..058f1bc9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStrikesInfo.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStrikesInfo.java @@ -6,32 +6,32 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdStrikesInfo extends FCommand { - public CmdStrikesInfo() { - super(); - this.aliases.add("info"); - this.optionalArgs.put("target", "faction"); + public CmdStrikesInfo() { + super(); + this.aliases.add("info"); + this.optionalArgs.put("target", "faction"); - this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Faction target = context.argAsFaction(0); - if (target == null) target = context.faction; - if (target.isSystemFaction()) { - context.msg(TL.COMMAND_STRIKES_TARGET_INVALID, context.argAsString(0)); - return; - } - context.msg(TL.COMMAND_STRIKES_INFO, target.getTag(), target.getStrikes()); - } + @Override + public void perform(CommandContext context) { + Faction target = context.argAsFaction(0); + if (target == null) target = context.faction; + if (target.isSystemFaction()) { + context.msg(TL.COMMAND_STRIKES_TARGET_INVALID, context.argAsString(0)); + return; + } + context.msg(TL.COMMAND_STRIKES_INFO, target.getTag(), target.getStrikes()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_STRIKESINFO_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKESINFO_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStrikesSet.java b/src/main/java/com/massivecraft/factions/cmd/CmdStrikesSet.java index e7937a8c..94e5b8d4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStrikesSet.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStrikesSet.java @@ -6,32 +6,32 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdStrikesSet extends FCommand { - public CmdStrikesSet() { - super(); - this.aliases.add("set"); - this.requiredArgs.add(0, "faction"); - this.requiredArgs.add(1, "amount"); + public CmdStrikesSet() { + super(); + this.aliases.add("set"); + this.requiredArgs.add(0, "faction"); + this.requiredArgs.add(1, "amount"); - this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Faction target = context.argAsFaction(0); - if (target == null || target.isSystemFaction()) { - context.msg(TL.COMMAND_STRIKES_TARGET_INVALID, context.argAsString(0)); - return; - } - target.setStrikes(context.argAsInt(1)); - context.msg(TL.COMMAND_STRIKES_CHANGED, target.getTag(), target.getStrikes()); - } + @Override + public void perform(CommandContext context) { + Faction target = context.argAsFaction(0); + if (target == null || target.isSystemFaction()) { + context.msg(TL.COMMAND_STRIKES_TARGET_INVALID, context.argAsString(0)); + return; + } + target.setStrikes(context.argAsInt(1)); + context.msg(TL.COMMAND_STRIKES_CHANGED, target.getTag(), target.getStrikes()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_STRIKESET_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKESET_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStrikesTake.java b/src/main/java/com/massivecraft/factions/cmd/CmdStrikesTake.java index e405a37b..c6df30af 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStrikesTake.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStrikesTake.java @@ -7,32 +7,32 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdStrikesTake extends FCommand { - public CmdStrikesTake() { - super(); - this.aliases.add("take"); - this.requiredArgs.add(0, "faction"); - this.requiredArgs.add(1, "number of strikes"); + public CmdStrikesTake() { + super(); + this.aliases.add("take"); + this.requiredArgs.add(0, "faction"); + this.requiredArgs.add(1, "number of strikes"); - this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETSTRIKES) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Faction target = context.argAsFaction(0); - if (target == null || target.isSystemFaction()) { - context.msg(TL.COMMAND_STRIKES_TARGET_INVALID, context.argAsString(0)); - return; - } - target.setStrikes(target.getStrikes() - context.argAsInt(1)); - context.msg(TL.COMMAND_STRIKES_CHANGED, target.getTag(), target.getStrikes()); - } + @Override + public void perform(CommandContext context) { + Faction target = context.argAsFaction(0); + if (target == null || target.isSystemFaction()) { + context.msg(TL.COMMAND_STRIKES_TARGET_INVALID, context.argAsString(0)); + return; + } + target.setStrikes(target.getStrikes() - context.argAsInt(1)); + context.msg(TL.COMMAND_STRIKES_CHANGED, target.getTag(), target.getStrikes()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_STRIKETAKE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STRIKETAKE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java b/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java index a0a3b9ef..936abc51 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java @@ -13,93 +13,93 @@ import org.bukkit.entity.Player; public class CmdStuck extends FCommand { - public CmdStuck() { - super(); - this.aliases.add("stuck"); - this.aliases.add("halp!"); // halp!c: + public CmdStuck() { + super(); + this.aliases.add("stuck"); + this.aliases.add("halp!"); // halp!c: - this.requirements = new CommandRequirements.Builder(Permission.STUCK) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.STUCK) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - final Player player = context.player; - final Location sentAt = player.getLocation(); - final FLocation chunk = context.fPlayer.getLastStoodAt(); - final long delay = FactionsPlugin.getInstance().getConfig().getLong("hcf.stuck.delay", 30); - final int radius = FactionsPlugin.getInstance().getConfig().getInt("hcf.stuck.radius", 10); + @Override + public void perform(CommandContext context) { + final Player player = context.player; + final Location sentAt = player.getLocation(); + final FLocation chunk = context.fPlayer.getLastStoodAt(); + final long delay = FactionsPlugin.getInstance().getConfig().getLong("hcf.stuck.delay", 30); + final int radius = FactionsPlugin.getInstance().getConfig().getInt("hcf.stuck.radius", 10); - if (FactionsPlugin.getInstance().getStuckMap().containsKey(player.getUniqueId())) { - long wait = FactionsPlugin.getInstance().getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); - String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); - context.msg(TL.COMMAND_STUCK_EXISTS, time); - } else { + if (FactionsPlugin.getInstance().getStuckMap().containsKey(player.getUniqueId())) { + long wait = FactionsPlugin.getInstance().getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); + String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); + context.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 (!context.payForCommand(Conf.econCostStuck, TL.COMMAND_STUCK_TOSTUCK.format(context.fPlayer.getName()), TL.COMMAND_STUCK_FORSTUCK.format(context.fPlayer.getName()))) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(Conf.econCostStuck, TL.COMMAND_STUCK_TOSTUCK.format(context.fPlayer.getName()), TL.COMMAND_STUCK_FORSTUCK.format(context.fPlayer.getName()))) { + return; + } - final int id = Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), new Runnable() { + final int id = Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), new Runnable() { - @Override - public void run() { - if (!FactionsPlugin.getInstance().getStuckMap().containsKey(player.getUniqueId())) { - return; + @Override + public void run() { + if (!FactionsPlugin.getInstance().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) { + context.msg(TL.COMMAND_STUCK_OUTSIDE.format(radius)); + FactionsPlugin.getInstance().getTimers().remove(player.getUniqueId()); + FactionsPlugin.getInstance().getStuckMap().remove(player.getUniqueId()); + return; + } + + final Board board = Board.getInstance(); + // spiral task to find nearest wilderness chunk + new SpiralTask(new FLocation(context.player), radius * 2) { + @Override + public boolean work() { + FLocation chunk = currentFLocation(); + Faction faction = board.getFactionAt(chunk); + int buffer = FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0) - 1; + 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); + context.msg(TL.COMMAND_STUCK_TELEPORT, tp.getBlockX(), tp.getBlockY(), tp.getBlockZ()); + FactionsPlugin.getInstance().getTimers().remove(player.getUniqueId()); + FactionsPlugin.getInstance().getStuckMap().remove(player.getUniqueId()); + if (!Essentials.handleTeleport(player, tp)) { + player.teleport(tp); + FactionsPlugin.getInstance().debug("/f stuck used regular teleport, not essentials!"); + } + this.stop(); + return false; + } + return true; + } + }; } + }, delay * 20).getTaskId(); - // check for world difference or radius exceeding - final World world = chunk.getWorld(); - if (world.getUID() != player.getWorld().getUID() || sentAt.distance(player.getLocation()) > radius) { - context.msg(TL.COMMAND_STUCK_OUTSIDE.format(radius)); - FactionsPlugin.getInstance().getTimers().remove(player.getUniqueId()); - FactionsPlugin.getInstance().getStuckMap().remove(player.getUniqueId()); - return; - } + FactionsPlugin.getInstance().getTimers().put(player.getUniqueId(), System.currentTimeMillis() + (delay * 1000)); + long wait = FactionsPlugin.getInstance().getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); + String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); + context.msg(TL.COMMAND_STUCK_START, time); + FactionsPlugin.getInstance().getStuckMap().put(player.getUniqueId(), id); + } + } - final Board board = Board.getInstance(); - // spiral task to find nearest wilderness chunk - new SpiralTask(new FLocation(context.player), radius * 2) { - @Override - public boolean work() { - FLocation chunk = currentFLocation(); - Faction faction = board.getFactionAt(chunk); - int buffer = FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0) - 1; - 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); - context.msg(TL.COMMAND_STUCK_TELEPORT, tp.getBlockX(), tp.getBlockY(), tp.getBlockZ()); - FactionsPlugin.getInstance().getTimers().remove(player.getUniqueId()); - FactionsPlugin.getInstance().getStuckMap().remove(player.getUniqueId()); - if (!Essentials.handleTeleport(player, tp)) { - player.teleport(tp); - FactionsPlugin.getInstance().debug("/f stuck used regular teleport, not essentials!"); - } - this.stop(); - return false; - } - return true; - } - }; - } - }, delay * 20).getTaskId(); - - FactionsPlugin.getInstance().getTimers().put(player.getUniqueId(), System.currentTimeMillis() + (delay * 1000)); - long wait = FactionsPlugin.getInstance().getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); - String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); - context.msg(TL.COMMAND_STUCK_START, time); - FactionsPlugin.getInstance().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 5c5ab560..8693bff5 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java @@ -13,75 +13,75 @@ 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.requiredArgs.add("faction tag"); - this.requirements = new CommandRequirements.Builder(Permission.TAG) - .withRole(Role.COLEADER) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.TAG) + .withRole(Role.COLEADER) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - String tag = context.argAsString(0); + @Override + public void perform(CommandContext context) { + String tag = context.argAsString(0); - // TODO does not first test cover selfcase? - if (Factions.getInstance().isTagTaken(tag) && !MiscUtil.getComparisonString(tag).equals(context.faction.getComparisonTag())) { - context.msg(TL.COMMAND_TAG_TAKEN); - return; - } + // TODO does not first test cover selfcase? + if (Factions.getInstance().isTagTaken(tag) && !MiscUtil.getComparisonString(tag).equals(context.faction.getComparisonTag())) { + context.msg(TL.COMMAND_TAG_TAKEN); + return; + } - ArrayList errors = MiscUtil.validateTag(tag); - if (errors.size() > 0) { - context.sendMessage(errors); - return; - } + ArrayList errors = MiscUtil.validateTag(tag); + if (errors.size() > 0) { + context.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 (!context.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 (!context.canAffordCommand(Conf.econCostTag, TL.COMMAND_TAG_TOCHANGE.toString())) { + return; + } - // trigger the faction rename event (cancellable) - FactionRenameEvent renameEvent = new FactionRenameEvent(context.fPlayer, tag); - Bukkit.getServer().getPluginManager().callEvent(renameEvent); - if (renameEvent.isCancelled()) { - return; - } + // trigger the faction rename event (cancellable) + FactionRenameEvent renameEvent = new FactionRenameEvent(context.fPlayer, tag); + Bukkit.getServer().getPluginManager().callEvent(renameEvent); + if (renameEvent.isCancelled()) { + return; + } - // then make 'em pay (if applicable) - if (!context.payForCommand(Conf.econCostTag, TL.COMMAND_TAG_TOCHANGE, TL.COMMAND_TAG_FORCHANGE)) { - return; - } + // then make 'em pay (if applicable) + if (!context.payForCommand(Conf.econCostTag, TL.COMMAND_TAG_TOCHANGE, TL.COMMAND_TAG_FORCHANGE)) { + return; + } - String oldtag = context.faction.getTag(); - context.faction.setTag(tag); + String oldtag = context.faction.getTag(); + context.faction.setTag(tag); - // Inform - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - if (fplayer.getFactionId().equals(context.faction.getId())) { - fplayer.msg(TL.COMMAND_TAG_FACTION, context.fPlayer.describeTo(context.faction, true), context.faction.getTag(context.faction)); - continue; - } + // Inform + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fplayer.getFactionId().equals(context.faction.getId())) { + fplayer.msg(TL.COMMAND_TAG_FACTION, context.fPlayer.describeTo(context.faction, true), context.faction.getTag(context.faction)); + continue; + } - // Broadcast the tag change (if applicable) - if (Conf.broadcastTagChanges) { - Faction faction = fplayer.getFaction(); - fplayer.msg(TL.COMMAND_TAG_CHANGED, context.fPlayer.getColorTo(faction) + oldtag, context.faction.getTag(faction)); - } - } + // Broadcast the tag change (if applicable) + if (Conf.broadcastTagChanges) { + Faction faction = fplayer.getFaction(); + fplayer.msg(TL.COMMAND_TAG_CHANGED, context.fPlayer.getColorTo(faction) + oldtag, context.faction.getTag(faction)); + } + } - FTeamWrapper.updatePrefixes(context.faction); - } + FTeamWrapper.updatePrefixes(context.faction); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TAG_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TAG_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java b/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java index 1afcda0d..dba02d24 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java @@ -8,33 +8,33 @@ import com.massivecraft.factions.zcore.util.TextUtil; public class CmdTitle extends FCommand { - public CmdTitle() { - this.aliases.add("title"); - this.requiredArgs.add("player name"); - this.optionalArgs.put("title", ""); + public CmdTitle() { + this.aliases.add("title"); + this.requiredArgs.add("player name"); + this.optionalArgs.put("title", ""); - this.requirements = new CommandRequirements.Builder(Permission.TITLE) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.TITLE) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - FPlayer you = context.argAsBestFPlayerMatch(0); - if (you == null) return; - context.args.remove(0); - String title = TextUtil.implode(context.args, " "); - if (!context.canIAdministerYou(context.fPlayer, you)) return; - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!context.payForCommand(Conf.econCostTitle, TL.COMMAND_TITLE_TOCHANGE, TL.COMMAND_TITLE_FORCHANGE)) return; - you.setTitle(context.sender, title); - // Inform - context.faction.msg(TL.COMMAND_TITLE_CHANGED, context.fPlayer.describeTo(context.faction, true), you.describeTo(context.faction, true)); - } + @Override + public void perform(CommandContext context) { + FPlayer you = context.argAsBestFPlayerMatch(0); + if (you == null) return; + context.args.remove(0); + String title = TextUtil.implode(context.args, " "); + if (!context.canIAdministerYou(context.fPlayer, you)) return; + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(Conf.econCostTitle, TL.COMMAND_TITLE_TOCHANGE, TL.COMMAND_TITLE_FORCHANGE)) return; + you.setTitle(context.sender, title); + // Inform + context.faction.msg(TL.COMMAND_TITLE_CHANGED, context.fPlayer.describeTo(context.faction, true), you.describeTo(context.faction, true)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TITLE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TITLE_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java b/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java index 490ac8cd..953e2d3e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java @@ -6,34 +6,34 @@ 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.requirements = new CommandRequirements.Builder(Permission.TOGGLE_ALLIANCE_CHAT) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.TOGGLE_ALLIANCE_CHAT) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TOGGLEALLIANCECHAT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TOGGLEALLIANCECHAT_DESCRIPTION; + } - @Override - public void perform(CommandContext context) { - if (!Conf.factionOnlyChat) { - context.msg(TL.COMMAND_CHAT_DISABLED.toString()); - return; - } + @Override + public void perform(CommandContext context) { + if (!Conf.factionOnlyChat) { + context.msg(TL.COMMAND_CHAT_DISABLED.toString()); + return; + } - boolean ignoring = context.fPlayer.isIgnoreAllianceChat(); + boolean ignoring = context.fPlayer.isIgnoreAllianceChat(); - context.msg(ignoring ? TL.COMMAND_TOGGLEALLIANCECHAT_UNIGNORE : TL.COMMAND_TOGGLEALLIANCECHAT_IGNORE); - context.fPlayer.setIgnoreAllianceChat(!ignoring); - } + context.msg(ignoring ? TL.COMMAND_TOGGLEALLIANCECHAT_UNIGNORE : TL.COMMAND_TOGGLEALLIANCECHAT_IGNORE); + context.fPlayer.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 cdd20d0c..0598c6f7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTop.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTop.java @@ -12,159 +12,159 @@ import java.util.ArrayList; public class CmdTop extends FCommand { - public CmdTop() { - super(); - this.aliases.add("top"); - this.aliases.add("t"); - this.requiredArgs.add("criteria"); - this.optionalArgs.put("page", "1"); + public CmdTop() { + super(); + this.aliases.add("top"); + this.aliases.add("t"); + this.requiredArgs.add("criteria"); + this.optionalArgs.put("page", "1"); - this.requirements = new CommandRequirements.Builder(Permission.TOP) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.TOP) + .build(); + } - @Override - public void perform(CommandContext context) { - // 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(CommandContext context) { + // 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 = context.argAsString(0); + String criteria = context.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 { - context.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 { + context.msg(TL.COMMAND_TOP_INVALID, criteria); + } - ArrayList lines = new ArrayList<>(); + ArrayList lines = new ArrayList<>(); - final int pageheight = 9; - int pagenumber = context.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 = context.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 = context.sender instanceof Player ? faction.getRelationTo(context.fPlayer).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 = context.sender instanceof Player ? faction.getRelationTo(context.fPlayer).getColor() + faction.getTag() : faction.getTag(); + lines.add(TL.COMMAND_TOP_LINE.format(rank, fac, getValue(faction, criteria))); + rank++; + } - context.sendMessage(lines); - } + context.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 713b5aac..3645a1d4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTpBanner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTpBanner.java @@ -9,37 +9,37 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdTpBanner extends FCommand { - public CmdTpBanner() { - super(); - this.aliases.add("tpbanner"); + public CmdTpBanner() { + super(); + this.aliases.add("tpbanner"); - this.requirements = new CommandRequirements.Builder(Permission.TPBANNER) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.TPBANNER) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Enabled")) { - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Enabled")) { + return; + } - final FactionsPlayerListener fpl = new FactionsPlayerListener(); + final FactionsPlayerListener fpl = new FactionsPlayerListener(); - if (FactionsBlockListener.bannerLocations.containsKey(context.fPlayer.getTag())) { - context.msg(TL.COMMAND_TPBANNER_SUCCESS); - context.doWarmUp(WarmUpUtil.Warmup.BANNER, TL.WARMUPS_NOTIFY_TELEPORT, "Banner", () -> { - context.player.teleport(FactionsBlockListener.bannerLocations.get(context.fPlayer.getTag())); - }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-banner", 0)); - } else { - context.msg(TL.COMMAND_TPBANNER_NOTSET); - } + if (FactionsBlockListener.bannerLocations.containsKey(context.fPlayer.getTag())) { + context.msg(TL.COMMAND_TPBANNER_SUCCESS); + context.doWarmUp(WarmUpUtil.Warmup.BANNER, TL.WARMUPS_NOTIFY_TELEPORT, "Banner", () -> { + context.player.teleport(FactionsBlockListener.bannerLocations.get(context.fPlayer.getTag())); + }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-banner", 0)); + } else { + context.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 fc293630..b041584a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java @@ -8,47 +8,47 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdUnban extends FCommand { - public CmdUnban() { - super(); - this.aliases.add("unban"); - this.requiredArgs.add("target"); + public CmdUnban() { + super(); + this.aliases.add("unban"); + this.requiredArgs.add("target"); - this.requirements = new CommandRequirements.Builder(Permission.BAN) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.BAN) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.BAN) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.BAN) + .build(); + } - @Override - public void perform(CommandContext context) { - // Good on permission checks. Now lets just ban the player. - FPlayer target = context.argAsFPlayer(0); - if (target == null) { - return; // the above method sends a message if fails to find someone. - } + @Override + public void perform(CommandContext context) { + // Good on permission checks. Now lets just ban the player. + FPlayer target = context.argAsFPlayer(0); + if (target == null) { + return; // the above method sends a message if fails to find someone. + } - if (target.getFaction() != context.fPlayer.getFaction()) { - if (target.getFaction().getAccess(context.fPlayer, PermissableAction.BAN) != Access.ALLOW) { - if (!context.fPlayer.isAdminBypassing()) { - context.fPlayer.msg(TL.COMMAND_UNBAN_TARGET_IN_OTHER_FACTION); - } - } - } + if (target.getFaction() != context.fPlayer.getFaction()) { + if (target.getFaction().getAccess(context.fPlayer, PermissableAction.BAN) != Access.ALLOW) { + if (!context.fPlayer.isAdminBypassing()) { + context.fPlayer.msg(TL.COMMAND_UNBAN_TARGET_IN_OTHER_FACTION); + } + } + } - if (!context.faction.isBanned(target)) { - context.msg(TL.COMMAND_UNBAN_NOTBANNED, target.getName()); - return; - } + if (!context.faction.isBanned(target)) { + context.msg(TL.COMMAND_UNBAN_NOTBANNED, target.getName()); + return; + } - context.faction.unban(target); + context.faction.unban(target); - context.msg(TL.COMMAND_UNBAN_UNBANNED, context.fPlayer.getName(), target.getName()); - target.msg(TL.COMMAND_UNBAN_TARGET, context.faction.getTag(target)); - } + context.msg(TL.COMMAND_UNBAN_UNBANNED, context.fPlayer.getName(), target.getName()); + target.msg(TL.COMMAND_UNBAN_TARGET, context.faction.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/CmdUpgrades.java b/src/main/java/com/massivecraft/factions/cmd/CmdUpgrades.java index 898eccf9..e0c3e73a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUpgrades.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUpgrades.java @@ -6,30 +6,30 @@ 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.requirements = new CommandRequirements.Builder(Permission.UPGRADES) - .playerOnly() - .memberOnly() - .build(); + this.requirements = new CommandRequirements.Builder(Permission.UPGRADES) + .playerOnly() + .memberOnly() + .build(); - } + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fupgrades.Enabled")) { - context.fPlayer.sendMessage("This command is disabled!"); - return; - } - new FUpgradesGUI().openMainMenu(context.fPlayer); - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fupgrades.Enabled")) { + context.fPlayer.sendMessage("This command is disabled!"); + return; + } + new FUpgradesGUI().openMainMenu(context.fPlayer); + } - @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 716b0b7b..0885b4fb 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdVault.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdVault.java @@ -13,58 +13,58 @@ import org.bukkit.inventory.Inventory; public class CmdVault extends FCommand { - public CmdVault() { - this.aliases.add("vault"); + public CmdVault() { + this.aliases.add("vault"); - this.requirements = new CommandRequirements.Builder(Permission.VAULT) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.VAULT) - .build(); + this.requirements = new CommandRequirements.Builder(Permission.VAULT) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.VAULT) + .build(); - } + } - @Override - public void perform(CommandContext context) { + @Override + public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fvault.Enabled")) { - context.fPlayer.sendMessage("This command is disabled!"); - return; - } + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fvault.Enabled")) { + context.fPlayer.sendMessage("This command is disabled!"); + return; + } - if (context.fPlayer.isInVault()) { - context.player.closeInventory(); - return; - } + if (context.fPlayer.isInVault()) { + context.player.closeInventory(); + return; + } - context.fPlayer.setInVault(true); - Location vaultLocation = context.faction.getVault(); - if (vaultLocation == null) { - context.msg(TL.COMMAND_VAULT_INVALID); - return; - } - FLocation vaultFLocation = new FLocation(vaultLocation); - if (Board.getInstance().getFactionAt(vaultFLocation) != context.faction) { - context.faction.setVault(null); - context.msg(TL.COMMAND_VAULT_INVALID); - return; - } - if (vaultLocation.getBlock().getType() != Material.CHEST) { - context.faction.setVault(null); - context.msg(TL.COMMAND_VAULT_INVALID); - return; - } - Chest chest = (Chest) vaultLocation.getBlock().getState(); - Inventory chestInv = chest.getBlockInventory(); - context.msg(TL.COMMAND_VAULT_OPENING); - context.player.openInventory(chestInv); + context.fPlayer.setInVault(true); + Location vaultLocation = context.faction.getVault(); + if (vaultLocation == null) { + context.msg(TL.COMMAND_VAULT_INVALID); + return; + } + FLocation vaultFLocation = new FLocation(vaultLocation); + if (Board.getInstance().getFactionAt(vaultFLocation) != context.faction) { + context.faction.setVault(null); + context.msg(TL.COMMAND_VAULT_INVALID); + return; + } + if (vaultLocation.getBlock().getType() != Material.CHEST) { + context.faction.setVault(null); + context.msg(TL.COMMAND_VAULT_INVALID); + return; + } + Chest chest = (Chest) vaultLocation.getBlock().getState(); + Inventory chestInv = chest.getBlockInventory(); + context.msg(TL.COMMAND_VAULT_OPENING); + context.player.openInventory(chestInv); - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_VAULT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_VAULT_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java b/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java index 3943a863..be7a4e60 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java @@ -7,22 +7,22 @@ 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.requirements = new CommandRequirements.Builder(Permission.VERSION) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.VERSION) + .build(); + } - @Override - public void perform(CommandContext context) { - context.msg(TL.COMMAND_VERSION_NAME); // Did this so people can differentiate between SavageFactions and FactionsUUID (( Requested Feature )) - context.msg(TL.COMMAND_VERSION_VERSION, FactionsPlugin.getInstance().getDescription().getFullName()); - } + @Override + public void perform(CommandContext context) { + context.msg(TL.COMMAND_VERSION_NAME); // Did this so people can differentiate between SavageFactions and FactionsUUID (( Requested Feature )) + context.msg(TL.COMMAND_VERSION_VERSION, FactionsPlugin.getInstance().getDescription().getFullName()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_VERSION_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_VERSION_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdViewChest.java b/src/main/java/com/massivecraft/factions/cmd/CmdViewChest.java index d7af8c36..d64eb946 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdViewChest.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdViewChest.java @@ -7,37 +7,37 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdViewChest extends FCommand { - public CmdViewChest() { - super(); - this.aliases.add("viewchest"); - this.aliases.add("viewpv"); + public CmdViewChest() { + super(); + this.aliases.add("viewchest"); + this.aliases.add("viewpv"); - this.requiredArgs.add("faction name"); + this.requiredArgs.add("faction name"); - this.requirements = new CommandRequirements.Builder(Permission.VIEWCHEST) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.VIEWCHEST) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fchest.Enabled")) { - context.msg(TL.GENERIC_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fchest.Enabled")) { + context.msg(TL.GENERIC_DISABLED); + return; + } - Faction myFaction = context.fPlayer.getFaction(); + Faction myFaction = context.fPlayer.getFaction(); - Faction faction = context.argAsFaction(0, context.fPlayer == null ? null : myFaction); - if (faction == null) { - return; - } - context.player.openInventory(context.faction.getChestInventory()); - } + Faction faction = context.argAsFaction(0, context.fPlayer == null ? null : myFaction); + if (faction == null) { + return; + } + context.player.openInventory(context.faction.getChestInventory()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_VIEWCHEST_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_VIEWCHEST_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CommandContext.java b/src/main/java/com/massivecraft/factions/cmd/CommandContext.java index b438b997..6bc76012 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CommandContext.java +++ b/src/main/java/com/massivecraft/factions/cmd/CommandContext.java @@ -19,400 +19,400 @@ import java.util.List; */ public class CommandContext { - public CommandSender sender; + public CommandSender sender; - public Player player; - public FPlayer fPlayer; - public Faction faction; + public Player player; + public FPlayer fPlayer; + public Faction faction; - public List args; - public String alias; + public List args; + public String alias; - public List commandChain = new ArrayList<>(); // The command chain used to execute this command + public List commandChain = new ArrayList<>(); // The command chain used to execute this command - public CommandContext(CommandSender sender, List args, String alias) { - this.sender = sender; - this.args = args; - this.alias = alias; + public CommandContext(CommandSender sender, List args, String alias) { + this.sender = sender; + this.args = args; + this.alias = alias; - if (sender instanceof Player) { - this.player = (Player) sender; - this.fPlayer = FPlayers.getInstance().getByPlayer(player); - this.faction = fPlayer.getFaction(); - } - } + if (sender instanceof Player) { + this.player = (Player) sender; + this.fPlayer = FPlayers.getInstance().getByPlayer(player); + this.faction = fPlayer.getFaction(); + } + } - // -------------------------------------------- // - // Message Sending Helpers - // -------------------------------------------- // + // -------------------------------------------- // + // Message Sending Helpers + // -------------------------------------------- // - public void msg(String str, Object... args) { - sender.sendMessage(FactionsPlugin.getInstance().txt.parse(str, args)); - } + public void msg(String str, Object... args) { + sender.sendMessage(FactionsPlugin.getInstance().txt.parse(str, args)); + } - public void msg(TL translation, Object... args) { - sender.sendMessage(FactionsPlugin.getInstance().txt.parse(translation.toString(), args)); - } + public void msg(TL translation, Object... args) { + sender.sendMessage(FactionsPlugin.getInstance().txt.parse(translation.toString(), args)); + } - public void sendMessage(String msg) { - sender.sendMessage(msg); - } + public void sendMessage(String msg) { + sender.sendMessage(msg); + } - public void sendMessage(List msgs) { - for (String msg : msgs) { - this.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(FancyMessage message) { + message.send(sender); + } - public void sendFancyMessage(List messages) { - for (FancyMessage m : messages) { - sendFancyMessage(m); - } - } + public void sendFancyMessage(List messages) { + for (FancyMessage m : messages) { + sendFancyMessage(m); + } + } - // TODO: Clean this UP - // -------------------------------------------- // - // Argument Readers - // -------------------------------------------- // + // TODO: Clean this UP + // -------------------------------------------- // + // Argument Readers + // -------------------------------------------- // - // Is set? ====================== - public boolean argIsSet(int idx) { - return args.size() >= idx + 1; - } + // Is set? ====================== + public boolean argIsSet(int idx) { + return args.size() >= idx + 1; + } - // STRING ====================== - public String argAsString(int idx, String def) { - if (args.size() < idx + 1) { - return def; - } - return args.get(idx); - } + // STRING ====================== + public String argAsString(int idx, String def) { + if (args.size() < idx + 1) { + return def; + } + return args.get(idx); + } - public String argAsString(int idx) { - return argAsString(idx, null); - } + public String argAsString(int idx) { + return 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; - } - } + // 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(argAsString(idx), def); - } + public Integer argAsInt(int idx, Integer def) { + return strAsInt(argAsString(idx), def); + } - public Integer argAsInt(int idx) { - return argAsInt(idx, null); - } + public Integer argAsInt(int idx) { + return 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; - } - } + // 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(argAsString(idx), def); - } + public Double argAsDouble(int idx, Double def) { + return strAsDouble(argAsString(idx), def); + } - public Double argAsDouble(int idx) { - return argAsDouble(idx, null); - } + public Double argAsDouble(int idx) { + return 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"); - } + // 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 = argAsString(idx); - if (str == null) { - return def; - } + public Boolean argAsBool(int idx, boolean def) { + String str = argAsString(idx); + if (str == null) { + return def; + } - return strAsBool(str); - } + return strAsBool(str); + } - public Boolean argAsBool(int idx) { - return argAsBool(idx, false); - } + public Boolean argAsBool(int idx) { + return argAsBool(idx, false); + } - // PLAYER ====================== - public Player strAsPlayer(String name, Player def, boolean msg) { - Player ret = def; + // 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 (name != null) { + Player player = Bukkit.getServer().getPlayer(name); + if (player != null) { + ret = player; + } + } - if (msg && ret == null) { - sender.sendMessage(TL.GENERIC_NOPLAYERFOUND.format(name)); - } + if (msg && ret == null) { + sender.sendMessage(TL.GENERIC_NOPLAYERFOUND.format(name)); + } - return ret; - } + return ret; + } - public Player argAsPlayer(int idx, Player def, boolean msg) { - return this.strAsPlayer(argAsString(idx), def, msg); - } + public Player argAsPlayer(int idx, Player def, boolean msg) { + return this.strAsPlayer(argAsString(idx), def, msg); + } - public Player argAsPlayer(int idx, Player def) { - return argAsPlayer(idx, def, true); - } + public Player argAsPlayer(int idx, Player def) { + return argAsPlayer(idx, def, true); + } - public Player argAsPlayer(int idx) { - return argAsPlayer(idx, null); - } + public Player argAsPlayer(int idx) { + return argAsPlayer(idx, null); + } - // BEST PLAYER MATCH ====================== - public Player strAsBestPlayerMatch(String name, Player def, boolean msg) { - Player ret = def; + // 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 (name != null) { + List players = Bukkit.getServer().matchPlayer(name); + if (players.size() > 0) { + ret = players.get(0); + } + } - if (msg && ret == null) { - sender.sendMessage(TL.GENERIC_NOPLAYERMATCH.format(name)); - } + if (msg && ret == null) { + sender.sendMessage(TL.GENERIC_NOPLAYERMATCH.format(name)); + } - return ret; - } + return ret; + } - public Player argAsBestPlayerMatch(int idx, Player def, boolean msg) { - return this.strAsBestPlayerMatch(argAsString(idx), def, msg); - } + public Player argAsBestPlayerMatch(int idx, Player def, boolean msg) { + return this.strAsBestPlayerMatch(argAsString(idx), def, msg); + } - public Player argAsBestPlayerMatch(int idx, Player def) { - return argAsBestPlayerMatch(idx, def, true); - } + public Player argAsBestPlayerMatch(int idx, Player def) { + return argAsBestPlayerMatch(idx, def, true); + } - public Player argAsBestPlayerMatch(int idx) { - return argAsPlayer(idx, null); - } + public Player argAsBestPlayerMatch(int idx) { + return argAsPlayer(idx, null); + } - // -------------------------------------------- // - // Faction Argument Readers - // -------------------------------------------- // + // -------------------------------------------- // + // Faction Argument Readers + // -------------------------------------------- // - // FPLAYER ====================== - public FPlayer strAsFPlayer(String name, FPlayer def, boolean msg) { - FPlayer ret = def; + // 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 (name != null) { + for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { + if (fplayer.getName().equalsIgnoreCase(name)) { + ret = fplayer; + break; + } + } + } - if (msg && ret == null) { - msg(TL.GENERIC_NOPLAYERFOUND, name); - } + if (msg && ret == null) { + msg(TL.GENERIC_NOPLAYERFOUND, name); + } - return ret; - } + return ret; + } - public FPlayer argAsFPlayer(int idx, FPlayer def, boolean msg) { - return this.strAsFPlayer(argAsString(idx), def, msg); - } + public FPlayer argAsFPlayer(int idx, FPlayer def, boolean msg) { + return this.strAsFPlayer(argAsString(idx), def, msg); + } - public FPlayer argAsFPlayer(int idx, FPlayer def) { - return argAsFPlayer(idx, def, true); - } + public FPlayer argAsFPlayer(int idx, FPlayer def) { + return argAsFPlayer(idx, def, true); + } - public FPlayer argAsFPlayer(int idx) { - return argAsFPlayer(idx, null); - } + public FPlayer argAsFPlayer(int idx) { + return argAsFPlayer(idx, null); + } - // BEST FPLAYER MATCH ====================== - public FPlayer strAsBestFPlayerMatch(String name, FPlayer def, boolean msg) { - return strAsFPlayer(name, def, msg); - } + // 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(argAsString(idx), def, msg); - } + public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def, boolean msg) { + return this.strAsBestFPlayerMatch(argAsString(idx), def, msg); + } - public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def) { - return argAsBestFPlayerMatch(idx, def, true); - } + public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def) { + return argAsBestFPlayerMatch(idx, def, true); + } - public FPlayer argAsBestFPlayerMatch(int idx) { - return argAsBestFPlayerMatch(idx, null); - } + public FPlayer argAsBestFPlayerMatch(int idx) { + return argAsBestFPlayerMatch(idx, null); + } - // FACTION ====================== - public Faction strAsFaction(String name, Faction def, boolean msg) { - Faction ret = def; + // 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. + 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(); - } - } + // 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 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(); - } - } + // 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 (faction != null) { + ret = faction; + } + } - if (msg && ret == null) { - sender.sendMessage(TL.GENERIC_NOFACTION_FOUND.format(name)); - } + if (msg && ret == null) { + sender.sendMessage(TL.GENERIC_NOFACTION_FOUND.format(name)); + } - return ret; - } + return ret; + } - public Faction argAsFaction(int idx, Faction def, boolean msg) { - return this.strAsFaction(argAsString(idx), def, msg); - } + public Faction argAsFaction(int idx, Faction def, boolean msg) { + return this.strAsFaction(argAsString(idx), def, msg); + } - public Faction argAsFaction(int idx, Faction def) { - return argAsFaction(idx, def, true); - } + public Faction argAsFaction(int idx, Faction def) { + return argAsFaction(idx, def, true); + } - public Faction argAsFaction(int idx) { - return argAsFaction(idx, null); - } + public Faction argAsFaction(int idx) { + return argAsFaction(idx, null); + } /* Assertions */ - public boolean assertHasFaction() { - if (player == null) { - return true; - } + public boolean assertHasFaction() { + if (player == null) { + return true; + } - if (!fPlayer.hasFaction()) { - sendMessage("You are not member of any faction."); - return false; - } - return true; - } + if (!fPlayer.hasFaction()) { + sendMessage("You are not member of any faction."); + return false; + } + return true; + } - public boolean assertMinRole(Role role) { - if (player == null) { - return true; - } + public boolean assertMinRole(Role role) { + if (player == null) { + return true; + } - if (fPlayer.getRole().value < role.value) { - msg("You must be " + role); - return false; - } - return true; - } + if (fPlayer.getRole().value < role.value) { + msg("You must be " + role); + return false; + } + return true; + } - /* - Common Methods - */ - public boolean canIAdministerYou(FPlayer i, FPlayer you) { - if (!i.getFaction().equals(you.getFaction())) { - i.msg(TL.COMMAND_CONTEXT_ADMINISTER_DIF_FACTION, you.describeTo(i, true)); - return false; - } + /* + Common Methods + */ + public boolean canIAdministerYou(FPlayer i, FPlayer you) { + if (!i.getFaction().equals(you.getFaction())) { + i.msg(TL.COMMAND_CONTEXT_ADMINISTER_DIF_FACTION, you.describeTo(i, true)); + return false; + } - if (i.getRole().value > you.getRole().value || i.getRole().equals(Role.LEADER)) return true; + if (i.getRole().value > you.getRole().value || i.getRole().equals(Role.LEADER)) return true; - if (you.getRole().equals(Role.LEADER)) i.msg(TL.COMMAND_CONTEXT_ADMINISTER_ADMIN_REQUIRED); + if (you.getRole().equals(Role.LEADER)) i.msg(TL.COMMAND_CONTEXT_ADMINISTER_ADMIN_REQUIRED); - else if (i.getRole().equals(Role.MODERATOR)) { + else if (i.getRole().equals(Role.MODERATOR)) { - if (i == you) return true; //Moderators can control themselves - else i.msg(TL.COMMAND_CONTEXT_ADMINISTER_SAME_RANK_CONTROL); + if (i == you) return true; //Moderators can control themselves + else i.msg(TL.COMMAND_CONTEXT_ADMINISTER_SAME_RANK_CONTROL); - } else i.msg(TL.COMMAND_CONTEXT_ADMINISTER_MOD_REQUIRED); + } else i.msg(TL.COMMAND_CONTEXT_ADMINISTER_MOD_REQUIRED); - return false; - } + 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.fPlayer == null || cost == 0.0 || fPlayer.isAdminBypassing()) { - return true; - } + // 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.fPlayer == null || cost == 0.0 || fPlayer.isAdminBypassing()) { + return true; + } - if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fPlayer.hasFaction()) { - return Econ.modifyMoney(faction, -cost, toDoThis, forDoingThis); - } else { - return Econ.modifyMoney(fPlayer, -cost, toDoThis, forDoingThis); - } - } + if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fPlayer.hasFaction()) { + return Econ.modifyMoney(faction, -cost, toDoThis, forDoingThis); + } else { + return Econ.modifyMoney(fPlayer, -cost, toDoThis, forDoingThis); + } + } - public boolean payForCommand(double cost, TL toDoThis, TL forDoingThis) { - return payForCommand(cost, toDoThis.toString(), forDoingThis.toString()); - } + 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() || fPlayer == null || cost == 0.0 || fPlayer.isAdminBypassing()) { - return true; - } + // 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() || fPlayer == null || cost == 0.0 || fPlayer.isAdminBypassing()) { + return true; + } - if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fPlayer.hasFaction()) { - return Econ.hasAtLeast(faction, cost, toDoThis); - } else { - return Econ.hasAtLeast(fPlayer, cost, toDoThis); - } - } + if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fPlayer.hasFaction()) { + return Econ.hasAtLeast(faction, cost, toDoThis); + } else { + return Econ.hasAtLeast(fPlayer, cost, toDoThis); + } + } - public void doWarmUp(WarmUpUtil.Warmup warmup, TL translationKey, String action, Runnable runnable, long delay) { - this.doWarmUp(fPlayer, warmup, translationKey, action, runnable, delay); - } + public void doWarmUp(WarmUpUtil.Warmup warmup, TL translationKey, String action, Runnable runnable, long delay) { + this.doWarmUp(fPlayer, 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 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/CommandRequirements.java b/src/main/java/com/massivecraft/factions/cmd/CommandRequirements.java index bc75c6c6..bf478f3a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CommandRequirements.java +++ b/src/main/java/com/massivecraft/factions/cmd/CommandRequirements.java @@ -9,147 +9,147 @@ import com.massivecraft.factions.zcore.util.TL; public class CommandRequirements { - // Permission required to execute command - public Permission permission; + // Permission required to execute command + public Permission permission; - // Must be player - public boolean playerOnly; - // Must be member of faction - public boolean memberOnly; + // Must be player + public boolean playerOnly; + // Must be member of faction + public boolean memberOnly; - // Must be atleast this role - public Role role; + // Must be atleast this role + public Role role; - // PermissableAction check if the player has allow for this before checking the role - public PermissableAction action; + // PermissableAction check if the player has allow for this before checking the role + public PermissableAction action; - // Commodore stuffs - public Class brigadier; + // Commodore stuffs + public Class brigadier; - // Edge case handling - public boolean errorOnManyArgs; - public boolean disableOnLock; + // Edge case handling + public boolean errorOnManyArgs; + public boolean disableOnLock; - private CommandRequirements(Permission permission, boolean playerOnly, boolean memberOnly, Role role, PermissableAction action, Class brigadier) { - this.permission = permission; - this.playerOnly = playerOnly; - this.memberOnly = memberOnly; - this.role = role; - this.action = action; - this.brigadier = brigadier; - } + private CommandRequirements(Permission permission, boolean playerOnly, boolean memberOnly, Role role, PermissableAction action, Class brigadier) { + this.permission = permission; + this.playerOnly = playerOnly; + this.memberOnly = memberOnly; + this.role = role; + this.action = action; + this.brigadier = brigadier; + } - public boolean computeRequirements(CommandContext context, boolean informIfNot) { - // Did not modify CommandRequirements return true - if (permission == null) { - return true; - } + public boolean computeRequirements(CommandContext context, boolean informIfNot) { + // Did not modify CommandRequirements return true + if (permission == null) { + return true; + } - if (context.player != null) { - // Is Player - if (!context.fPlayer.hasFaction() && memberOnly) { - if (informIfNot) context.msg(TL.GENERIC_MEMBERONLY); - return false; - } - - if (!FactionsPlugin.getInstance().perm.has(context.sender, permission.node, informIfNot)) return false; - - // Permissable Action provided compute that before role - if (action != null) { - if (context.fPlayer.getRole() == Role.LEADER) return true; - Access access = context.faction.getAccess(context.fPlayer, action); - if (access == Access.DENY) { - if (informIfNot) context.msg(TL.GENERIC_FPERM_NOPERMISSION, action.getName()); + if (context.player != null) { + // Is Player + if (!context.fPlayer.hasFaction() && memberOnly) { + if (informIfNot) context.msg(TL.GENERIC_MEMBERONLY); return false; - } + } - if (access != Access.ALLOW) { - // They have undefined assert their role - if (role != null && !context.fPlayer.getRole().isAtLeast(role)) { - // They do not fullfill the role - if (informIfNot) context.msg(TL.GENERIC_YOUMUSTBE, role.translation); - return false; + if (!FactionsPlugin.getInstance().perm.has(context.sender, permission.node, informIfNot)) return false; + + // Permissable Action provided compute that before role + if (action != null) { + if (context.fPlayer.getRole() == Role.LEADER) return true; + Access access = context.faction.getAccess(context.fPlayer, action); + if (access == Access.DENY) { + if (informIfNot) context.msg(TL.GENERIC_FPERM_NOPERMISSION, action.getName()); + return false; } - } - // They have been explicitly allowed - return true; - } else { - if ((role != null && !context.fPlayer.getRole().isAtLeast(role)) && informIfNot) { - context.msg(TL.GENERIC_YOUMUSTBE, role.translation); - } - return role == null || context.fPlayer.getRole().isAtLeast(role); - } - } else { - if (playerOnly) { - if (informIfNot) context.sender.sendMessage(TL.GENERIC_PLAYERONLY.toString()); - return false; - } - return context.sender.hasPermission(permission.node); - } - } - public static class Builder { + if (access != Access.ALLOW) { + // They have undefined assert their role + if (role != null && !context.fPlayer.getRole().isAtLeast(role)) { + // They do not fullfill the role + if (informIfNot) context.msg(TL.GENERIC_YOUMUSTBE, role.translation); + return false; + } + } + // They have been explicitly allowed + return true; + } else { + if ((role != null && !context.fPlayer.getRole().isAtLeast(role)) && informIfNot) { + context.msg(TL.GENERIC_YOUMUSTBE, role.translation); + } + return role == null || context.fPlayer.getRole().isAtLeast(role); + } + } else { + if (playerOnly) { + if (informIfNot) context.sender.sendMessage(TL.GENERIC_PLAYERONLY.toString()); + return false; + } + return context.sender.hasPermission(permission.node); + } + } - private Permission permission; + public static class Builder { - private boolean playerOnly = false; - private boolean memberOnly = false; + private Permission permission; - private Role role = null; - private PermissableAction action; + private boolean playerOnly = false; + private boolean memberOnly = false; - private Class brigadier; + private Role role = null; + private PermissableAction action; - private boolean errorOnManyArgs = true; - private boolean disableOnLock = true; + private Class brigadier; - public Builder(Permission permission) { - this.permission = permission; - } + private boolean errorOnManyArgs = true; + private boolean disableOnLock = true; - public Builder playerOnly() { - playerOnly = true; - return this; - } + public Builder(Permission permission) { + this.permission = permission; + } - public Builder memberOnly() { - playerOnly = true; - memberOnly = true; - return this; - } + public Builder playerOnly() { + playerOnly = true; + return this; + } - public Builder withRole(Role role) { - this.role = role; - return this; - } + public Builder memberOnly() { + playerOnly = true; + memberOnly = true; + return this; + } - public Builder withAction(PermissableAction action) { - this.action = action; - return this; - } + public Builder withRole(Role role) { + this.role = role; + return this; + } - public Builder brigadier(Class brigadier) { - this.brigadier = brigadier; - return this; - } + public Builder withAction(PermissableAction action) { + this.action = action; + return this; + } - public CommandRequirements build() { - CommandRequirements requirements = new CommandRequirements(permission, playerOnly, memberOnly, role, action, brigadier); - requirements.errorOnManyArgs = errorOnManyArgs; - requirements.disableOnLock = disableOnLock; - return requirements; - } + public Builder brigadier(Class brigadier) { + this.brigadier = brigadier; + return this; + } - public Builder noErrorOnManyArgs() { - errorOnManyArgs = false; - return this; - } + public CommandRequirements build() { + CommandRequirements requirements = new CommandRequirements(permission, playerOnly, memberOnly, role, action, brigadier); + requirements.errorOnManyArgs = errorOnManyArgs; + requirements.disableOnLock = disableOnLock; + return requirements; + } - public Builder noDisableOnLock() { - disableOnLock = false; - return this; - } + public Builder noErrorOnManyArgs() { + errorOnManyArgs = false; + return this; + } - } + public Builder noDisableOnLock() { + disableOnLock = false; + return this; + } + + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java b/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java index f43d274d..da43b636 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java @@ -36,307 +36,307 @@ import java.util.logging.Level; public class FCmdRoot extends FCommand implements CommandExecutor { - public BrigadierManager brigadierManager; + public BrigadierManager brigadierManager; - 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 CmdGrace cmdGrace = new CmdGrace(); - 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 CmdAlts cmdAlts = new CmdAlts(); - public CmdCorner cmdCorner = new CmdCorner(); - public CmdInventorySee cmdInventorySee = new CmdInventorySee(); - public CmdFGlobal cmdFGlobal = new CmdFGlobal(); - public CmdViewChest cmdViewChest = new CmdViewChest(); - public CmdPoints cmdPoints = new CmdPoints(); - public CmdLogout cmdLogout = new CmdLogout(); - public CmdShop cmdShop = new CmdShop(); - public CmdMissions cmdMissions = new CmdMissions(); - public CmdStrikes cmdStrikes = new CmdStrikes(); - public CmdCheck cmdCheck = new CmdCheck(); - public CmdWeeWoo cmdWeeWoo = new CmdWeeWoo(); - public CmdConvertConfig cmdConvertConfig = new CmdConvertConfig(); + 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 CmdGrace cmdGrace = new CmdGrace(); + 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 CmdAlts cmdAlts = new CmdAlts(); + public CmdCorner cmdCorner = new CmdCorner(); + public CmdInventorySee cmdInventorySee = new CmdInventorySee(); + public CmdFGlobal cmdFGlobal = new CmdFGlobal(); + public CmdViewChest cmdViewChest = new CmdViewChest(); + public CmdPoints cmdPoints = new CmdPoints(); + public CmdLogout cmdLogout = new CmdLogout(); + public CmdShop cmdShop = new CmdShop(); + public CmdMissions cmdMissions = new CmdMissions(); + public CmdStrikes cmdStrikes = new CmdStrikes(); + public CmdCheck cmdCheck = new CmdCheck(); + public CmdWeeWoo cmdWeeWoo = new CmdWeeWoo(); + public CmdConvertConfig cmdConvertConfig = new CmdConvertConfig(); - public FCmdRoot() { - super(); + public FCmdRoot() { + super(); - if (CommodoreProvider.isSupported()) brigadierManager = new BrigadierManager(); + if (CommodoreProvider.isSupported()) brigadierManager = new BrigadierManager(); - this.aliases.addAll(Conf.baseCommandAliases); - this.aliases.removeAll(Collections.singletonList(null)); + this.aliases.addAll(Conf.baseCommandAliases); + this.aliases.removeAll(Collections.singletonList(null)); - this.setHelpShort("The faction base command"); - this.helpLong.add(FactionsPlugin.getInstance().txt.parseTags("This command contains all faction stuff.")); + this.setHelpShort("The faction base command"); + this.helpLong.add(FactionsPlugin.getInstance().txt.parseTags("This command contains all faction stuff.")); - if (CommodoreProvider.isSupported()) brigadierManager = new BrigadierManager(); + if (CommodoreProvider.isSupported()) brigadierManager = new BrigadierManager(); - 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.cmdLogout); - 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.cmdCorner); - this.addSubCommand(this.cmdStrikes); - this.addSubCommand(this.cmdFGlobal); - this.addSubCommand(this.cmdViewChest); - this.addSubCommand(this.cmdConvertConfig); + 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.cmdLogout); + 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.cmdCorner); + this.addSubCommand(this.cmdStrikes); + this.addSubCommand(this.cmdFGlobal); + this.addSubCommand(this.cmdViewChest); + this.addSubCommand(this.cmdConvertConfig); - if (Conf.useCheckSystem) { - this.addSubCommand(this.cmdCheck); - this.addSubCommand(this.cmdWeeWoo); - } + if (Conf.useCheckSystem) { + this.addSubCommand(this.cmdCheck); + this.addSubCommand(this.cmdWeeWoo); + } - if (FactionsPlugin.getInstance().getConfig().getBoolean("Missions-Enabled")) { - this.addSubCommand(this.cmdMissions); - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("Missions-Enabled")) { + this.addSubCommand(this.cmdMissions); + } - if (FactionsPlugin.getInstance().getConfig().getBoolean("F-Shop.Enabled")) { - this.addSubCommand(this.cmdShop); - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("F-Shop.Enabled")) { + this.addSubCommand(this.cmdShop); + } - if (FactionsPlugin.getInstance().getConfig().getBoolean("f-inventory-see.Enabled")) { - this.addSubCommand(this.cmdInventorySee); - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("f-inventory-see.Enabled")) { + this.addSubCommand(this.cmdInventorySee); + } - if (FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled")) { - this.addSubCommand(this.cmdPoints); - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled")) { + this.addSubCommand(this.cmdPoints); + } - if (FactionsPlugin.getInstance().getConfig().getBoolean("f-alts.Enabled")) { - this.addSubCommand(this.cmdAlts); - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("f-alts.Enabled")) { + this.addSubCommand(this.cmdAlts); + } - if (FactionsPlugin.getInstance().getConfig().getBoolean("f-grace.Enabled")) { - this.addSubCommand(this.cmdGrace); - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("f-grace.Enabled")) { + this.addSubCommand(this.cmdGrace); + } - if (Bukkit.getServer().getPluginManager().getPlugin("CoreProtect") != null) { - FactionsPlugin.getInstance().log("Found CoreProtect, enabling Inspect"); - this.addSubCommand(this.cmdInspect); - } else { - FactionsPlugin.getInstance().log("CoreProtect not found, disabling Inspect"); - } - if (FactionsPlugin.getInstance().getConfig().getBoolean("ffocus.Enabled")) { - addSubCommand(this.cmdFocus); - } + if (Bukkit.getServer().getPluginManager().getPlugin("CoreProtect") != null) { + FactionsPlugin.getInstance().log("Found CoreProtect, enabling Inspect"); + this.addSubCommand(this.cmdInspect); + } else { + FactionsPlugin.getInstance().log("CoreProtect not found, disabling Inspect"); + } + if (FactionsPlugin.getInstance().getConfig().getBoolean("ffocus.Enabled")) { + addSubCommand(this.cmdFocus); + } - if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight", false)) { - this.addSubCommand(this.cmdFly); - } - if (Bukkit.getServer().getPluginManager().getPlugin("FactionsTop") != null || Bukkit.getServer().getPluginManager().getPlugin("SavageFTOP") != null || Bukkit.getServer().getPluginManager().getPlugin("SaberFTOP") != null) { - FactionsPlugin.getInstance().log(Level.INFO, "Found FactionsTop plugin. Disabling our own /f top command."); - } else { - FactionsPlugin.getInstance().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 (FactionsPlugin.getInstance().getConfig().getBoolean("fpaypal.Enabled")) { - this.addSubCommand(this.cmdPaypalSet); - this.addSubCommand(this.cmdPaypalSee); - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight", false)) { + this.addSubCommand(this.cmdFly); + } + if (Bukkit.getServer().getPluginManager().getPlugin("FactionsTop") != null || Bukkit.getServer().getPluginManager().getPlugin("SavageFTOP") != null || Bukkit.getServer().getPluginManager().getPlugin("SaberFTOP") != null) { + FactionsPlugin.getInstance().log(Level.INFO, "Found FactionsTop plugin. Disabling our own /f top command."); + } else { + FactionsPlugin.getInstance().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 (FactionsPlugin.getInstance().getConfig().getBoolean("fpaypal.Enabled")) { + this.addSubCommand(this.cmdPaypalSet); + this.addSubCommand(this.cmdPaypalSee); + } - if (CommodoreProvider.isSupported()) brigadierManager.build(); - } + if (CommodoreProvider.isSupported()) brigadierManager.build(); + } - @Override - public void perform(CommandContext context) { - context.commandChain.add(this); - this.cmdHelp.execute(context); - } + @Override + public void perform(CommandContext context) { + context.commandChain.add(this); + this.cmdHelp.execute(context); + } - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - this.execute(new CommandContext(sender, new ArrayList<>(Arrays.asList(args)), label)); - return true; - } + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + this.execute(new CommandContext(sender, new ArrayList<>(Arrays.asList(args)), label)); + return true; + } - @Override - public void addSubCommand(FCommand subCommand) { - super.addSubCommand(subCommand); - // People were getting NPE's as somehow CommodoreProvider#isSupported returned true on legacy versions. - if (CommodoreProvider.isSupported()) { - brigadierManager.addSubCommand(subCommand); - } - } + @Override + public void addSubCommand(FCommand subCommand) { + super.addSubCommand(subCommand); + // People were getting NPE's as somehow CommodoreProvider#isSupported returned true on legacy versions. + if (CommodoreProvider.isSupported()) { + brigadierManager.addSubCommand(subCommand); + } + } - @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 f2553930..76ea057c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCommand.java @@ -17,232 +17,232 @@ import java.util.*; public abstract class FCommand { - public SimpleDateFormat sdf = new SimpleDateFormat(TL.DATE_FORMAT.toString()); + public SimpleDateFormat sdf = new SimpleDateFormat(TL.DATE_FORMAT.toString()); - // Command Aliases - public List aliases; + // Command Aliases + public List aliases; - // Information on the args - public List requiredArgs; - public LinkedHashMap optionalArgs; + // Information on the args + public List requiredArgs; + public LinkedHashMap optionalArgs; - // Requirements to execute this command - public CommandRequirements requirements; - /* - Subcommands - */ - public List subCommands; - /* - Help - */ - public List helpLong; - public CommandVisibility visibility; - private String helpShort; + // Requirements to execute this command + public CommandRequirements requirements; + /* + Subcommands + */ + public List subCommands; + /* + Help + */ + public List helpLong; + public CommandVisibility visibility; + private String helpShort; - public FCommand() { + public FCommand() { - requirements = new CommandRequirements.Builder(null).build(); + requirements = new CommandRequirements.Builder(null).build(); - this.subCommands = new ArrayList<>(); - this.aliases = new ArrayList<>(); + this.subCommands = new ArrayList<>(); + this.aliases = new ArrayList<>(); - this.requiredArgs = new ArrayList<>(); - this.optionalArgs = new LinkedHashMap<>(); + this.requiredArgs = new ArrayList<>(); + this.optionalArgs = new LinkedHashMap<>(); - this.helpShort = null; - this.helpLong = new ArrayList<>(); - this.visibility = CommandVisibility.VISIBLE; - } + this.helpShort = null; + this.helpLong = new ArrayList<>(); + this.visibility = CommandVisibility.VISIBLE; + } - public abstract void perform(CommandContext context); + public abstract void perform(CommandContext context); - public void execute(CommandContext context) { - // Is there a matching sub command? - if (context.args.size() > 0) { - for (FCommand subCommand : this.subCommands) { - if (subCommand.aliases.contains(context.args.get(0).toLowerCase())) { - context.args.remove(0); - context.commandChain.add(this); - subCommand.execute(context); - return; - } - } - } + public void execute(CommandContext context) { + // Is there a matching sub command? + if (context.args.size() > 0) { + for (FCommand subCommand : this.subCommands) { + if (subCommand.aliases.contains(context.args.get(0).toLowerCase())) { + context.args.remove(0); + context.commandChain.add(this); + subCommand.execute(context); + return; + } + } + } - if (!validCall(context)) { - return; - } + if (!validCall(context)) { + return; + } - if (!this.isEnabled(context)) { - return; - } + if (!this.isEnabled(context)) { + return; + } - perform(context); - } + perform(context); + } - public boolean validCall(CommandContext context) { - return requirements.computeRequirements(context, true) && validArgs(context); - } + public boolean validCall(CommandContext context) { + return requirements.computeRequirements(context, true) && validArgs(context); + } - public boolean isEnabled(CommandContext context) { - if (FactionsPlugin.getInstance().getLocked() && requirements.disableOnLock) { - context.msg("Factions was locked by an admin. Please try again later."); - return false; - } - return true; - } + public boolean isEnabled(CommandContext context) { + if (FactionsPlugin.getInstance().getLocked() && requirements.disableOnLock) { + context.msg("Factions was locked by an admin. Please try again later."); + return false; + } + return true; + } - public boolean validArgs(CommandContext context) { - if (context.args.size() < this.requiredArgs.size()) { - if (context.sender != null) { - context.msg(TL.GENERIC_ARGS_TOOFEW); - context.sender.sendMessage(this.getUseageTemplate(context)); - } - return false; - } + public boolean validArgs(CommandContext context) { + if (context.args.size() < this.requiredArgs.size()) { + if (context.sender != null) { + context.msg(TL.GENERIC_ARGS_TOOFEW); + context.sender.sendMessage(this.getUseageTemplate(context)); + } + return false; + } - if (context.args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.requirements.errorOnManyArgs) { - if (context.sender != null) { - // Get the to many string slice - List theToMany = context.args.subList(this.requiredArgs.size() + this.optionalArgs.size(), context.args.size()); - context.msg(TL.GENERIC_ARGS_TOOMANY, TextUtil.implode(theToMany, " ")); - context.sender.sendMessage(this.getUseageTemplate(context)); - } - return false; - } - return true; - } + if (context.args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.requirements.errorOnManyArgs) { + if (context.sender != null) { + // Get the to many string slice + List theToMany = context.args.subList(this.requiredArgs.size() + this.optionalArgs.size(), context.args.size()); + context.msg(TL.GENERIC_ARGS_TOOMANY, TextUtil.implode(theToMany, " ")); + context.sender.sendMessage(this.getUseageTemplate(context)); + } + return false; + } + return true; + } - public void addSubCommand(FCommand subCommand) { - this.subCommands.add(subCommand); - } + public void addSubCommand(FCommand subCommand) { + this.subCommands.add(subCommand); + } - public String getHelpShort() { - if (this.helpShort == null) { - return getUsageTranslation().toString(); - } + public String getHelpShort() { + if (this.helpShort == null) { + return getUsageTranslation().toString(); + } - return this.helpShort; - } + return this.helpShort; + } - public void setHelpShort(String val) { - this.helpShort = val; - } + public void setHelpShort(String val) { + this.helpShort = val; + } - public abstract TL getUsageTranslation(); + public abstract TL getUsageTranslation(); - /* - Common Logic - */ - public List getToolTips(FPlayer player) { - List lines = new ArrayList<>(); - for (String s : FactionsPlugin.getInstance().getConfig().getStringList("tooltips.show")) { - lines.add(ChatColor.translateAlternateColorCodes('&', replaceFPlayerTags(s, player))); - } - return lines; - } + /* + Common Logic + */ + public List getToolTips(FPlayer player) { + List lines = new ArrayList<>(); + for (String s : FactionsPlugin.getInstance().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 : FactionsPlugin.getInstance().getConfig().getStringList("tooltips.list")) { - lines.add(ChatColor.translateAlternateColorCodes('&', replaceFactionTags(s, faction))); - } - return lines; - } + public List getToolTips(Faction faction) { + List lines = new ArrayList<>(); + for (String s : FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(player.getId()))); - s = s.replace("{group}", group); - } - return s; - } + 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 = FactionsPlugin.getInstance().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())); + 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; - } + } + if (s.contains("{online}")) { + s = s.replace("{online}", String.valueOf(faction.getOnlinePlayers().size())); + } + return s; + } - /* - Help and Usage information - */ - public String getUseageTemplate(CommandContext context, boolean addShortHelp) { - StringBuilder ret = new StringBuilder(); - ret.append(FactionsPlugin.getInstance().color(TL.COMMAND_USEAGE_TEMPLATE_COLOR.toString())); - ret.append('/'); + /* + Help and Usage information + */ + public String getUseageTemplate(CommandContext context, boolean addShortHelp) { + StringBuilder ret = new StringBuilder(); + ret.append(FactionsPlugin.getInstance().color(TL.COMMAND_USEAGE_TEMPLATE_COLOR.toString())); + ret.append('/'); - for (FCommand fc : context.commandChain) { - ret.append(TextUtil.implode(fc.aliases, ",")); - ret.append(' '); - } + for (FCommand fc : context.commandChain) { + ret.append(TextUtil.implode(fc.aliases, ",")); + ret.append(' '); + } - ret.append(TextUtil.implode(this.aliases, ",")); + ret.append(TextUtil.implode(this.aliases, ",")); - List args = new ArrayList<>(); + List args = new ArrayList<>(); - for (String requiredArg : this.requiredArgs) { - args.add("<" + requiredArg + ">"); - } + for (String requiredArg : this.requiredArgs) { + args.add("<" + requiredArg + ">"); + } - for (Map.Entry optionalArg : this.optionalArgs.entrySet()) { - String val = optionalArg.getValue(); - if (val == null) { - val = ""; - } else { - val = "=" + val; - } - args.add("[" + optionalArg.getKey() + val + "]"); - } + for (Map.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(FactionsPlugin.getInstance().txt.parseTags(" ")); - ret.append(TextUtil.implode(args, " ")); - } + if (args.size() > 0) { + ret.append(FactionsPlugin.getInstance().txt.parseTags(" ")); + ret.append(TextUtil.implode(args, " ")); + } - if (addShortHelp) { - ret.append(FactionsPlugin.getInstance().txt.parseTags(" ")); - ret.append(this.getHelpShort()); - } + if (addShortHelp) { + ret.append(FactionsPlugin.getInstance().txt.parseTags(" ")); + ret.append(this.getHelpShort()); + } - return ret.toString(); - } + return ret.toString(); + } - public String getUseageTemplate(CommandContext context) { - return getUseageTemplate(context, false); - } + public String getUseageTemplate(CommandContext context) { + return getUseageTemplate(context, false); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/alts/CmdAlts.java b/src/main/java/com/massivecraft/factions/cmd/alts/CmdAlts.java index 1a2232b2..89b3862b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/alts/CmdAlts.java +++ b/src/main/java/com/massivecraft/factions/cmd/alts/CmdAlts.java @@ -10,39 +10,39 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdAlts extends FCommand { - public CmdInviteAlt cmdInviteAlt = new CmdInviteAlt(); - public CmdAltsList cmdAltsList = new CmdAltsList(); + public CmdInviteAlt cmdInviteAlt = new CmdInviteAlt(); + public CmdAltsList cmdAltsList = new CmdAltsList(); - public CmdAlts() { - super(); + public CmdAlts() { + super(); - this.aliases.add("alts"); - this.aliases.add("alt"); + this.aliases.add("alts"); + this.aliases.add("alt"); - this.addSubCommand(this.cmdInviteAlt); - this.addSubCommand(this.cmdAltsList); + this.addSubCommand(this.cmdInviteAlt); + this.addSubCommand(this.cmdAltsList); - this.requirements = new CommandRequirements.Builder(Permission.ALTS) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.ALTS) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-alts.Enabled", false)) { - context.msg(TL.GENERIC_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-alts.Enabled", false)) { + context.msg(TL.GENERIC_DISABLED); + return; + } - context.commandChain.add(this); - FactionsPlugin.getInstance().cmdAutoHelp.execute(context); - } + context.commandChain.add(this); + FactionsPlugin.getInstance().cmdAutoHelp.execute(context); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_ALTS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ALTS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltsList.java b/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltsList.java index 57151ebd..d4ddb9b7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltsList.java +++ b/src/main/java/com/massivecraft/factions/cmd/alts/CmdAltsList.java @@ -14,45 +14,45 @@ import java.util.stream.Collectors; public class CmdAltsList extends FCommand { - public CmdAltsList() { - super(); - this.aliases.add("list"); - this.aliases.add("l"); - this.optionalArgs.put("faction", "yours"); + public CmdAltsList() { + super(); + this.aliases.add("list"); + this.aliases.add("l"); + this.optionalArgs.put("faction", "yours"); - this.requirements = new CommandRequirements.Builder(Permission.LIST) - .playerOnly() - .memberOnly() - .build(); + this.requirements = new CommandRequirements.Builder(Permission.LIST) + .playerOnly() + .memberOnly() + .build(); - } + } - @Override - public void perform(CommandContext context) { - Faction faction = context.faction; - if (context.argIsSet(0)) { - faction = context.argAsFaction(0); - } - if (faction == null) - return; + @Override + public void perform(CommandContext context) { + Faction faction = context.faction; + if (context.argIsSet(0)) { + faction = context.argAsFaction(0); + } + if (faction == null) + return; - if (faction != context.faction && !context.fPlayer.isAdminBypassing()) { - return; - } + if (faction != context.faction && !context.fPlayer.isAdminBypassing()) { + return; + } - if (faction.getAltPlayers().size() == 0) { - context.msg(TL.COMMAND_ALTS_LIST_NOALTS, faction.getTag()); - return; - } + if (faction.getAltPlayers().size() == 0) { + context.msg(TL.COMMAND_ALTS_LIST_NOALTS, faction.getTag()); + return; + } - context.msg("There are " + faction.getAltPlayers().size() + " alts in " + faction.getTag() + ":"); - context.msg(Joiner.on(", ").join(faction.getAltPlayers().stream().map(FPlayer::getName).collect(Collectors.toList()))); - } + context.msg("There are " + faction.getAltPlayers().size() + " alts in " + faction.getTag() + ":"); + context.msg(Joiner.on(", ").join(faction.getAltPlayers().stream().map(FPlayer::getName).collect(Collectors.toList()))); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_ALTS_LIST_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ALTS_LIST_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/alts/CmdInviteAlt.java b/src/main/java/com/massivecraft/factions/cmd/alts/CmdInviteAlt.java index 8bd44283..da520789 100644 --- a/src/main/java/com/massivecraft/factions/cmd/alts/CmdInviteAlt.java +++ b/src/main/java/com/massivecraft/factions/cmd/alts/CmdInviteAlt.java @@ -16,76 +16,76 @@ import org.bukkit.ChatColor; public class CmdInviteAlt extends FCommand { - public CmdInviteAlt() { - super(); - this.aliases.add("invite"); - this.requiredArgs.add("player name"); + public CmdInviteAlt() { + super(); + this.aliases.add("invite"); + this.requiredArgs.add("player name"); - this.requirements = new CommandRequirements.Builder(Permission.INVITE) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.INVITE) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-alts.Enabled", false)) { - context.fPlayer.msg(TL.GENERIC_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-alts.Enabled", false)) { + context.fPlayer.msg(TL.GENERIC_DISABLED); + return; + } - FPlayer target = context.argAsBestFPlayerMatch(0); - if (target == null) { - return; - } + FPlayer target = context.argAsBestFPlayerMatch(0); + if (target == null) { + return; + } - if (target.getFaction() == context.faction) { - context.msg(TL.COMMAND_INVITE_ALREADYMEMBER, target.getName(), context.faction.getTag()); - return; - } + if (target.getFaction() == context.faction) { + context.msg(TL.COMMAND_INVITE_ALREADYMEMBER, target.getName(), context.faction.getTag()); + return; + } - // if economy is enabled, they're not on the bypass list, and this - // command has a cost set, make 'em pay - if (!context.payForCommand(Conf.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 (!context.payForCommand(Conf.econCostInvite, TL.COMMAND_INVITE_TOINVITE.toString(), TL.COMMAND_INVITE_FORINVITE.toString())) { + return; + } - if (!context.fPlayer.isAdminBypassing()) { - Access access = context.faction.getAccess(context.fPlayer, PermissableAction.INVITE); - if (access != Access.ALLOW && context.fPlayer.getRole() != Role.LEADER) { - context.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage invites"); - return; - } - } + if (!context.fPlayer.isAdminBypassing()) { + Access access = context.faction.getAccess(context.fPlayer, PermissableAction.INVITE); + if (access != Access.ALLOW && context.fPlayer.getRole() != Role.LEADER) { + context.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage invites"); + return; + } + } - if (context.faction.isBanned(target)) { - context.msg(TL.COMMAND_INVITE_BANNED, target.getName()); - return; - } + if (context.faction.isBanned(target)) { + context.msg(TL.COMMAND_INVITE_BANNED, target.getName()); + return; + } - context.faction.deinvite(target); - context.faction.altInvite(target); - if (!target.isOnline()) { - return; - } + context.faction.deinvite(target); + context.faction.altInvite(target); + if (!target.isOnline()) { + return; + } - FancyMessage message = new FancyMessage(context.fPlayer.describeTo(target, true)) - .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()) - .then(TL.COMMAND_INVITE_INVITEDYOU.toString()) - .color(ChatColor.YELLOW) - .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()) - .then(context.faction.describeTo(target)).tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()); + FancyMessage message = new FancyMessage(context.fPlayer.describeTo(target, true)) + .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()) + .then(TL.COMMAND_INVITE_INVITEDYOU.toString()) + .color(ChatColor.YELLOW) + .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()) + .then(context.faction.describeTo(target)).tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + context.faction.getTag()); - message.send(target.getPlayer()); + message.send(target.getPlayer()); - context.faction.msg(TL.COMMAND_ALTINVITE_INVITED_ALT, context.fPlayer.describeTo(context.faction, true), target.describeTo(context.faction)); - } + context.faction.msg(TL.COMMAND_ALTINVITE_INVITED_ALT, context.fPlayer.describeTo(context.faction, true), target.describeTo(context.faction)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_ALTINVITE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ALTINVITE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/check/CheckHistoryFrame.java b/src/main/java/com/massivecraft/factions/cmd/check/CheckHistoryFrame.java index 5a883892..17e19377 100644 --- a/src/main/java/com/massivecraft/factions/cmd/check/CheckHistoryFrame.java +++ b/src/main/java/com/massivecraft/factions/cmd/check/CheckHistoryFrame.java @@ -18,72 +18,72 @@ import java.text.SimpleDateFormat; import java.util.*; public class CheckHistoryFrame implements FactionGUI { - private FactionsPlugin plugin; - private Faction faction; - private Inventory inventory; - private SimpleDateFormat simpleDateFormat; + private FactionsPlugin plugin; + private Faction faction; + private Inventory inventory; + private SimpleDateFormat simpleDateFormat; - public CheckHistoryFrame(FactionsPlugin plugin, Faction faction) { - this.simpleDateFormat = new SimpleDateFormat(Conf.dateFormat); - this.plugin = plugin; - this.faction = faction; - this.inventory = plugin.getServer().createInventory(this, 54, TL.CHECK_HISTORY_GUI_TITLE.toString()); - } + public CheckHistoryFrame(FactionsPlugin plugin, Faction faction) { + this.simpleDateFormat = new SimpleDateFormat(Conf.dateFormat); + this.plugin = plugin; + this.faction = faction; + this.inventory = plugin.getServer().createInventory(this, 54, TL.CHECK_HISTORY_GUI_TITLE.toString()); + } - public void onClick(int slot, ClickType action) { - } + public void onClick(int slot, ClickType action) { + } - public void build() { - int currentSlot = 0; - for (Map.Entry entry : Lists.reverse(new ArrayList<>(faction.getChecks().entrySet()))) { - if (currentSlot >= 54) { - continue; - } + public void build() { + int currentSlot = 0; + for (Map.Entry entry : Lists.reverse(new ArrayList<>(faction.getChecks().entrySet()))) { + if (currentSlot >= 54) { + continue; + } - ItemStack itemStack = new ItemStack(XMaterial.MAGENTA_STAINED_GLASS_PANE.parseItem()); - if (entry.getValue().startsWith("U")) { - itemStack.setDurability((short) 2); - MaterialData data = itemStack.getData(); - data.setData(DyeColor.MAGENTA.getWoolData()); - itemStack.setData(data); - ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setDisplayName(TL.CHECK_WALLS_CHECKED_GUI_ICON.toString()); - itemMeta.setLore(Arrays.asList(TL.CHECK_TIME_LORE_LINE.format(simpleDateFormat.format(new Date(entry.getKey()))), TL.CHECK_PLAYER_LORE_LINE.format(entry.getValue().substring(1)))); - itemStack.setItemMeta(itemMeta); - } else if (entry.getValue().startsWith("Y")) { - itemStack.setDurability((short) 2); - MaterialData data = itemStack.getData(); - data.setData(DyeColor.MAGENTA.getWoolData()); - itemStack.setData(data); - ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setDisplayName(TL.CHECK_BUFFERS_CHECKED_GUI_ICON.toString()); - itemMeta.setLore(Arrays.asList(TL.CHECK_TIME_LORE_LINE.format(simpleDateFormat.format(new Date(entry.getKey()))), TL.CHECK_PLAYER_LORE_LINE.format(entry.getValue().substring(1)))); - itemStack.setItemMeta(itemMeta); - } else if (entry.getValue().startsWith("J")) { - itemStack.setDurability((short) 0); - MaterialData data = itemStack.getData(); - data.setData(DyeColor.WHITE.getWoolData()); - itemStack.setData(data); - ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setDisplayName(TL.CHECK_WALLS_UNCHECKED_GUI_ICON.toString()); - itemMeta.setLore(Collections.singletonList(TL.CHECK_TIME_LORE_LINE.format(simpleDateFormat.format(new Date(entry.getKey()))))); - itemStack.setItemMeta(itemMeta); - } else if (entry.getValue().startsWith("H")) { - itemStack.setDurability((short) 0); - MaterialData data = itemStack.getData(); - data.setData(DyeColor.WHITE.getWoolData()); - itemStack.setData(data); - ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setDisplayName(TL.CHECK_BUFFERS_UNCHECKED_GUI_ICON.toString()); - itemMeta.setLore(Collections.singletonList(TL.CHECK_TIME_LORE_LINE.format(simpleDateFormat.format(new Date(entry.getKey()))))); - itemStack.setItemMeta(itemMeta); - } - inventory.setItem(currentSlot, itemStack); - ++currentSlot; - } - } + ItemStack itemStack = new ItemStack(XMaterial.MAGENTA_STAINED_GLASS_PANE.parseItem()); + if (entry.getValue().startsWith("U")) { + itemStack.setDurability((short) 2); + MaterialData data = itemStack.getData(); + data.setData(DyeColor.MAGENTA.getWoolData()); + itemStack.setData(data); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(TL.CHECK_WALLS_CHECKED_GUI_ICON.toString()); + itemMeta.setLore(Arrays.asList(TL.CHECK_TIME_LORE_LINE.format(simpleDateFormat.format(new Date(entry.getKey()))), TL.CHECK_PLAYER_LORE_LINE.format(entry.getValue().substring(1)))); + itemStack.setItemMeta(itemMeta); + } else if (entry.getValue().startsWith("Y")) { + itemStack.setDurability((short) 2); + MaterialData data = itemStack.getData(); + data.setData(DyeColor.MAGENTA.getWoolData()); + itemStack.setData(data); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(TL.CHECK_BUFFERS_CHECKED_GUI_ICON.toString()); + itemMeta.setLore(Arrays.asList(TL.CHECK_TIME_LORE_LINE.format(simpleDateFormat.format(new Date(entry.getKey()))), TL.CHECK_PLAYER_LORE_LINE.format(entry.getValue().substring(1)))); + itemStack.setItemMeta(itemMeta); + } else if (entry.getValue().startsWith("J")) { + itemStack.setDurability((short) 0); + MaterialData data = itemStack.getData(); + data.setData(DyeColor.WHITE.getWoolData()); + itemStack.setData(data); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(TL.CHECK_WALLS_UNCHECKED_GUI_ICON.toString()); + itemMeta.setLore(Collections.singletonList(TL.CHECK_TIME_LORE_LINE.format(simpleDateFormat.format(new Date(entry.getKey()))))); + itemStack.setItemMeta(itemMeta); + } else if (entry.getValue().startsWith("H")) { + itemStack.setDurability((short) 0); + MaterialData data = itemStack.getData(); + data.setData(DyeColor.WHITE.getWoolData()); + itemStack.setData(data); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(TL.CHECK_BUFFERS_UNCHECKED_GUI_ICON.toString()); + itemMeta.setLore(Collections.singletonList(TL.CHECK_TIME_LORE_LINE.format(simpleDateFormat.format(new Date(entry.getKey()))))); + itemStack.setItemMeta(itemMeta); + } + inventory.setItem(currentSlot, itemStack); + ++currentSlot; + } + } - public Inventory getInventory() { - return inventory; - } + public Inventory getInventory() { + return inventory; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/check/CheckSettingsFrame.java b/src/main/java/com/massivecraft/factions/cmd/check/CheckSettingsFrame.java index 858d9244..02c2bc05 100644 --- a/src/main/java/com/massivecraft/factions/cmd/check/CheckSettingsFrame.java +++ b/src/main/java/com/massivecraft/factions/cmd/check/CheckSettingsFrame.java @@ -16,95 +16,95 @@ import org.bukkit.inventory.meta.ItemMeta; import java.util.Collections; public class CheckSettingsFrame implements InventoryHolder, FactionGUI { - private FactionsPlugin plugin; - private FPlayer fPlayer; - private Inventory inventory; + private FactionsPlugin plugin; + private FPlayer fPlayer; + private Inventory inventory; - public CheckSettingsFrame(FactionsPlugin plugin, FPlayer fPlayer) { - this.plugin = plugin; - this.fPlayer = fPlayer; - this.inventory = plugin.getServer().createInventory(this, plugin.getConfig().getInt("f-check.gui-rows") * 9, TL.CHECK_SETTINGS_GUI_TITLE.toString()); - } + public CheckSettingsFrame(FactionsPlugin plugin, FPlayer fPlayer) { + this.plugin = plugin; + this.fPlayer = fPlayer; + this.inventory = plugin.getServer().createInventory(this, plugin.getConfig().getInt("f-check.gui-rows") * 9, TL.CHECK_SETTINGS_GUI_TITLE.toString()); + } - public void onClick(int slot, ClickType action) { - Faction faction = this.fPlayer.getFaction(); - if (slot == FactionsPlugin.getInstance().getConfig().getInt("f-check.wall-check.slot")) { - faction.setWallCheckMinutes(getNext(faction.getWallCheckMinutes())); - } else { - if (slot == FactionsPlugin.getInstance().getConfig().getInt("f-check.history.slot")) { - CheckHistoryFrame checkHistoryFrame = new CheckHistoryFrame(plugin, fPlayer.getFaction()); - checkHistoryFrame.build(); - fPlayer.getPlayer().openInventory(checkHistoryFrame.getInventory()); - return; - } - if (slot == FactionsPlugin.getInstance().getConfig().getInt("f-check.buffer-check.slot")) { - faction.setBufferCheckMinutes(getNext(faction.getBufferCheckMinutes())); - } - } - build(); - fPlayer.getPlayer().openInventory(inventory); - } + public void onClick(int slot, ClickType action) { + Faction faction = this.fPlayer.getFaction(); + if (slot == FactionsPlugin.getInstance().getConfig().getInt("f-check.wall-check.slot")) { + faction.setWallCheckMinutes(getNext(faction.getWallCheckMinutes())); + } else { + if (slot == FactionsPlugin.getInstance().getConfig().getInt("f-check.history.slot")) { + CheckHistoryFrame checkHistoryFrame = new CheckHistoryFrame(plugin, fPlayer.getFaction()); + checkHistoryFrame.build(); + fPlayer.getPlayer().openInventory(checkHistoryFrame.getInventory()); + return; + } + if (slot == FactionsPlugin.getInstance().getConfig().getInt("f-check.buffer-check.slot")) { + faction.setBufferCheckMinutes(getNext(faction.getBufferCheckMinutes())); + } + } + build(); + fPlayer.getPlayer().openInventory(inventory); + } - public void build() { - Faction faction = fPlayer.getFaction(); - ItemStack wallsStack = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("f-check.wall-check.Type")).parseItem(); - ItemMeta wallsMeta = wallsStack.getItemMeta(); - wallsMeta.setDisplayName(TL.CHECK_WALL_CHECK_GUI_ICON.toString()); - wallsMeta.setLore(Collections.singletonList(TL.CHECK_CHECK_LORE_LINE.format(getFormatted(faction.getWallCheckMinutes())))); - wallsStack.setItemMeta(wallsMeta); - inventory.setItem(FactionsPlugin.getInstance().getConfig().getInt("f-check.wall-check.slot"), wallsStack); - ItemStack bufferStack = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("f-check.buffer-check.Type")).parseItem(); - ItemMeta bufferMeta = bufferStack.getItemMeta(); - bufferMeta.setDisplayName(TL.CHECK_BUFFER_CHECK_GUI_ICON.toString()); - bufferMeta.setLore(Collections.singletonList(TL.CHECK_CHECK_LORE_LINE.format(getFormatted(faction.getBufferCheckMinutes())))); - bufferStack.setItemMeta(bufferMeta); - inventory.setItem(FactionsPlugin.getInstance().getConfig().getInt("f-check.buffer-check.slot"), bufferStack); - ItemStack historyStack = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("f-check.history.Type")).parseItem(); - ItemMeta historyMeta = historyStack.getItemMeta(); - historyMeta.setDisplayName(TL.CHECK_HISTORY_GUI_ICON.toString()); - historyStack.setItemMeta(historyMeta); - inventory.setItem(FactionsPlugin.getInstance().getConfig().getInt("f-check.history.slot"), historyStack); - } + public void build() { + Faction faction = fPlayer.getFaction(); + ItemStack wallsStack = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("f-check.wall-check.Type")).parseItem(); + ItemMeta wallsMeta = wallsStack.getItemMeta(); + wallsMeta.setDisplayName(TL.CHECK_WALL_CHECK_GUI_ICON.toString()); + wallsMeta.setLore(Collections.singletonList(TL.CHECK_CHECK_LORE_LINE.format(getFormatted(faction.getWallCheckMinutes())))); + wallsStack.setItemMeta(wallsMeta); + inventory.setItem(FactionsPlugin.getInstance().getConfig().getInt("f-check.wall-check.slot"), wallsStack); + ItemStack bufferStack = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("f-check.buffer-check.Type")).parseItem(); + ItemMeta bufferMeta = bufferStack.getItemMeta(); + bufferMeta.setDisplayName(TL.CHECK_BUFFER_CHECK_GUI_ICON.toString()); + bufferMeta.setLore(Collections.singletonList(TL.CHECK_CHECK_LORE_LINE.format(getFormatted(faction.getBufferCheckMinutes())))); + bufferStack.setItemMeta(bufferMeta); + inventory.setItem(FactionsPlugin.getInstance().getConfig().getInt("f-check.buffer-check.slot"), bufferStack); + ItemStack historyStack = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("f-check.history.Type")).parseItem(); + ItemMeta historyMeta = historyStack.getItemMeta(); + historyMeta.setDisplayName(TL.CHECK_HISTORY_GUI_ICON.toString()); + historyStack.setItemMeta(historyMeta); + inventory.setItem(FactionsPlugin.getInstance().getConfig().getInt("f-check.history.slot"), historyStack); + } - public Inventory getInventory() { - return this.inventory; - } + public Inventory getInventory() { + return this.inventory; + } - private int getNext(int current) { - switch (current) { - case 0: { - return 3; - } - case 3: { - return 5; - } - case 5: { - return 10; - } - case 10: { - return 15; - } - case 15: { - return 30; - } - case 30: { - return 0; - } - default: { - return 0; - } - } - } + private int getNext(int current) { + switch (current) { + case 0: { + return 3; + } + case 3: { + return 5; + } + case 5: { + return 10; + } + case 10: { + return 15; + } + case 15: { + return 30; + } + case 30: { + return 0; + } + default: { + return 0; + } + } + } - private String getFormatted(int minutes) { - if (minutes == 0) { - return "Offline"; - } - return minutes + " Minutes"; - } + private String getFormatted(int minutes) { + if (minutes == 0) { + return "Offline"; + } + return minutes + " Minutes"; + } - public String color(String message) { - return ChatColor.translateAlternateColorCodes('&', message); - } + public String color(String message) { + return ChatColor.translateAlternateColorCodes('&', message); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/check/CheckTask.java b/src/main/java/com/massivecraft/factions/cmd/check/CheckTask.java index 7d5a895c..8564f7dc 100644 --- a/src/main/java/com/massivecraft/factions/cmd/check/CheckTask.java +++ b/src/main/java/com/massivecraft/factions/cmd/check/CheckTask.java @@ -13,86 +13,86 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class CheckTask implements Runnable { - private static List wallChecks = new CopyOnWriteArrayList<>(); - private static List bufferChecks = new CopyOnWriteArrayList<>(); - private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Conf.dateFormat); - private FactionsPlugin plugin; - private int minute; + private static List wallChecks = new CopyOnWriteArrayList<>(); + private static List bufferChecks = new CopyOnWriteArrayList<>(); + private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Conf.dateFormat); + private FactionsPlugin plugin; + private int minute; - public CheckTask(FactionsPlugin plugin, int minute) { - this.plugin = plugin; - this.minute = minute; - } + public CheckTask(FactionsPlugin plugin, int minute) { + this.plugin = plugin; + this.minute = minute; + } - public static void cleanupTask() { - for (Faction faction : Factions.getInstance().getAllFactions()) { - if (!faction.isNormal()) { - continue; - } - List remove = new ArrayList<>(); - int i = 0; - if (faction.getChecks() == null) return; - for (Long key : Lists.reverse(new ArrayList<>(faction.getChecks().keySet()))) { - if (key == null) return; - if (i >= 54) { - remove.add(key); - } - ++i; - } - remove.forEach(r -> faction.getChecks().remove(r)); - } - } - - public static boolean wallCheck(String factionId) { - return CheckTask.wallChecks.remove(factionId); - } - - public static boolean bufferCheck(String factionId) { - return CheckTask.bufferChecks.remove(factionId); - } - - @Override - public void run() { - long currentTime = System.currentTimeMillis(); - for (Faction faction : Factions.getInstance().getAllFactions()) { - if (!faction.isNormal()) { - continue; - } - if (faction.getWallCheckMinutes() != minute) { - continue; - } - long CurrentTime = currentTime; - if (CheckTask.wallChecks.contains(faction.getId())) { - plugin.getServer().getScheduler().runTask(plugin, () -> faction.getChecks().put(CurrentTime, "J")); - } else { - CheckTask.wallChecks.add(faction.getId()); - } - faction.msg(TL.CHECK_WALLS_CHECK); - } - - - ++currentTime; - for (Faction faction : Factions.getInstance().getAllFactions()) { - if (!faction.isNormal()) { - continue; - } - if (faction.getBufferCheckMinutes() != minute) { - continue; - } - if (CheckTask.bufferChecks.contains(faction.getId())) { - Faction faction2 = null; - long CurrentTime2 = 0; - plugin.getServer().getScheduler().runTask(plugin, () -> { - if (faction2 != null) { - faction2.getChecks().put(CurrentTime2, "H"); + public static void cleanupTask() { + for (Faction faction : Factions.getInstance().getAllFactions()) { + if (!faction.isNormal()) { + continue; + } + List remove = new ArrayList<>(); + int i = 0; + if (faction.getChecks() == null) return; + for (Long key : Lists.reverse(new ArrayList<>(faction.getChecks().keySet()))) { + if (key == null) return; + if (i >= 54) { + remove.add(key); } - }); - } else { - CheckTask.bufferChecks.add(faction.getId()); - } - faction.msg(TL.CHECK_BUFFERS_CHECK); - } - } + ++i; + } + remove.forEach(r -> faction.getChecks().remove(r)); + } + } + + public static boolean wallCheck(String factionId) { + return CheckTask.wallChecks.remove(factionId); + } + + public static boolean bufferCheck(String factionId) { + return CheckTask.bufferChecks.remove(factionId); + } + + @Override + public void run() { + long currentTime = System.currentTimeMillis(); + for (Faction faction : Factions.getInstance().getAllFactions()) { + if (!faction.isNormal()) { + continue; + } + if (faction.getWallCheckMinutes() != minute) { + continue; + } + long CurrentTime = currentTime; + if (CheckTask.wallChecks.contains(faction.getId())) { + plugin.getServer().getScheduler().runTask(plugin, () -> faction.getChecks().put(CurrentTime, "J")); + } else { + CheckTask.wallChecks.add(faction.getId()); + } + faction.msg(TL.CHECK_WALLS_CHECK); + } + + + ++currentTime; + for (Faction faction : Factions.getInstance().getAllFactions()) { + if (!faction.isNormal()) { + continue; + } + if (faction.getBufferCheckMinutes() != minute) { + continue; + } + if (CheckTask.bufferChecks.contains(faction.getId())) { + Faction faction2 = null; + long CurrentTime2 = 0; + plugin.getServer().getScheduler().runTask(plugin, () -> { + if (faction2 != null) { + faction2.getChecks().put(CurrentTime2, "H"); + } + }); + } else { + CheckTask.bufferChecks.add(faction.getId()); + } + faction.msg(TL.CHECK_BUFFERS_CHECK); + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/check/CmdCheck.java b/src/main/java/com/massivecraft/factions/cmd/check/CmdCheck.java index 36e7bd8a..d7e73a92 100644 --- a/src/main/java/com/massivecraft/factions/cmd/check/CmdCheck.java +++ b/src/main/java/com/massivecraft/factions/cmd/check/CmdCheck.java @@ -16,96 +16,96 @@ import java.util.*; import java.util.stream.Collectors; public class CmdCheck extends FCommand { - private SimpleDateFormat simpleDateFormat; + private SimpleDateFormat simpleDateFormat; - public CmdCheck() { - this.simpleDateFormat = new SimpleDateFormat(Conf.dateFormat); - this.aliases.add("check"); - this.requiredArgs.add("walls/buffers/settings/leaderboard"); + public CmdCheck() { + this.simpleDateFormat = new SimpleDateFormat(Conf.dateFormat); + this.aliases.add("check"); + this.requiredArgs.add("walls/buffers/settings/leaderboard"); - this.requirements = new CommandRequirements.Builder(Permission.CHECK) - .playerOnly() - .withAction(PermissableAction.CHECK) - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CHECK) + .playerOnly() + .withAction(PermissableAction.CHECK) + .memberOnly() + .build(); + } - public void perform(CommandContext context) { - if (context.faction == null || !context.faction.isNormal()) { - return; - } - String subCommand = context.argAsString(0, null); + public void perform(CommandContext context) { + if (context.faction == null || !context.faction.isNormal()) { + return; + } + String subCommand = context.argAsString(0, null); - long currentTime = System.currentTimeMillis(); - if (subCommand.equalsIgnoreCase("leaderboard")) { - context.msg(TL.CHECK_LEADERBOARD_HEADER); - Map players = new HashMap<>(); - for (Map.Entry entry : context.faction.getPlayerWallCheckCount().entrySet()) { - players.put(entry.getKey(), entry.getValue()); - } - for (Map.Entry entry : context.faction.getPlayerBufferCheckCount().entrySet()) { - if (players.containsKey(entry.getKey())) { - players.replace(entry.getKey(), players.get(entry.getKey()) + entry.getValue()); - } else { + long currentTime = System.currentTimeMillis(); + if (subCommand.equalsIgnoreCase("leaderboard")) { + context.msg(TL.CHECK_LEADERBOARD_HEADER); + Map players = new HashMap<>(); + for (Map.Entry entry : context.faction.getPlayerWallCheckCount().entrySet()) { players.put(entry.getKey(), entry.getValue()); - } - } - List> entryList = players.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getValue)).collect(Collectors.toList()); - for (int max = (entryList.size() > 10) ? 10 : entryList.size(), current = 0; current < max; ++current) { - Map.Entry entry = entryList.get(current); - OfflinePlayer offlinePlayer = FactionsPlugin.getInstance().getServer().getOfflinePlayer(entry.getKey()); - context.msg(TL.CHECK_LEADERBOARD_LINE.format(current + 1, offlinePlayer.getName(), entry.getValue(), context.faction.getPlayerBufferCheckCount().getOrDefault(entry.getKey(), 0), context.faction.getPlayerWallCheckCount().getOrDefault(entry.getKey(), 0))); - } - if (entryList.isEmpty()) { - context.msg(TL.CHECK_LEADERBOARD_NO_DATA); - } - } else if (subCommand.equalsIgnoreCase("walls")) { - if (!CheckTask.wallCheck(context.faction.getId())) { - if (context.faction.getChecks().isEmpty()) { - context.msg(TL.CHECK_NO_CHECKS); + } + for (Map.Entry entry : context.faction.getPlayerBufferCheckCount().entrySet()) { + if (players.containsKey(entry.getKey())) { + players.replace(entry.getKey(), players.get(entry.getKey()) + entry.getValue()); + } else { + players.put(entry.getKey(), entry.getValue()); + } + } + List> entryList = players.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getValue)).collect(Collectors.toList()); + for (int max = (entryList.size() > 10) ? 10 : entryList.size(), current = 0; current < max; ++current) { + Map.Entry entry = entryList.get(current); + OfflinePlayer offlinePlayer = FactionsPlugin.getInstance().getServer().getOfflinePlayer(entry.getKey()); + context.msg(TL.CHECK_LEADERBOARD_LINE.format(current + 1, offlinePlayer.getName(), entry.getValue(), context.faction.getPlayerBufferCheckCount().getOrDefault(entry.getKey(), 0), context.faction.getPlayerWallCheckCount().getOrDefault(entry.getKey(), 0))); + } + if (entryList.isEmpty()) { + context.msg(TL.CHECK_LEADERBOARD_NO_DATA); + } + } else if (subCommand.equalsIgnoreCase("walls")) { + if (!CheckTask.wallCheck(context.faction.getId())) { + if (context.faction.getChecks().isEmpty()) { + context.msg(TL.CHECK_NO_CHECKS); + return; + } + context.msg(TL.CHECK_ALREADY_CHECKED); + } else { + int current = context.faction.getPlayerWallCheckCount().getOrDefault(context.player.getUniqueId(), 0); + if (current == 0) { + context.faction.getPlayerWallCheckCount().put(context.player.getUniqueId(), 1); + } else { + context.faction.getPlayerWallCheckCount().replace(context.player.getUniqueId(), current + 1); + } + context.faction.getChecks().put(currentTime, "U" + context.fPlayer.getNameAndTag()); + context.msg(TL.CHECK_WALLS_MARKED_CHECKED); + } + } else if (subCommand.equalsIgnoreCase("buffers")) { + if (!CheckTask.bufferCheck(context.faction.getId())) { + if (context.faction.getChecks().isEmpty()) { + context.msg(TL.CHECK_NO_CHECKS); + return; + } + context.msg(TL.CHECK_ALREADY_CHECKED); + } else { + int current = context.faction.getPlayerBufferCheckCount().getOrDefault(context.player.getUniqueId(), 0); + if (current == 0) { + context.faction.getPlayerBufferCheckCount().put(context.player.getUniqueId(), 1); + } else { + context.faction.getPlayerBufferCheckCount().replace(context.player.getUniqueId(), current + 1); + } + context.faction.getChecks().put(System.currentTimeMillis(), "Y" + context.fPlayer.getNameAndTag()); + context.msg(TL.CHECK_BUFFERS_MARKED_CHECKED); + } + } else if (subCommand.equalsIgnoreCase("settings")) { + if (!context.fPlayer.getRole().isAtLeast(Role.COLEADER)) { + context.msg(TL.CHECK_MUST_BE_ATLEAST_COLEADER); return; - } - context.msg(TL.CHECK_ALREADY_CHECKED); - } else { - int current = context.faction.getPlayerWallCheckCount().getOrDefault(context.player.getUniqueId(), 0); - if (current == 0) { - context.faction.getPlayerWallCheckCount().put(context.player.getUniqueId(), 1); - } else { - context.faction.getPlayerWallCheckCount().replace(context.player.getUniqueId(), current + 1); - } - context.faction.getChecks().put(currentTime, "U" + context.fPlayer.getNameAndTag()); - context.msg(TL.CHECK_WALLS_MARKED_CHECKED); - } - } else if (subCommand.equalsIgnoreCase("buffers")) { - if (!CheckTask.bufferCheck(context.faction.getId())) { - if (context.faction.getChecks().isEmpty()) { - context.msg(TL.CHECK_NO_CHECKS); - return; - } - context.msg(TL.CHECK_ALREADY_CHECKED); - } else { - int current = context.faction.getPlayerBufferCheckCount().getOrDefault(context.player.getUniqueId(), 0); - if (current == 0) { - context.faction.getPlayerBufferCheckCount().put(context.player.getUniqueId(), 1); - } else { - context.faction.getPlayerBufferCheckCount().replace(context.player.getUniqueId(), current + 1); - } - context.faction.getChecks().put(System.currentTimeMillis(), "Y" + context.fPlayer.getNameAndTag()); - context.msg(TL.CHECK_BUFFERS_MARKED_CHECKED); - } - } else if (subCommand.equalsIgnoreCase("settings")) { - if (!context.fPlayer.getRole().isAtLeast(Role.COLEADER)) { - context.msg(TL.CHECK_MUST_BE_ATLEAST_COLEADER); - return; - } - CheckSettingsFrame checkGUI = new CheckSettingsFrame(FactionsPlugin.getInstance(), context.fPlayer); - checkGUI.build(); - context.fPlayer.getPlayer().openInventory(checkGUI.getInventory()); - } - } + } + CheckSettingsFrame checkGUI = new CheckSettingsFrame(FactionsPlugin.getInstance(), context.fPlayer); + checkGUI.build(); + context.fPlayer.getPlayer().openInventory(checkGUI.getInventory()); + } + } - public TL getUsageTranslation() { - return TL.COMMAND_CHECK_DESCRIPTION; - } + public TL getUsageTranslation() { + return TL.COMMAND_CHECK_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/check/CmdWeeWoo.java b/src/main/java/com/massivecraft/factions/cmd/check/CmdWeeWoo.java index f52c6c2a..c00dc9ef 100644 --- a/src/main/java/com/massivecraft/factions/cmd/check/CmdWeeWoo.java +++ b/src/main/java/com/massivecraft/factions/cmd/check/CmdWeeWoo.java @@ -7,43 +7,43 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdWeeWoo extends FCommand { - public CmdWeeWoo() { - this.aliases.add("weewoo"); - this.requiredArgs.add("start/stop"); + public CmdWeeWoo() { + this.aliases.add("weewoo"); + this.requiredArgs.add("start/stop"); - this.requirements = new CommandRequirements.Builder(Permission.CHECK) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CHECK) + .playerOnly() + .memberOnly() + .build(); + } - public void perform(CommandContext context) { - if (context.faction == null || !context.faction.isNormal()) { - return; - } - String argument = context.argAsString(0); - boolean weewoo = context.faction.isWeeWoo(); - if (argument.equalsIgnoreCase("start")) { - if (weewoo) { - context.msg(TL.COMMAND_WEEWOO_ALREADY_STARTED); - return; - } - context.faction.setWeeWoo(true); - context.msg(TL.COMMAND_WEEWOO_STARTED, context.fPlayer.getNameAndTag()); + public void perform(CommandContext context) { + if (context.faction == null || !context.faction.isNormal()) { + return; + } + String argument = context.argAsString(0); + boolean weewoo = context.faction.isWeeWoo(); + if (argument.equalsIgnoreCase("start")) { + if (weewoo) { + context.msg(TL.COMMAND_WEEWOO_ALREADY_STARTED); + return; + } + context.faction.setWeeWoo(true); + context.msg(TL.COMMAND_WEEWOO_STARTED, context.fPlayer.getNameAndTag()); - } else if (argument.equalsIgnoreCase("stop")) { - if (!weewoo) { - context.msg(TL.COMMAND_WEEWOO_ALREADY_STOPPED); - return; - } - context.faction.setWeeWoo(false); - context.msg(TL.COMMAND_WEEWOO_STOPPED, context.fPlayer.getNameAndTag()); - } else { - context.msg("/f weewoo "); - } - } + } else if (argument.equalsIgnoreCase("stop")) { + if (!weewoo) { + context.msg(TL.COMMAND_WEEWOO_ALREADY_STOPPED); + return; + } + context.faction.setWeeWoo(false); + context.msg(TL.COMMAND_WEEWOO_STOPPED, context.fPlayer.getNameAndTag()); + } else { + context.msg("/f weewoo "); + } + } - public TL getUsageTranslation() { - return TL.COMMAND_WEEWOO_DESCRIPTION; - } + public TL getUsageTranslation() { + return TL.COMMAND_WEEWOO_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/check/WeeWooTask.java b/src/main/java/com/massivecraft/factions/cmd/check/WeeWooTask.java index ffce2553..7d9ea86a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/check/WeeWooTask.java +++ b/src/main/java/com/massivecraft/factions/cmd/check/WeeWooTask.java @@ -7,19 +7,19 @@ import com.massivecraft.factions.zcore.util.TL; public class WeeWooTask implements Runnable { - private FactionsPlugin plugin; + private FactionsPlugin plugin; - public WeeWooTask(FactionsPlugin plugin) { - this.plugin = plugin; - } + public WeeWooTask(FactionsPlugin plugin) { + this.plugin = plugin; + } - @Override - public void run() { - for (Faction faction : Factions.getInstance().getAllFactions()) { - if (!faction.isWeeWoo()) { - continue; - } - faction.msg(TL.WEE_WOO_MESSAGE); - } - } + @Override + public void run() { + for (Faction faction : Factions.getInstance().getAllFactions()) { + if (!faction.isWeeWoo()) { + continue; + } + faction.msg(TL.WEE_WOO_MESSAGE); + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/chest/ChestLogsHandler.java b/src/main/java/com/massivecraft/factions/cmd/chest/ChestLogsHandler.java index 0a8e1edd..a8b61462 100644 --- a/src/main/java/com/massivecraft/factions/cmd/chest/ChestLogsHandler.java +++ b/src/main/java/com/massivecraft/factions/cmd/chest/ChestLogsHandler.java @@ -17,107 +17,107 @@ import java.util.Map; public class ChestLogsHandler implements Listener { - public static HashMap> removeMap = new HashMap<>(); - public static HashMap> addMap = new HashMap<>(); - public static HashMap totalMap = new HashMap<>(); + public static HashMap> removeMap = new HashMap<>(); + public static HashMap> addMap = new HashMap<>(); + public static HashMap totalMap = new HashMap<>(); - public static int getAll(String uuid) { - int t = 0; - t = t + removeMap.get(uuid).size(); - t = t + addMap.get(uuid).size(); - return t; - } + public static int getAll(String uuid) { + int t = 0; + t = t + removeMap.get(uuid).size(); + t = t + addMap.get(uuid).size(); + return t; + } - public static int getAll() { - int t = 0; - for (Map.Entry> entry : removeMap.entrySet()) { - t = t + entry.getValue().size(); - } - for (Map.Entry> entry : addMap.entrySet()) { - t = t + entry.getValue().size(); - } - return t; - } + public static int getAll() { + int t = 0; + for (Map.Entry> entry : removeMap.entrySet()) { + t = t + entry.getValue().size(); + } + for (Map.Entry> entry : addMap.entrySet()) { + t = t + entry.getValue().size(); + } + return t; + } - public void mapAdd(String uuid, String string) { - List list = new ArrayList<>(); - if (addMap.get(uuid) != null) { - list = addMap.get(uuid); - } - list.add(string); - addMap.remove(uuid); - addMap.put(uuid, list); + public void mapAdd(String uuid, String string) { + List list = new ArrayList<>(); + if (addMap.get(uuid) != null) { + list = addMap.get(uuid); + } + list.add(string); + addMap.remove(uuid); + addMap.put(uuid, list); - if (totalMap.get(uuid) == null) { - totalMap.put(uuid, 1); - } else { - int t = totalMap.get(uuid); - totalMap.remove(uuid); - totalMap.put(uuid, t + 1); - } - } + if (totalMap.get(uuid) == null) { + totalMap.put(uuid, 1); + } else { + int t = totalMap.get(uuid); + totalMap.remove(uuid); + totalMap.put(uuid, t + 1); + } + } - public void mapRemove(String uuid, String string) { - List list = new ArrayList<>(); - if (removeMap.get(uuid) != null) { - list = removeMap.get(uuid); - } - list.add(string); - removeMap.remove(uuid); - removeMap.put(uuid, list); - if (totalMap.get(uuid) == null) { - totalMap.put(uuid, 1); - } else { - int t = totalMap.get(uuid); - totalMap.remove(uuid); - totalMap.put(uuid, t + 1); - } - } + public void mapRemove(String uuid, String string) { + List list = new ArrayList<>(); + if (removeMap.get(uuid) != null) { + list = removeMap.get(uuid); + } + list.add(string); + removeMap.remove(uuid); + removeMap.put(uuid, list); + if (totalMap.get(uuid) == null) { + totalMap.put(uuid, 1); + } else { + int t = totalMap.get(uuid); + totalMap.remove(uuid); + totalMap.put(uuid, t + 1); + } + } - public String itemString(ItemStack itemStack) { - String s = "x" + itemStack.getAmount() + " " + itemStack.getType().name().toLowerCase(); - if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName()) { - s = s + " (" + itemStack.getItemMeta().getDisplayName() + ")"; - } - return s.replace("_", " "); - } + public String itemString(ItemStack itemStack) { + String s = "x" + itemStack.getAmount() + " " + itemStack.getType().name().toLowerCase(); + if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName()) { + s = s + " (" + itemStack.getItemMeta().getDisplayName() + ")"; + } + return s.replace("_", " "); + } - @EventHandler - public void fChestInventoryClick(InventoryClickEvent e) { - Player p = (Player) e.getWhoClicked(); + @EventHandler + public void fChestInventoryClick(InventoryClickEvent e) { + Player p = (Player) e.getWhoClicked(); - Inventory topInventory = p.getOpenInventory().getTopInventory(); - Inventory bottomInventory = p.getOpenInventory().getBottomInventory(); - if (topInventory != null) { - if (topInventory.equals(FPlayers.getInstance().getByPlayer(p).getFaction().getChestInventory())) { + Inventory topInventory = p.getOpenInventory().getTopInventory(); + Inventory bottomInventory = p.getOpenInventory().getBottomInventory(); + if (topInventory != null) { + if (topInventory.equals(FPlayers.getInstance().getByPlayer(p).getFaction().getChestInventory())) { - if (e.getClickedInventory() != null) { - if (e.getClickedInventory().equals(topInventory)) { - ItemStack current = e.getCurrentItem(); - if (current == null) return; - ItemStack cursor = e.getCursor(); - if (e.getClick().isShiftClick()) return; - if (cursor != null) { - if (current.getType().equals(Material.AIR)) { - if (!cursor.getType().equals(Material.AIR)) { - mapAdd(p.getName(), itemString(cursor)); - } - } else { - if (!current.getType().equals(Material.AIR)) { - mapRemove(p.getName(), itemString(current)); - } - } - } - } else { - if (e.getClickedInventory().equals(bottomInventory)) { - //clicking from bottom inventory - if (e.getClick().isShiftClick()) { - } - } + if (e.getClickedInventory() != null) { + if (e.getClickedInventory().equals(topInventory)) { + ItemStack current = e.getCurrentItem(); + if (current == null) return; + ItemStack cursor = e.getCursor(); + if (e.getClick().isShiftClick()) return; + if (cursor != null) { + if (current.getType().equals(Material.AIR)) { + if (!cursor.getType().equals(Material.AIR)) { + mapAdd(p.getName(), itemString(cursor)); + } + } else { + if (!current.getType().equals(Material.AIR)) { + mapRemove(p.getName(), itemString(current)); + } + } + } + } else { + if (e.getClickedInventory().equals(bottomInventory)) { + //clicking from bottom inventory + if (e.getClick().isShiftClick()) { + } + } + } } - } - } - } - } + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/chest/CmdChest.java b/src/main/java/com/massivecraft/factions/cmd/chest/CmdChest.java index 5c970910..d3f03a1c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/chest/CmdChest.java +++ b/src/main/java/com/massivecraft/factions/cmd/chest/CmdChest.java @@ -10,31 +10,31 @@ 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.requirements = new CommandRequirements.Builder(Permission.CHEST) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.CHEST) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CHEST) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.CHEST) + .build(); + } - @Override - public void perform(CommandContext context) { + @Override + public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("fchest.Enabled")) { - context.fPlayer.sendMessage("This command is disabled!"); - return; - } - // This permission check is way too explicit but it's clean - context.player.openInventory(context.faction.getChestInventory()); - } + if (!FactionsPlugin.getInstance().getConfig().getBoolean("fchest.Enabled")) { + context.fPlayer.sendMessage("This command is disabled!"); + return; + } + // This permission check is way too explicit but it's clean + context.player.openInventory(context.faction.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/claim/CmdAutoClaim.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdAutoClaim.java index 74ecd1d8..3116812e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdAutoClaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdAutoClaim.java @@ -12,57 +12,57 @@ 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.requirements = new CommandRequirements.Builder(Permission.AUTOCLAIM) - .playerOnly() - .withAction(PermissableAction.TERRITORY) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.AUTOCLAIM) + .playerOnly() + .withAction(PermissableAction.TERRITORY) + .build(); + } - @Override - public void perform(CommandContext context) { - Faction forFaction = context.argAsFaction(0, context.faction); + @Override + public void perform(CommandContext context) { + Faction forFaction = context.argAsFaction(0, context.faction); - if (forFaction != context.fPlayer.getFaction()) { - if (!context.fPlayer.isAdminBypassing()) { - if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) { - context.msg(TL.COMMAND_CLAIM_DENIED); - return; - } - } - } + if (forFaction != context.fPlayer.getFaction()) { + if (!context.fPlayer.isAdminBypassing()) { + if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) { + context.msg(TL.COMMAND_CLAIM_DENIED); + return; + } + } + } - if (forFaction == null || forFaction == context.fPlayer.getAutoClaimFor()) { - context.fPlayer.setAutoClaimFor(null); - context.msg(TL.COMMAND_AUTOCLAIM_DISABLED); - return; - } + if (forFaction == null || forFaction == context.fPlayer.getAutoClaimFor()) { + context.fPlayer.setAutoClaimFor(null); + context.msg(TL.COMMAND_AUTOCLAIM_DISABLED); + return; + } - if (!context.fPlayer.canClaimForFaction(forFaction)) { - if (context.faction == forFaction) { - context.msg(TL.COMMAND_AUTOCLAIM_REQUIREDRANK, Role.MODERATOR.getTranslation()); - } else { - context.msg(TL.COMMAND_AUTOCLAIM_OTHERFACTION, forFaction.describeTo(context.fPlayer)); - } + if (!context.fPlayer.canClaimForFaction(forFaction)) { + if (context.faction == forFaction) { + context.msg(TL.COMMAND_AUTOCLAIM_REQUIREDRANK, Role.MODERATOR.getTranslation()); + } else { + context.msg(TL.COMMAND_AUTOCLAIM_OTHERFACTION, forFaction.describeTo(context.fPlayer)); + } - return; - } + return; + } - context.fPlayer.setAutoClaimFor(forFaction); + context.fPlayer.setAutoClaimFor(forFaction); - context.msg(TL.COMMAND_AUTOCLAIM_ENABLED, forFaction.describeTo(context.fPlayer)); - context.fPlayer.attemptClaim(forFaction, context.fPlayer.getPlayer().getLocation(), true); - } + context.msg(TL.COMMAND_AUTOCLAIM_ENABLED, forFaction.describeTo(context.fPlayer)); + context.fPlayer.attemptClaim(forFaction, context.fPlayer.getPlayer().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/claim/CmdClaim.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaim.java index 26cc7b04..84c7f9c2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaim.java @@ -16,73 +16,73 @@ 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.requirements = new CommandRequirements.Builder(Permission.CLAIM) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CLAIM) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { + @Override + public void perform(CommandContext context) { - // Read and validate input - int radius = context.argAsInt(0, 1); // Default to 1 - final Faction forFaction = context.argAsFaction(1, context.faction); // Default to own + // Read and validate input + int radius = context.argAsInt(0, 1); // Default to 1 + final Faction forFaction = context.argAsFaction(1, context.faction); // Default to own - if (!context.fPlayer.isAdminBypassing()) { - if (!(context.fPlayer.getFaction().equals(forFaction) && context.fPlayer.getRole() == Role.LEADER)) { - if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) { - context.msg(TL.COMMAND_CLAIM_DENIED); - return; - } - } - } - - - if (radius < 1) { - context.msg(TL.COMMAND_CLAIM_INVALIDRADIUS); - return; - } - - if (radius < 2) { - // single chunk - context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), true); - } else { - // radius claim - if (!Permission.CLAIM_RADIUS.has(context.sender, true)) { - return; - } - - new SpiralTask(new FLocation(context.player), radius) { - private final int limit = Conf.radiusClaimFailureLimit - 1; - private int failCount = 0; - - @Override - public boolean work() { - boolean success = context.fPlayer.attemptClaim(forFaction, this.currentLocation(), true); - if (success) { - failCount = 0; - } else if (failCount++ >= limit) { - this.stop(); - return false; + if (!context.fPlayer.isAdminBypassing()) { + if (!(context.fPlayer.getFaction().equals(forFaction) && context.fPlayer.getRole() == Role.LEADER)) { + if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) { + context.msg(TL.COMMAND_CLAIM_DENIED); + return; } + } + } - return true; - } - }; - } - } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CLAIM_DESCRIPTION; - } + if (radius < 1) { + context.msg(TL.COMMAND_CLAIM_INVALIDRADIUS); + return; + } + + if (radius < 2) { + // single chunk + context.fPlayer.attemptClaim(forFaction, context.player.getLocation(), true); + } else { + // radius claim + if (!Permission.CLAIM_RADIUS.has(context.sender, true)) { + return; + } + + new SpiralTask(new FLocation(context.player), radius) { + private final int limit = Conf.radiusClaimFailureLimit - 1; + private int failCount = 0; + + @Override + public boolean work() { + boolean success = context.fPlayer.attemptClaim(forFaction, this.currentLocation(), true); + if (success) { + failCount = 0; + } else if (failCount++ >= limit) { + this.stop(); + return false; + } + + return true; + } + }; + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CLAIM_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimAt.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimAt.java index b3759607..f9f94112 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimAt.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimAt.java @@ -11,36 +11,36 @@ 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.requirements = new CommandRequirements.Builder(Permission.CLAIMAT) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.TERRITORY) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CLAIMAT) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.TERRITORY) + .build(); + } - @Override - public void perform(CommandContext context) { - int x = context.argAsInt(1); - int z = context.argAsInt(2); - FLocation location = new FLocation(context.argAsString(0), x, z); - if (!((context.player.getLocation().getX() + (x * 16)) > (context.player.getLocation().getX() + (Conf.mapWidth * 16))) && - !((context.player.getLocation().getZ() + (z * 16)) > (context.player.getLocation().getZ() + (Conf.mapHeight * 16))) && - !context.argAsString(0).equals(context.player.getLocation().getWorld().getName())) { - context.fPlayer.attemptClaim(context.faction, location, true); - } else context.fPlayer.msg(TL.COMMAND_CLAIM_DENIED); - } + @Override + public void perform(CommandContext context) { + int x = context.argAsInt(1); + int z = context.argAsInt(2); + FLocation location = new FLocation(context.argAsString(0), x, z); + if (!((context.player.getLocation().getX() + (x * 16)) > (context.player.getLocation().getX() + (Conf.mapWidth * 16))) && + !((context.player.getLocation().getZ() + (z * 16)) > (context.player.getLocation().getZ() + (Conf.mapHeight * 16))) && + !context.argAsString(0).equals(context.player.getLocation().getWorld().getName())) { + context.fPlayer.attemptClaim(context.faction, location, true); + } else context.fPlayer.msg(TL.COMMAND_CLAIM_DENIED); + } - @Override - public TL getUsageTranslation() { - return null; - } + @Override + public TL getUsageTranslation() { + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimLine.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimLine.java index 6f153d79..a3f0dcc7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimLine.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdClaimLine.java @@ -14,76 +14,76 @@ 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.requirements = new CommandRequirements.Builder(Permission.CLAIM_LINE) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.TERRITORY) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CLAIM_LINE) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.TERRITORY) + .build(); + } - @Override - public void perform(CommandContext context) { - // Args - Integer amount = context.argAsInt(0, 1); // Default to 1 + @Override + public void perform(CommandContext context) { + // Args + Integer amount = context.argAsInt(0, 1); // Default to 1 - if (amount > Conf.lineClaimLimit) { - context.fPlayer.msg(TL.COMMAND_CLAIMLINE_ABOVEMAX, Conf.lineClaimLimit); - return; - } + if (amount > Conf.lineClaimLimit) { + context.fPlayer.msg(TL.COMMAND_CLAIMLINE_ABOVEMAX, Conf.lineClaimLimit); + return; + } - String direction = context.argAsString(1); - BlockFace blockFace; + String direction = context.argAsString(1); + BlockFace blockFace; - if (direction == null) { - blockFace = axis[Math.round(context.player.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 { - context.msg(TL.COMMAND_CLAIMLINE_NOTVALID, direction); - return; - } + if (direction == null) { + blockFace = axis[Math.round(context.player.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 { + context.msg(TL.COMMAND_CLAIMLINE_NOTVALID, direction); + return; + } - final Faction forFaction = context.argAsFaction(2, context.faction); + final Faction forFaction = context.argAsFaction(2, context.faction); - if (forFaction != context.fPlayer.getFaction()) { - if (!context.fPlayer.isAdminBypassing()) { - if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) { - context.msg(TL.COMMAND_CLAIM_DENIED); - return; - } - } - } + if (forFaction != context.fPlayer.getFaction()) { + if (!context.fPlayer.isAdminBypassing()) { + if (forFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) != Access.ALLOW) { + context.msg(TL.COMMAND_CLAIM_DENIED); + return; + } + } + } - Location location = context.player.getLocation(); + Location location = context.player.getLocation(); - // TODO: make this a task like claiming a radius? - for (int i = 0; i < amount; i++) { - context.fPlayer.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++) { + context.fPlayer.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/claim/CmdCorner.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdCorner.java index e1641790..442b829a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdCorner.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdCorner.java @@ -16,52 +16,52 @@ import java.util.List; public class CmdCorner extends FCommand { - public CmdCorner() { - this.aliases.add("corner"); + public CmdCorner() { + this.aliases.add("corner"); - this.requirements = new CommandRequirements.Builder(Permission.CORNER) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.TERRITORY) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CORNER) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.TERRITORY) + .build(); + } - @Override - public void perform(CommandContext context) { - FLocation to = new FLocation(context.player.getLocation()); - if (FactionsPlugin.getInstance().getFactionsPlayerListener().getCorners().contains(to)) { - Faction cornerAt = Board.getInstance().getFactionAt(to); - if (cornerAt != null && cornerAt.isNormal() && !cornerAt.equals(context.fPlayer.getFaction())) { - context.msg(TL.COMMAND_CORNER_CANT_CLAIM); - } else { - context.msg(TL.COMMAND_CORNER_ATTEMPTING_CLAIM); - List surrounding = new ArrayList<>(400); - for (int x = 0; x < Conf.factionBufferSize; ++x) { - for (int z = 0; z < Conf.factionBufferSize; ++z) { - int newX = (int) ((to.getX() > 0L) ? (to.getX() - x) : (to.getX() + x)); - int newZ = (int) ((to.getZ() > 0L) ? (to.getZ() - z) : (to.getZ() + z)); - FLocation location = new FLocation(context.player.getWorld().getName(), newX, newZ); - Faction at = Board.getInstance().getFactionAt(location); - if (at == null || !at.isNormal()) { - surrounding.add(location); - } - } - } - surrounding.sort(Comparator.comparingInt(fLocation -> (int) fLocation.getDistanceTo(to))); - if (surrounding.isEmpty()) { + @Override + public void perform(CommandContext context) { + FLocation to = new FLocation(context.player.getLocation()); + if (FactionsPlugin.getInstance().getFactionsPlayerListener().getCorners().contains(to)) { + Faction cornerAt = Board.getInstance().getFactionAt(to); + if (cornerAt != null && cornerAt.isNormal() && !cornerAt.equals(context.fPlayer.getFaction())) { context.msg(TL.COMMAND_CORNER_CANT_CLAIM); - } else { - new CornerTask(context.fPlayer, surrounding).runTaskTimer(FactionsPlugin.getInstance(), 1L, 1L); - } - } - } else { - context.msg(TL.COMMAND_CORNER_NOT_CORNER); - } - } + } else { + context.msg(TL.COMMAND_CORNER_ATTEMPTING_CLAIM); + List surrounding = new ArrayList<>(400); + for (int x = 0; x < Conf.factionBufferSize; ++x) { + for (int z = 0; z < Conf.factionBufferSize; ++z) { + int newX = (int) ((to.getX() > 0L) ? (to.getX() - x) : (to.getX() + x)); + int newZ = (int) ((to.getZ() > 0L) ? (to.getZ() - z) : (to.getZ() + z)); + FLocation location = new FLocation(context.player.getWorld().getName(), newX, newZ); + Faction at = Board.getInstance().getFactionAt(location); + if (at == null || !at.isNormal()) { + surrounding.add(location); + } + } + } + surrounding.sort(Comparator.comparingInt(fLocation -> (int) fLocation.getDistanceTo(to))); + if (surrounding.isEmpty()) { + context.msg(TL.COMMAND_CORNER_CANT_CLAIM); + } else { + new CornerTask(context.fPlayer, surrounding).runTaskTimer(FactionsPlugin.getInstance(), 1L, 1L); + } + } + } else { + context.msg(TL.COMMAND_CORNER_NOT_CORNER); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CORNER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CORNER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/claim/CmdSafeunclaimall.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdSafeunclaimall.java index bb210593..c1e26fd6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdSafeunclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdSafeunclaimall.java @@ -14,42 +14,42 @@ import org.bukkit.World; public class CmdSafeunclaimall extends FCommand { - public CmdSafeunclaimall() { - this.aliases.add("safeunclaimall"); - this.aliases.add("safedeclaimall"); - this.optionalArgs.put("world", "all"); + public CmdSafeunclaimall() { + this.aliases.add("safeunclaimall"); + this.aliases.add("safedeclaimall"); + this.optionalArgs.put("world", "all"); - this.requirements = new CommandRequirements.Builder(Permission.MANAGE_SAFE_ZONE) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MANAGE_SAFE_ZONE) + .build(); + } - @Override - public void perform(CommandContext context) { - String worldName = context.argAsString(0); - World world = null; + @Override + public void perform(CommandContext context) { + String worldName = context.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); + } - context.msg(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMED); + context.msg(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMED); - if (Conf.logLandUnclaims) { - FactionsPlugin.getInstance().log(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMEDLOG.format(context.sender.getName())); - } - } + if (Conf.logLandUnclaims) { + FactionsPlugin.getInstance().log(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMEDLOG.format(context.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/claim/CmdUnclaim.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java index 01bb5ad6..3217258b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaim.java @@ -16,175 +16,175 @@ 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("faction", "yours"); + this.optionalArgs.put("radius", "1"); + this.optionalArgs.put("faction", "yours"); - this.requirements = new CommandRequirements.Builder(Permission.UNCLAIM) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.TERRITORY) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.UNCLAIM) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.TERRITORY) + .build(); + } - @Override - public void perform(CommandContext context) { + @Override + public void perform(CommandContext context) { - if (context.args.size() == 2) { - Faction target = context.argAsFaction(1); - // Dont have to say anything since the argsAsFaction method will tell the player for me. - if (target == null) return; - context.faction = target; - if (context.faction != context.fPlayer.getFaction() && !context.fPlayer.isAdminBypassing()) { - context.msg(TL.COMMAND_UNCLAIM_WRONGFACTION); - return; - } - } + if (context.args.size() == 2) { + Faction target = context.argAsFaction(1); + // Dont have to say anything since the argsAsFaction method will tell the player for me. + if (target == null) return; + context.faction = target; + if (context.faction != context.fPlayer.getFaction() && !context.fPlayer.isAdminBypassing()) { + context.msg(TL.COMMAND_UNCLAIM_WRONGFACTION); + return; + } + } - // Read and validate input - int radius = context.argAsInt(0, 1); // Default to 1 + // Read and validate input + int radius = context.argAsInt(0, 1); // Default to 1 - if (radius < 1) { - context.msg(TL.COMMAND_CLAIM_INVALIDRADIUS); - return; - } + if (radius < 1) { + context.msg(TL.COMMAND_CLAIM_INVALIDRADIUS); + return; + } - if (radius == 1) { - // single chunk - unClaim(new FLocation(context.player), context); - } else { - // radius claim - if (!Permission.CLAIM_RADIUS.has(context.sender, false)) { - context.msg(TL.COMMAND_CLAIM_DENIED); - return; - } + if (radius == 1) { + // single chunk + unClaim(new FLocation(context.player), context); + } else { + // radius claim + if (!Permission.CLAIM_RADIUS.has(context.sender, false)) { + context.msg(TL.COMMAND_CLAIM_DENIED); + return; + } - new SpiralTask(new FLocation(context.player), radius) { - private final int limit = Conf.radiusClaimFailureLimit - 1; - private int failCount = 0; + new SpiralTask(new FLocation(context.player), radius) { + private final int limit = Conf.radiusClaimFailureLimit - 1; + private int failCount = 0; - @Override - public boolean work() { - boolean success = unClaim(currentFLocation(), context); - if (success) { - failCount = 0; - } else if (failCount++ >= limit) { - this.stop(); - return false; + @Override + public boolean work() { + boolean success = unClaim(currentFLocation(), context); + if (success) { + failCount = 0; + } else if (failCount++ >= limit) { + this.stop(); + return false; + } + + return true; } + }; + } + } + private boolean unClaim(FLocation target, CommandContext context) { + Faction targetFaction = Board.getInstance().getFactionAt(target); + if (targetFaction.isSafeZone()) { + if (Permission.MANAGE_SAFE_ZONE.has(context.sender)) { + Board.getInstance().removeAt(target); + context.msg(TL.COMMAND_UNCLAIM_SAFEZONE_SUCCESS); + + if (Conf.logLandUnclaims) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); + } return true; - } - }; - } - } - - private boolean unClaim(FLocation target, CommandContext context) { - Faction targetFaction = Board.getInstance().getFactionAt(target); - if (targetFaction.isSafeZone()) { - if (Permission.MANAGE_SAFE_ZONE.has(context.sender)) { - Board.getInstance().removeAt(target); - context.msg(TL.COMMAND_UNCLAIM_SAFEZONE_SUCCESS); - - if (Conf.logLandUnclaims) { - FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); - } - return true; - } else { - context.msg(TL.COMMAND_UNCLAIM_SAFEZONE_NOPERM); - return false; - } - } else if (targetFaction.isWarZone()) { - if (Permission.MANAGE_WAR_ZONE.has(context.sender)) { - Board.getInstance().removeAt(target); - context.msg(TL.COMMAND_UNCLAIM_WARZONE_SUCCESS); - - if (Conf.logLandUnclaims) { - FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); - } - return true; - } else { - context.msg(TL.COMMAND_UNCLAIM_WARZONE_NOPERM); - return false; - } - } - - if (context.fPlayer.isAdminBypassing()) { - LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, context.fPlayer); - Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); - if (unclaimEvent.isCancelled()) { - return false; - } - - Board.getInstance().removeAt(target); - - targetFaction.msg(TL.COMMAND_UNCLAIM_UNCLAIMED, context.fPlayer.describeTo(targetFaction, true)); - context.msg(TL.COMMAND_UNCLAIM_UNCLAIMS); - - if (Conf.logLandUnclaims) { - FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); - } - - return true; - } - - if (targetFaction.getClaimOwnership().containsKey(target) && !targetFaction.isPlayerInOwnerList(context.fPlayer, target)) { - context.msg(TL.GENERIC_FPERM_OWNER_NOPERMISSION, "unclaim"); - return false; - } - - if (targetFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) == Access.DENY && context.fPlayer.getRole() != Role.LEADER) { - context.msg(TL.GENERIC_FPERM_NOPERMISSION, "unclaim"); - return false; - } - - if (!context.assertHasFaction()) { - context.msg(TL.ACTIONS_NOFACTION); - return false; - } - - if (context.faction != targetFaction) { - context.msg(TL.COMMAND_UNCLAIM_WRONGFACTION); - return false; - } - - - LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, context.fPlayer); - Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> Bukkit.getServer().getPluginManager().callEvent(unclaimEvent)); - if (unclaimEvent.isCancelled()) { - return false; - } - - if (Econ.shouldBeUsed()) { - double refund = Econ.calculateClaimRefund(context.faction.getLandRounded()); - - if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { - if (!Econ.modifyMoney(context.faction, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { + } else { + context.msg(TL.COMMAND_UNCLAIM_SAFEZONE_NOPERM); return false; - } - } else { - if (!Econ.modifyMoney(context.fPlayer, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { + } + } else if (targetFaction.isWarZone()) { + if (Permission.MANAGE_WAR_ZONE.has(context.sender)) { + Board.getInstance().removeAt(target); + context.msg(TL.COMMAND_UNCLAIM_WARZONE_SUCCESS); + + if (Conf.logLandUnclaims) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); + } + return true; + } else { + context.msg(TL.COMMAND_UNCLAIM_WARZONE_NOPERM); return false; - } - } - } + } + } - Board.getInstance().removeAt(target); - context.faction.msg(TL.COMMAND_UNCLAIM_FACTIONUNCLAIMED, context.fPlayer.describeTo(context.faction, true)); + if (context.fPlayer.isAdminBypassing()) { + LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, context.fPlayer); + Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); + if (unclaimEvent.isCancelled()) { + return false; + } - if (Conf.logLandUnclaims) { - FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); - } + Board.getInstance().removeAt(target); - return true; - } + targetFaction.msg(TL.COMMAND_UNCLAIM_UNCLAIMED, context.fPlayer.describeTo(targetFaction, true)); + context.msg(TL.COMMAND_UNCLAIM_UNCLAIMS); - @Override - public TL getUsageTranslation() { - return TL.COMMAND_UNCLAIM_DESCRIPTION; - } + if (Conf.logLandUnclaims) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); + } + + return true; + } + + if (targetFaction.getClaimOwnership().containsKey(target) && !targetFaction.isPlayerInOwnerList(context.fPlayer, target)) { + context.msg(TL.GENERIC_FPERM_OWNER_NOPERMISSION, "unclaim"); + return false; + } + + if (targetFaction.getAccess(context.fPlayer, PermissableAction.TERRITORY) == Access.DENY && context.fPlayer.getRole() != Role.LEADER) { + context.msg(TL.GENERIC_FPERM_NOPERMISSION, "unclaim"); + return false; + } + + if (!context.assertHasFaction()) { + context.msg(TL.ACTIONS_NOFACTION); + return false; + } + + if (context.faction != targetFaction) { + context.msg(TL.COMMAND_UNCLAIM_WRONGFACTION); + return false; + } + + + LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, context.fPlayer); + Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> Bukkit.getServer().getPluginManager().callEvent(unclaimEvent)); + if (unclaimEvent.isCancelled()) { + return false; + } + + if (Econ.shouldBeUsed()) { + double refund = Econ.calculateClaimRefund(context.faction.getLandRounded()); + + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { + if (!Econ.modifyMoney(context.faction, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { + return false; + } + } else { + if (!Econ.modifyMoney(context.fPlayer, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { + return false; + } + } + } + + Board.getInstance().removeAt(target); + context.faction.msg(TL.COMMAND_UNCLAIM_FACTIONUNCLAIMED, context.fPlayer.describeTo(context.faction, true)); + + if (Conf.logLandUnclaims) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIM_LOG.format(context.fPlayer.getName(), target.getCoordString(), targetFaction.getTag())); + } + + return true; + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UNCLAIM_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java index 8df9fba8..c3265db4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdUnclaimall.java @@ -16,72 +16,72 @@ 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.optionalArgs.put("faction", "yours"); + this.optionalArgs.put("faction", "yours"); - this.requirements = new CommandRequirements.Builder(Permission.UNCLAIM_ALL) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.TERRITORY) //TODO: Add Unclaimall PermissableAction - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.UNCLAIM_ALL) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.TERRITORY) //TODO: Add Unclaimall PermissableAction + .build(); + } - @Override - public void perform(CommandContext context) { - Faction target = context.faction; - if (context.args.size() == 1) { - target = context.argAsFaction(0); - if (target == null) { - context.msg(TL.GENERIC_NOFACTION_FOUND); - return; - } - - if (!context.fPlayer.isAdminBypassing()) { - context.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", target.getTag()).replace("{action}", "unclaimall land")); - return; - } - - Board.getInstance().unclaimAll(target.getId()); - context.faction.msg(TL.COMMAND_UNCLAIMALL_LOG, context.fPlayer.describeTo(target, true), target.getTag()); - if (Conf.logLandUnclaims) - FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIMALL_LOG.format(context.fPlayer.getName(), context.faction.getTag())); - return; - - } - if (Econ.shouldBeUsed()) { - double refund = Econ.calculateTotalLandRefund(target.getLandRounded()); - if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { - if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + @Override + public void perform(CommandContext context) { + Faction target = context.faction; + if (context.args.size() == 1) { + target = context.argAsFaction(0); + if (target == null) { + context.msg(TL.GENERIC_NOFACTION_FOUND); return; - } - } else { - if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + } + + if (!context.fPlayer.isAdminBypassing()) { + context.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", target.getTag()).replace("{action}", "unclaimall land")); return; - } - } - } + } - LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(target, context.fPlayer); - Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> Bukkit.getServer().getPluginManager().callEvent(unclaimAllEvent)); - if (unclaimAllEvent.isCancelled()) { - return; - } + Board.getInstance().unclaimAll(target.getId()); + context.faction.msg(TL.COMMAND_UNCLAIMALL_LOG, context.fPlayer.describeTo(target, true), target.getTag()); + if (Conf.logLandUnclaims) + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIMALL_LOG.format(context.fPlayer.getName(), context.faction.getTag())); + return; - Board.getInstance().unclaimAll(target.getId()); - context.faction.msg(TL.COMMAND_UNCLAIMALL_UNCLAIMED, context.fPlayer.describeTo(context.faction, true)); + } + if (Econ.shouldBeUsed()) { + double refund = Econ.calculateTotalLandRefund(target.getLandRounded()); + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { + if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + return; + } + } else { + if (!Econ.modifyMoney(target, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + return; + } + } + } - if (Conf.logLandUnclaims) { - FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIMALL_LOG.format(context.fPlayer.getName(), context.faction.getTag())); - } - } + LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(target, context.fPlayer); + Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> Bukkit.getServer().getPluginManager().callEvent(unclaimAllEvent)); + if (unclaimAllEvent.isCancelled()) { + return; + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_UNCLAIMALL_DESCRIPTION; - } + Board.getInstance().unclaimAll(target.getId()); + context.faction.msg(TL.COMMAND_UNCLAIMALL_UNCLAIMED, context.fPlayer.describeTo(context.faction, true)); + + if (Conf.logLandUnclaims) { + FactionsPlugin.getInstance().log(TL.COMMAND_UNCLAIMALL_LOG.format(context.fPlayer.getName(), context.faction.getTag())); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UNCLAIMALL_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/claim/CmdWarunclaimall.java b/src/main/java/com/massivecraft/factions/cmd/claim/CmdWarunclaimall.java index 5c15eca4..b44baa9c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/claim/CmdWarunclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/claim/CmdWarunclaimall.java @@ -14,39 +14,39 @@ import org.bukkit.World; public class CmdWarunclaimall extends FCommand { - public CmdWarunclaimall() { - this.aliases.add("warunclaimall"); - this.aliases.add("wardeclaimall"); - this.optionalArgs.put("world", "all"); + public CmdWarunclaimall() { + this.aliases.add("warunclaimall"); + this.aliases.add("wardeclaimall"); + this.optionalArgs.put("world", "all"); - this.requirements = new CommandRequirements.Builder(Permission.MANAGE_WAR_ZONE) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MANAGE_WAR_ZONE) + .build(); + } - @Override - public void perform(CommandContext context) { - String worldName = context.argAsString(0); - World world = null; + @Override + public void perform(CommandContext context) { + String worldName = context.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); + } - context.msg(TL.COMMAND_WARUNCLAIMALL_SUCCESS); - if (Conf.logLandUnclaims) - FactionsPlugin.getInstance().log(TL.COMMAND_WARUNCLAIMALL_LOG.format(context.fPlayer.getName())); - } + context.msg(TL.COMMAND_WARUNCLAIMALL_SUCCESS); + if (Conf.logLandUnclaims) + FactionsPlugin.getInstance().log(TL.COMMAND_WARUNCLAIMALL_LOG.format(context.fPlayer.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/configsf/CmdConvertConfig.java b/src/main/java/com/massivecraft/factions/cmd/configsf/CmdConvertConfig.java index 73ada76e..40ec56f5 100644 --- a/src/main/java/com/massivecraft/factions/cmd/configsf/CmdConvertConfig.java +++ b/src/main/java/com/massivecraft/factions/cmd/configsf/CmdConvertConfig.java @@ -8,22 +8,22 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdConvertConfig extends FCommand { - public CmdConvertConfig() { - super(); - this.aliases.add("convertconfig"); + public CmdConvertConfig() { + super(); + this.aliases.add("convertconfig"); - this.requirements = new CommandRequirements.Builder(Permission.CONVERTCONFIG) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.CONVERTCONFIG) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - ConvertConfigHandler.convertconfig(context.player); - } + @Override + public void perform(CommandContext context) { + ConvertConfigHandler.convertconfig(context.player); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CONVERTCONFIG_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CONVERTCONFIG_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/configsf/ConvertConfigHandler.java b/src/main/java/com/massivecraft/factions/cmd/configsf/ConvertConfigHandler.java index e176682c..f59ff324 100644 --- a/src/main/java/com/massivecraft/factions/cmd/configsf/ConvertConfigHandler.java +++ b/src/main/java/com/massivecraft/factions/cmd/configsf/ConvertConfigHandler.java @@ -19,124 +19,129 @@ import java.util.logging.Level; public class ConvertConfigHandler { - static File savageConfigFile = new File("plugins/Factions/SavageFactions/config.yml"); - static FileConfiguration sv = YamlConfiguration.loadConfiguration(savageConfigFile); - static File configFile = new File("plugins/Factions/config.yml"); - static FileConfiguration sb = YamlConfiguration.loadConfiguration(configFile); - public static void setString(String s){ - sb.set(s, sv.getString(s)); - } - public static void setInt(String s){ - sb.set(s, sv.getInt(s)); - } - public static void setConfigSec(String s){ - ConfigurationSection cs = sv.getConfigurationSection(s); - sb.set(s, cs); - } - static JavaPlugin plugin = JavaPlugin.getProvidingPlugin(FactionsPlugin.class); - public static void setBoolean(String s){ - sb.set(s, sv.getBoolean(s)); - } - public static void convertconfig(Player player) { - if (new File("plugins/Factions/SavageFactions/config.yml").exists()) { - BukkitScheduler scheduler = plugin.getServer().getScheduler(); - scheduler.scheduleAsyncDelayedTask(plugin, () -> { - File savageConfigFile = new File("plugins/Factions/SavageFactions/config.yml"); - FileConfiguration sv = YamlConfiguration.loadConfiguration(savageConfigFile); - File configFile = new File("plugins/Factions/config.yml"); - FileConfiguration sb = YamlConfiguration.loadConfiguration(configFile); - sb.set("ConfigConvertedFromSavageFactions", true); - sb.set("debug", sv.getBoolean("debug")); - ConfigurationSection ffe = sv.getConfigurationSection("findfactionsexploit"); - sb.set("findfactionsexploit", ffe); - setString("default-relation"); - ConfigurationSection pC = sv.getConfigurationSection("portals"); - sb.set("portals", pC); - sb.set("maxwarps", sv.getInt("maxwarps")); - setConfigSec("warp-cost"); - setBoolean("enable-faction-flight"); - setBoolean("ffly.AutoEnable"); - setInt("fly-falldamage-cooldown"); - setBoolean("disable-pistons-in-territory"); - setConfigSec("tooltips"); - setConfigSec("scoreboard"); - sb.set("scoreboard.also-send-chat", true); - setConfigSec("warmups"); - setConfigSec("max-relations"); - setInt("world-border.buffer"); - setConfigSec("hcf"); - sb.set("show", sv.getStringList("show")); - setBoolean("show-exempt"); - sb.set("map", sv.getStringList("map")); - setConfigSec("list"); - setBoolean("use-old-help"); - setConfigSec("help"); - setConfigSec("fperm-gui"); - sb.set("fperm-gui.action.slots.check", 50); - setConfigSec("fwarp-gui"); - setBoolean("faction-creation-broadcast"); - setBoolean("faction-disband-broadcast"); - setBoolean("See-Invisible-Faction-Members"); - setConfigSec("frules"); - setConfigSec("ftnt"); - setBoolean("fpaypal.Enabled"); - setBoolean("checkpoints.Enabled"); - setConfigSec("fnear"); - setConfigSec("ffocus"); - setConfigSec("fvualt"); - setString("fupgrades.MainMenu.Title"); - setString("fupgrades.MainMenu.DummyItem.Name"); - setString("fupgrades.MainMenu.DummyItem.Type"); - List l = sv.getStringList("fupgrades.MainMenu.DummyItem.Lore"); - sb.set("fupgrades.MainMenu.DummyItem.Lore", l); - setConfigSec("fupgrades.MainMenu.Crops.Crop-Boost"); - setConfigSec("fupgrades.MainMenu.Crops.Cost"); - sb.set("fupgrades.MainMenu.Crops.CropItem", sv.getConfigurationSection("fupgrades.MainMenu.Crops.DisplayItem")); - setConfigSec("fupgrades.MainMenu.EXP.EXP-Boost"); - setConfigSec("fupgrades.MainMenu.EXP.Cost"); - sb.set("fupgrades.MainMenu.EXP.EXPItem", sv.getConfigurationSection("fupgrades.MainMenu.EXP.DisplayItem")); - setConfigSec("fupgrades.MainMenu.Power.Power-Boost"); - setConfigSec("fupgrades.MainMenu.Power.Cost"); - sb.set("fupgrades.MainMenu.Power.PowerItem", sv.getConfigurationSection("fupgrades.MainMenu.Power.DisplayItem")); - List p = new ArrayList(); - p.add(sv.getInt("fupgrades.MainMenu.Power.DisplayItem.Slot")); - sb.set("fupgrades.MainMenu.Power.PowerItem.slots", p); - sb.set("fupgrades.MainMenu.Power.PowerItem.Amount", 1); - sb.set("fupgrades.MainMenu.Power.PowerItem.Damage", 0); - sb.set("fupgrades.MainMenu.Power.PowerItem.Slot", null); - sb.set("fupgrades.MainMenu.Members.Members-Limit", sv.getConfigurationSection("fupgrades.MainMenu.Members.Members-Boost")); - setConfigSec("fupgrades.MainMenu.Spawners.Spawner-Boost"); - setConfigSec("fupgrades.MainMenu.Spawners.Cost"); - sb.set("fupgrades.MainMenu.Spawners.SpawnerItem", sv.getConfigurationSection("fupgrades.MainMenu.Spawners.DisplayItem")); - setConfigSec("fupgrades.MainMenu.Chest.Chest-Size"); - setConfigSec("fupgrades.MainMenu.Chest.Cost"); - sb.set("fupgrades.MainMenu.Chest.ChestItem", sv.getConfigurationSection("fupgrades.MainMenu.Chest.DisplayItem")); - setConfigSec("fupgrades.MainMenu.Members.Cost"); - sb.set("fupgrades.MainMenu.Members.MembersItem", sv.getConfigurationSection("fupgrades.MainMenu.Members.DisplayItem")); - sb.set("fupgrades.MainMenu.Members.MembersItem.Amount", 1); - sb.set("fupgrades.MainMenu.Members.MembersItem.Damage", 0); - if (sv.getString("fupgrades.MainMenu.Members.DisplayItem.Type").equalsIgnoreCase("PLAYER_HEAD")) - sb.set("fupgrades.MainMenu.Members.MembersItem.Type", "PAPER"); - List x = new ArrayList(); - x.add(sv.getInt("fupgrades.MainMenu.Members.DisplayItem.Slot")); - sb.set("fupgrades.MainMenu.Members.MembersItem.slots", x); - sb.set("fupgrades.MainMenu.Members.MembersItem.Slot", null); - sb.set("fupgrades.MainMenu.Members.Members-Limit", sv.getConfigurationSection("fupgrades.MainMenu.Members.Members-Boost")); - setConfigSec("fbanners"); - setConfigSec("see-chunk"); - setConfigSec("Tntfill"); - try { - sb.save(configFile); - plugin.reloadConfig(); - } catch (IOException e) { - player.sendMessage(TL.COMMAND_CONVERTCONFIG_FAIL.toString()); - Bukkit.getLogger().log(Level.SEVERE, Arrays.toString(e.getStackTrace())); - } - player.sendMessage(TL.COMMAND_CONVERTCONFIG_SUCCESS.toString()); - }, 0L); - } else { - player.sendMessage(TL.COMMAND_CONVERTCONFIG_FAILCONFIGMISSING.toString()); - } - } + static File savageConfigFile = new File("plugins/Factions/SavageFactions/config.yml"); + static FileConfiguration sv = YamlConfiguration.loadConfiguration(savageConfigFile); + static File configFile = new File("plugins/Factions/config.yml"); + static FileConfiguration sb = YamlConfiguration.loadConfiguration(configFile); + static JavaPlugin plugin = JavaPlugin.getProvidingPlugin(FactionsPlugin.class); + + public static void setString(String s) { + sb.set(s, sv.getString(s)); + } + + public static void setInt(String s) { + sb.set(s, sv.getInt(s)); + } + + public static void setConfigSec(String s) { + ConfigurationSection cs = sv.getConfigurationSection(s); + sb.set(s, cs); + } + + public static void setBoolean(String s) { + sb.set(s, sv.getBoolean(s)); + } + + public static void convertconfig(Player player) { + if (new File("plugins/Factions/SavageFactions/config.yml").exists()) { + BukkitScheduler scheduler = plugin.getServer().getScheduler(); + scheduler.scheduleAsyncDelayedTask(plugin, () -> { + File savageConfigFile = new File("plugins/Factions/SavageFactions/config.yml"); + FileConfiguration sv = YamlConfiguration.loadConfiguration(savageConfigFile); + File configFile = new File("plugins/Factions/config.yml"); + FileConfiguration sb = YamlConfiguration.loadConfiguration(configFile); + sb.set("ConfigConvertedFromSavageFactions", true); + sb.set("debug", sv.getBoolean("debug")); + ConfigurationSection ffe = sv.getConfigurationSection("findfactionsexploit"); + sb.set("findfactionsexploit", ffe); + setString("default-relation"); + ConfigurationSection pC = sv.getConfigurationSection("portals"); + sb.set("portals", pC); + sb.set("maxwarps", sv.getInt("maxwarps")); + setConfigSec("warp-cost"); + setBoolean("enable-faction-flight"); + setBoolean("ffly.AutoEnable"); + setInt("fly-falldamage-cooldown"); + setBoolean("disable-pistons-in-territory"); + setConfigSec("tooltips"); + setConfigSec("scoreboard"); + sb.set("scoreboard.also-send-chat", true); + setConfigSec("warmups"); + setConfigSec("max-relations"); + setInt("world-border.buffer"); + setConfigSec("hcf"); + sb.set("show", sv.getStringList("show")); + setBoolean("show-exempt"); + sb.set("map", sv.getStringList("map")); + setConfigSec("list"); + setBoolean("use-old-help"); + setConfigSec("help"); + setConfigSec("fperm-gui"); + sb.set("fperm-gui.action.slots.check", 50); + setConfigSec("fwarp-gui"); + setBoolean("faction-creation-broadcast"); + setBoolean("faction-disband-broadcast"); + setBoolean("See-Invisible-Faction-Members"); + setConfigSec("frules"); + setConfigSec("ftnt"); + setBoolean("fpaypal.Enabled"); + setBoolean("checkpoints.Enabled"); + setConfigSec("fnear"); + setConfigSec("ffocus"); + setConfigSec("fvualt"); + setString("fupgrades.MainMenu.Title"); + setString("fupgrades.MainMenu.DummyItem.Name"); + setString("fupgrades.MainMenu.DummyItem.Type"); + List l = sv.getStringList("fupgrades.MainMenu.DummyItem.Lore"); + sb.set("fupgrades.MainMenu.DummyItem.Lore", l); + setConfigSec("fupgrades.MainMenu.Crops.Crop-Boost"); + setConfigSec("fupgrades.MainMenu.Crops.Cost"); + sb.set("fupgrades.MainMenu.Crops.CropItem", sv.getConfigurationSection("fupgrades.MainMenu.Crops.DisplayItem")); + setConfigSec("fupgrades.MainMenu.EXP.EXP-Boost"); + setConfigSec("fupgrades.MainMenu.EXP.Cost"); + sb.set("fupgrades.MainMenu.EXP.EXPItem", sv.getConfigurationSection("fupgrades.MainMenu.EXP.DisplayItem")); + setConfigSec("fupgrades.MainMenu.Power.Power-Boost"); + setConfigSec("fupgrades.MainMenu.Power.Cost"); + sb.set("fupgrades.MainMenu.Power.PowerItem", sv.getConfigurationSection("fupgrades.MainMenu.Power.DisplayItem")); + List p = new ArrayList(); + p.add(sv.getInt("fupgrades.MainMenu.Power.DisplayItem.Slot")); + sb.set("fupgrades.MainMenu.Power.PowerItem.slots", p); + sb.set("fupgrades.MainMenu.Power.PowerItem.Amount", 1); + sb.set("fupgrades.MainMenu.Power.PowerItem.Damage", 0); + sb.set("fupgrades.MainMenu.Power.PowerItem.Slot", null); + sb.set("fupgrades.MainMenu.Members.Members-Limit", sv.getConfigurationSection("fupgrades.MainMenu.Members.Members-Boost")); + setConfigSec("fupgrades.MainMenu.Spawners.Spawner-Boost"); + setConfigSec("fupgrades.MainMenu.Spawners.Cost"); + sb.set("fupgrades.MainMenu.Spawners.SpawnerItem", sv.getConfigurationSection("fupgrades.MainMenu.Spawners.DisplayItem")); + setConfigSec("fupgrades.MainMenu.Chest.Chest-Size"); + setConfigSec("fupgrades.MainMenu.Chest.Cost"); + sb.set("fupgrades.MainMenu.Chest.ChestItem", sv.getConfigurationSection("fupgrades.MainMenu.Chest.DisplayItem")); + setConfigSec("fupgrades.MainMenu.Members.Cost"); + sb.set("fupgrades.MainMenu.Members.MembersItem", sv.getConfigurationSection("fupgrades.MainMenu.Members.DisplayItem")); + sb.set("fupgrades.MainMenu.Members.MembersItem.Amount", 1); + sb.set("fupgrades.MainMenu.Members.MembersItem.Damage", 0); + if (sv.getString("fupgrades.MainMenu.Members.DisplayItem.Type").equalsIgnoreCase("PLAYER_HEAD")) + sb.set("fupgrades.MainMenu.Members.MembersItem.Type", "PAPER"); + List x = new ArrayList(); + x.add(sv.getInt("fupgrades.MainMenu.Members.DisplayItem.Slot")); + sb.set("fupgrades.MainMenu.Members.MembersItem.slots", x); + sb.set("fupgrades.MainMenu.Members.MembersItem.Slot", null); + sb.set("fupgrades.MainMenu.Members.Members-Limit", sv.getConfigurationSection("fupgrades.MainMenu.Members.Members-Boost")); + setConfigSec("fbanners"); + setConfigSec("see-chunk"); + setConfigSec("Tntfill"); + try { + sb.save(configFile); + plugin.reloadConfig(); + } catch (IOException e) { + player.sendMessage(TL.COMMAND_CONVERTCONFIG_FAIL.toString()); + Bukkit.getLogger().log(Level.SEVERE, Arrays.toString(e.getStackTrace())); + } + player.sendMessage(TL.COMMAND_CONVERTCONFIG_SUCCESS.toString()); + }, 0L); + } else { + player.sendMessage(TL.COMMAND_CONVERTCONFIG_FAILCONFIGMISSING.toString()); + } + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoney.java b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoney.java index 3b3380b7..10fef77b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoney.java +++ b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoney.java @@ -8,44 +8,44 @@ 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"); - this.aliases.add("bank"); + public CmdMoney() { + super(); + this.aliases.add("money"); + this.aliases.add("bank"); - //this.requiredArgs.add(""); - //this.optionalArgs.put("","") + //this.requiredArgs.add(""); + //this.optionalArgs.put("","") - this.helpLong.add(FactionsPlugin.getInstance().txt.parseTags(TL.COMMAND_MONEY_LONG.toString())); + this.helpLong.add(FactionsPlugin.getInstance().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(CommandContext context) { - if (!Conf.econEnabled) { - context.msg(TL.ECON_OFF, "economy option is enabled, please set \'econEnabled\' to true in conf.json"); - return; - } - context.commandChain.add(this); - FactionsPlugin.getInstance().cmdAutoHelp.execute(context); - } + @Override + public void perform(CommandContext context) { + if (!Conf.econEnabled) { + context.msg(TL.ECON_OFF, "economy option is enabled, please set \'econEnabled\' to true in conf.json"); + return; + } + context.commandChain.add(this); + FactionsPlugin.getInstance().cmdAutoHelp.execute(context); + } - @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/econ/CmdMoneyBalance.java b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyBalance.java index cde68cd3..44e6b34d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyBalance.java +++ b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyBalance.java @@ -11,43 +11,43 @@ import org.bukkit.command.CommandSender; 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.setHelpShort(TL.COMMAND_MONEYBALANCE_SHORT.toString()); + this.setHelpShort(TL.COMMAND_MONEYBALANCE_SHORT.toString()); - this.requirements = new CommandRequirements.Builder(Permission.MONEY_BALANCE).build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MONEY_BALANCE).build(); + } - @Override - public void perform(CommandContext context) { - Faction faction = context.faction; - if (context.argIsSet(0)) { - faction = context.argAsFaction(0); - } + @Override + public void perform(CommandContext context) { + Faction faction = context.faction; + if (context.argIsSet(0)) { + faction = context.argAsFaction(0); + } - if (faction == null) { - return; - } - if (faction != context.faction && !Permission.MONEY_BALANCE_ANY.has(context.sender, true)) { - return; - } + if (faction == null) { + return; + } + if (faction != context.faction && !Permission.MONEY_BALANCE_ANY.has(context.sender, true)) { + return; + } - if (context.fPlayer != null) { - Econ.sendBalanceInfo((CommandSender) context.fPlayer, faction); - } else { - Econ.sendBalanceInfo(context.sender, faction); - } - } + if (context.fPlayer != null) { + Econ.sendBalanceInfo((CommandSender) context.fPlayer, faction); + } else { + Econ.sendBalanceInfo(context.sender, 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/econ/CmdMoneyDeposit.java b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyDeposit.java index 24becf24..12bd11f2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyDeposit.java +++ b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyDeposit.java @@ -14,37 +14,37 @@ 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.requirements = new CommandRequirements.Builder(Permission.MONEY_DEPOSIT) - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MONEY_DEPOSIT) + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - double amount = context.argAsDouble(0, 0d); - EconomyParticipator faction = context.argAsFaction(1, context.faction); - if (faction == null) { - return; - } - boolean success = Econ.transferMoney(context.fPlayer, context.fPlayer, faction, amount); + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator faction = context.argAsFaction(1, context.faction); + if (faction == null) { + return; + } + boolean success = Econ.transferMoney(context.fPlayer, context.fPlayer, faction, amount); - if (success && Conf.logMoneyTransactions) { - FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYDEPOSIT_DEPOSITED.toString(), context.fPlayer.getName(), Econ.moneyString(amount), faction.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYDEPOSIT_DEPOSITED.toString(), context.fPlayer.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/econ/CmdMoneyTransferFf.java b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferFf.java index 9da896b5..14568ac0 100644 --- a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferFf.java +++ b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferFf.java @@ -16,39 +16,39 @@ 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.requirements = new CommandRequirements.Builder(Permission.MONEY_F2F).build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MONEY_F2F).build(); + } - @Override - public void perform(CommandContext context) { - double amount = context.argAsDouble(0, 0d); - EconomyParticipator from = context.argAsFaction(1); - if (from == null) { - return; - } - EconomyParticipator to = context.argAsFaction(2); - if (to == null) { - return; - } + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator from = context.argAsFaction(1); + if (from == null) { + return; + } + EconomyParticipator to = context.argAsFaction(2); + if (to == null) { + return; + } - boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); + boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); - if (success && Conf.logMoneyTransactions) { - String name = context.sender instanceof Player ? context.fPlayer.getName() : context.sender.getName(); - FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYTRANSFERFF_TRANSFER.toString(), name, Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + String name = context.sender instanceof Player ? context.fPlayer.getName() : context.sender.getName(); + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().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; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferFp.java b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferFp.java index 2eac623b..494bccf5 100644 --- a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferFp.java +++ b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferFp.java @@ -13,38 +13,38 @@ 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.requirements = new CommandRequirements.Builder(Permission.MONEY_F2P).build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MONEY_F2P).build(); + } - @Override - public void perform(CommandContext context) { - double amount = context.argAsDouble(0, 0d); - EconomyParticipator from = context.argAsFaction(1); - if (from == null) { - return; - } - EconomyParticipator to = context.argAsBestFPlayerMatch(2); - if (to == null) { - return; - } + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator from = context.argAsFaction(1); + if (from == null) { + return; + } + EconomyParticipator to = context.argAsBestFPlayerMatch(2); + if (to == null) { + return; + } - boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); + boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); - if (success && Conf.logMoneyTransactions) { - FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYTRANSFERFP_TRANSFER.toString(), context.fPlayer.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYTRANSFERFP_TRANSFER.toString(), context.fPlayer.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/econ/CmdMoneyTransferPf.java b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferPf.java index ab67d6be..26ab044b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferPf.java +++ b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyTransferPf.java @@ -14,37 +14,37 @@ 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.requirements = new CommandRequirements.Builder(Permission.MONEY_P2F).build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MONEY_P2F).build(); + } - @Override - public void perform(CommandContext context) { - double amount = context.argAsDouble(0, 0d); - EconomyParticipator from = context.argAsBestFPlayerMatch(1); - if (from == null) { - return; - } - EconomyParticipator to = context.argAsFaction(2); - if (to == null) { - return; - } + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator from = context.argAsBestFPlayerMatch(1); + if (from == null) { + return; + } + EconomyParticipator to = context.argAsFaction(2); + if (to == null) { + return; + } - boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); + boolean success = Econ.transferMoney(context.fPlayer, from, to, amount); - if (success && Conf.logMoneyTransactions) { - FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYTRANSFERPF_TRANSFER.toString(), context.fPlayer.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYTRANSFERPF_TRANSFER.toString(), context.fPlayer.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/econ/CmdMoneyWithdraw.java b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyWithdraw.java index a3cc0686..1a784ef7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyWithdraw.java +++ b/src/main/java/com/massivecraft/factions/cmd/econ/CmdMoneyWithdraw.java @@ -17,42 +17,42 @@ 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.requirements = new CommandRequirements.Builder(Permission.MONEY_F2P) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MONEY_F2P) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - double amount = context.argAsDouble(0, 0d); - EconomyParticipator faction = context.argAsFaction(1, context.faction); - if (faction == null) { - return; - } + @Override + public void perform(CommandContext context) { + double amount = context.argAsDouble(0, 0d); + EconomyParticipator faction = context.argAsFaction(1, context.faction); + if (faction == null) { + return; + } - Access access = context.faction.getAccess(context.fPlayer, PermissableAction.WITHDRAW); - if (context.fPlayer.getRole() != Role.LEADER) { - if (access == Access.DENY) { - context.msg(TL.GENERIC_NOPERMISSION, "withdraw", "withdraw money from the bank"); - return; - } - } - boolean success = Econ.transferMoney(context.fPlayer, faction, context.fPlayer, amount); + Access access = context.faction.getAccess(context.fPlayer, PermissableAction.WITHDRAW); + if (context.fPlayer.getRole() != Role.LEADER) { + if (access == Access.DENY) { + context.msg(TL.GENERIC_NOPERMISSION, "withdraw", "withdraw money from the bank"); + return; + } + } + boolean success = Econ.transferMoney(context.fPlayer, faction, context.fPlayer, amount); - if (success && Conf.logMoneyTransactions) { - FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYWITHDRAW_WITHDRAW.toString(), context.fPlayer.getName(), Econ.moneyString(amount), faction.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + FactionsPlugin.getInstance().log(ChatColor.stripColor(FactionsPlugin.getInstance().txt.parse(TL.COMMAND_MONEYWITHDRAW_WITHDRAW.toString(), context.fPlayer.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/grace/CmdGrace.java b/src/main/java/com/massivecraft/factions/cmd/grace/CmdGrace.java index d64a456e..0a9b1e22 100644 --- a/src/main/java/com/massivecraft/factions/cmd/grace/CmdGrace.java +++ b/src/main/java/com/massivecraft/factions/cmd/grace/CmdGrace.java @@ -9,25 +9,25 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdGrace extends FCommand { - public CmdGrace() { - super(); - this.aliases.add("grace"); + public CmdGrace() { + super(); + this.aliases.add("grace"); - this.requirements = new CommandRequirements.Builder(Permission.GRACE) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.GRACE) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Conf.gracePeriod = !Conf.gracePeriod; - context.msg(TL.COMMAND_GRACE_TOGGLE, Conf.gracePeriod ? TL.GENERIC_ENABLED : TL.GENERIC_DISABLED); - } + @Override + public void perform(CommandContext context) { + Conf.gracePeriod = !Conf.gracePeriod; + context.msg(TL.COMMAND_GRACE_TOGGLE, Conf.gracePeriod ? TL.GENERIC_ENABLED : TL.GENERIC_DISABLED); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_GRACE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_GRACE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/logout/CmdLogout.java b/src/main/java/com/massivecraft/factions/cmd/logout/CmdLogout.java index e1ed15c4..f9553b86 100644 --- a/src/main/java/com/massivecraft/factions/cmd/logout/CmdLogout.java +++ b/src/main/java/com/massivecraft/factions/cmd/logout/CmdLogout.java @@ -9,30 +9,30 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdLogout extends FCommand { - public CmdLogout() { - super(); - this.aliases.add("logout"); + public CmdLogout() { + super(); + this.aliases.add("logout"); - this.requirements = new CommandRequirements.Builder(Permission.LOGOUT) - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.LOGOUT) + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - LogoutHandler handler = LogoutHandler.getByName(context.player.getName()); + @Override + public void perform(CommandContext context) { + LogoutHandler handler = LogoutHandler.getByName(context.player.getName()); - if (handler.isLogoutActive(context.player)) { - context.msg(TL.COMMAND_LOGOUT_ACTIVE); - return; - } + if (handler.isLogoutActive(context.player)) { + context.msg(TL.COMMAND_LOGOUT_ACTIVE); + return; + } - handler.applyLogoutCooldown(context.player); - context.msg(TL.COMMAND_LOGOUT_LOGGING, Conf.logoutCooldown); - } + handler.applyLogoutCooldown(context.player); + context.msg(TL.COMMAND_LOGOUT_LOGGING, Conf.logoutCooldown); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_LOGOUT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LOGOUT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/logout/LogoutHandler.java b/src/main/java/com/massivecraft/factions/cmd/logout/LogoutHandler.java index 0596e2c6..02989213 100644 --- a/src/main/java/com/massivecraft/factions/cmd/logout/LogoutHandler.java +++ b/src/main/java/com/massivecraft/factions/cmd/logout/LogoutHandler.java @@ -13,37 +13,37 @@ import java.util.UUID; public class LogoutHandler { - public static Map factionDatas = new HashMap<>(); - private Map logoutCooldown = new HashMap<>(); - private String name; + public static Map factionDatas = new HashMap<>(); + private Map logoutCooldown = new HashMap<>(); + private String name; - public LogoutHandler(String name) { - this.name = name; - factionDatas.put(name, this); - } + public LogoutHandler(String name) { + this.name = name; + factionDatas.put(name, this); + } - public static LogoutHandler getByName(String name) { - LogoutHandler logoutHandler = factionDatas.get(name); - return logoutHandler == null ? new LogoutHandler(name) : factionDatas.get(name); - } + public static LogoutHandler getByName(String name) { + LogoutHandler logoutHandler = factionDatas.get(name); + return logoutHandler == null ? new LogoutHandler(name) : factionDatas.get(name); + } - public boolean isLogoutActive(Player player) { - return logoutCooldown.containsKey(player.getUniqueId()) && System.currentTimeMillis() < logoutCooldown.get(player.getUniqueId()); - } + public boolean isLogoutActive(Player player) { + return logoutCooldown.containsKey(player.getUniqueId()) && System.currentTimeMillis() < logoutCooldown.get(player.getUniqueId()); + } - public void cancelLogout(Player player) { - logoutCooldown.remove(player.getUniqueId()); - } + public void cancelLogout(Player player) { + logoutCooldown.remove(player.getUniqueId()); + } - public void applyLogoutCooldown(Player player) { - logoutCooldown.put(player.getUniqueId(), System.currentTimeMillis() + (30 * 1000)); + public void applyLogoutCooldown(Player player) { + logoutCooldown.put(player.getUniqueId(), System.currentTimeMillis() + (30 * 1000)); - Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> { - if (isLogoutActive(player)) { - player.setMetadata("Logout", new FixedMetadataValue(FactionsPlugin.getInstance(), true)); - player.kickPlayer(String.valueOf(TL.COMMAND_LOGOUT_KICK_MESSAGE)); - cancelLogout(player); - } - }, Conf.logoutCooldown * 20L); - } + Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> { + if (isLogoutActive(player)) { + player.setMetadata("Logout", new FixedMetadataValue(FactionsPlugin.getInstance(), true)); + player.kickPlayer(String.valueOf(TL.COMMAND_LOGOUT_KICK_MESSAGE)); + cancelLogout(player); + } + }, Conf.logoutCooldown * 20L); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/points/CmdPoints.java b/src/main/java/com/massivecraft/factions/cmd/points/CmdPoints.java index 762a06d8..06617699 100644 --- a/src/main/java/com/massivecraft/factions/cmd/points/CmdPoints.java +++ b/src/main/java/com/massivecraft/factions/cmd/points/CmdPoints.java @@ -9,39 +9,39 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPoints extends FCommand { - public CmdPointsRemove cmdPointsRemove = new CmdPointsRemove(); - public CmdPointsSet cmdPointsSet = new CmdPointsSet(); - public CmdPointsAdd cmdPointsAdd = new CmdPointsAdd(); + public CmdPointsRemove cmdPointsRemove = new CmdPointsRemove(); + public CmdPointsSet cmdPointsSet = new CmdPointsSet(); + public CmdPointsAdd cmdPointsAdd = new CmdPointsAdd(); - public CmdPoints() { - super(); - this.aliases.add("points"); + public CmdPoints() { + super(); + this.aliases.add("points"); - this.requirements = new CommandRequirements.Builder(Permission.POINTS) - .playerOnly() - .build(); + this.requirements = new CommandRequirements.Builder(Permission.POINTS) + .playerOnly() + .build(); - this.addSubCommand(this.cmdPointsAdd); - this.addSubCommand(this.cmdPointsRemove); - this.addSubCommand(this.cmdPointsSet); - } + this.addSubCommand(this.cmdPointsAdd); + this.addSubCommand(this.cmdPointsRemove); + this.addSubCommand(this.cmdPointsSet); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled", true)) { - context.msg(TL.GENERIC_DISABLED); - return; - } - context.commandChain.add(this); - FactionsPlugin.getInstance().cmdAutoHelp.execute(context); - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled", true)) { + context.msg(TL.GENERIC_DISABLED); + return; + } + context.commandChain.add(this); + FactionsPlugin.getInstance().cmdAutoHelp.execute(context); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_POINTS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_POINTS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsAdd.java b/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsAdd.java index f1964ae3..84cd05e9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsAdd.java +++ b/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsAdd.java @@ -11,49 +11,49 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPointsAdd extends FCommand { - public CmdPointsAdd() { - super(); - this.aliases.add("add"); + public CmdPointsAdd() { + super(); + this.aliases.add("add"); - this.requiredArgs.add("faction/player"); - this.requiredArgs.add("# of points"); + this.requiredArgs.add("faction/player"); + this.requiredArgs.add("# of points"); - this.requirements = new CommandRequirements.Builder(Permission.ADDPOINTS) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.ADDPOINTS) + .build(); + } - @Override - public void perform(CommandContext context) { - Faction faction = Factions.getInstance().getByTag(context.args.get(0)); + @Override + public void perform(CommandContext context) { + Faction faction = Factions.getInstance().getByTag(context.args.get(0)); - if (faction == null) { - FPlayer fPlayer = context.argAsFPlayer(0); - if (fPlayer != null) { - faction = fPlayer.getFaction(); - } - } + if (faction == null) { + FPlayer fPlayer = context.argAsFPlayer(0); + if (fPlayer != null) { + faction = fPlayer.getFaction(); + } + } - if (faction == null || faction.isWilderness()) { - context.msg(TL.COMMAND_POINTS_FAILURE.toString().replace("{faction}", context.args.get(0))); - return; - } - if (context.argAsInt(1) <= 0) { - context.msg(TL.COMMAND_POINTS_INSUFFICIENT); - return; - } + if (faction == null || faction.isWilderness()) { + context.msg(TL.COMMAND_POINTS_FAILURE.toString().replace("{faction}", context.args.get(0))); + return; + } + if (context.argAsInt(1) <= 0) { + context.msg(TL.COMMAND_POINTS_INSUFFICIENT); + return; + } - faction.setPoints(faction.getPoints() + context.argAsInt(1)); + faction.setPoints(faction.getPoints() + context.argAsInt(1)); - context.msg(TL.COMMAND_POINTS_SUCCESSFUL, context.argAsInt(1), faction.getTag(), faction.getPoints()); - } + context.msg(TL.COMMAND_POINTS_SUCCESSFUL, context.argAsInt(1), faction.getTag(), faction.getPoints()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_ADDPOINTS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ADDPOINTS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsRemove.java b/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsRemove.java index 6320a256..54f41ab2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsRemove.java +++ b/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsRemove.java @@ -11,48 +11,48 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPointsRemove extends FCommand { - public CmdPointsRemove() { - super(); - this.aliases.add("remove"); + public CmdPointsRemove() { + super(); + this.aliases.add("remove"); - this.requiredArgs.add("faction/player"); - this.requiredArgs.add("# of points"); + this.requiredArgs.add("faction/player"); + this.requiredArgs.add("# of points"); - this.requirements = new CommandRequirements.Builder(Permission.REMOVEPOINTS) - .build(); + this.requirements = new CommandRequirements.Builder(Permission.REMOVEPOINTS) + .build(); - } + } - @Override - public void perform(CommandContext context) { - Faction faction = Factions.getInstance().getByTag(context.args.get(0)); + @Override + public void perform(CommandContext context) { + Faction faction = Factions.getInstance().getByTag(context.args.get(0)); - FPlayer fPlayer = context.argAsFPlayer(0); - if (fPlayer != null) { - faction = fPlayer.getFaction(); - } + FPlayer fPlayer = context.argAsFPlayer(0); + if (fPlayer != null) { + faction = fPlayer.getFaction(); + } - if (faction == null || faction.isWilderness()) { - context.msg(TL.COMMAND_POINTS_FAILURE.toString().replace("{faction}", context.args.get(0))); - return; - } + if (faction == null || faction.isWilderness()) { + context.msg(TL.COMMAND_POINTS_FAILURE.toString().replace("{faction}", context.args.get(0))); + return; + } - if (context.argAsInt(1) <= 0) { - context.msg(TL.COMMAND_POINTS_INSUFFICIENT); - return; - } + if (context.argAsInt(1) <= 0) { + context.msg(TL.COMMAND_POINTS_INSUFFICIENT); + return; + } - faction.setPoints(faction.getPoints() - context.argAsInt(1)); - context.msg(TL.COMMAND_REMOVEPOINTS_SUCCESSFUL, context.argAsInt(1), faction.getTag(), faction.getPoints()); - } + faction.setPoints(faction.getPoints() - context.argAsInt(1)); + context.msg(TL.COMMAND_REMOVEPOINTS_SUCCESSFUL, context.argAsInt(1), faction.getTag(), faction.getPoints()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_REMOVEPOINTS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_REMOVEPOINTS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsSet.java b/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsSet.java index e3fde0f5..b0ca79ae 100644 --- a/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsSet.java +++ b/src/main/java/com/massivecraft/factions/cmd/points/CmdPointsSet.java @@ -11,47 +11,47 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPointsSet extends FCommand { - public CmdPointsSet() { - super(); - this.aliases.add("set"); + public CmdPointsSet() { + super(); + this.aliases.add("set"); - this.requiredArgs.add("faction/player"); - this.requiredArgs.add("# of points"); + this.requiredArgs.add("faction/player"); + this.requiredArgs.add("# of points"); - this.requirements = new CommandRequirements.Builder(Permission.SETPOINTS) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.SETPOINTS) + .build(); + } - @Override - public void perform(CommandContext context) { - Faction faction = Factions.getInstance().getByTag(context.args.get(0)); + @Override + public void perform(CommandContext context) { + Faction faction = Factions.getInstance().getByTag(context.args.get(0)); - FPlayer fPlayer = context.argAsFPlayer(0); - if (fPlayer != null) { - faction = fPlayer.getFaction(); - } + FPlayer fPlayer = context.argAsFPlayer(0); + if (fPlayer != null) { + faction = fPlayer.getFaction(); + } - if (faction == null || faction.isWilderness()) { - context.msg(TL.COMMAND_POINTS_FAILURE.toString().replace("{faction}", context.args.get(0))); - return; - } + if (faction == null || faction.isWilderness()) { + context.msg(TL.COMMAND_POINTS_FAILURE.toString().replace("{faction}", context.args.get(0))); + return; + } - if (context.argAsInt(1) < 0) { - context.msg(TL.COMMAND_POINTS_INSUFFICIENT); - return; - } + if (context.argAsInt(1) < 0) { + context.msg(TL.COMMAND_POINTS_INSUFFICIENT); + return; + } - faction.setPoints(context.argAsInt(1)); - context.msg(TL.COMMAND_SETPOINTS_SUCCESSFUL, context.argAsInt(1), faction.getTag(), faction.getPoints()); - } + faction.setPoints(context.argAsInt(1)); + context.msg(TL.COMMAND_SETPOINTS_SUCCESSFUL, context.argAsInt(1), faction.getTag(), faction.getPoints()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SETPOINTS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETPOINTS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationAlly.java b/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationAlly.java index 921c211c..530ca0e9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationAlly.java +++ b/src/main/java/com/massivecraft/factions/cmd/relational/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/relational/CmdRelationEnemy.java b/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationEnemy.java index 7b3ab4b2..62780821 100644 --- a/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationEnemy.java +++ b/src/main/java/com/massivecraft/factions/cmd/relational/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/relational/CmdRelationNeutral.java b/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationNeutral.java index d5def765..f4c5cdbd 100644 --- a/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationNeutral.java +++ b/src/main/java/com/massivecraft/factions/cmd/relational/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/relational/CmdRelationTruce.java b/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationTruce.java index 88149013..4fabb5d2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/relational/CmdRelationTruce.java +++ b/src/main/java/com/massivecraft/factions/cmd/relational/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/relational/FRelationCommand.java b/src/main/java/com/massivecraft/factions/cmd/relational/FRelationCommand.java index 4e5e21a3..400c265d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/relational/FRelationCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/relational/FRelationCommand.java @@ -18,111 +18,111 @@ import org.bukkit.ChatColor; public abstract class FRelationCommand extends FCommand { - public Relation targetRelation; + public Relation targetRelation; - public FRelationCommand() { - super(); - this.requiredArgs.add("faction tag"); + public FRelationCommand() { + super(); + this.requiredArgs.add("faction tag"); - this.requirements = new CommandRequirements.Builder(Permission.RELATION) - .withRole(Role.MODERATOR) - .playerOnly() - .memberOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.RELATION) + .withRole(Role.MODERATOR) + .playerOnly() + .memberOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - Faction them = context.argAsFaction(0); - if (them == null) { - return; - } + @Override + public void perform(CommandContext context) { + Faction them = context.argAsFaction(0); + if (them == null) { + return; + } - if (!them.isNormal()) { - context.msg(TL.COMMAND_RELATIONS_ALLTHENOPE); - return; - } + if (!them.isNormal()) { + context.msg(TL.COMMAND_RELATIONS_ALLTHENOPE); + return; + } - if (them == context.faction) { - context.msg(TL.COMMAND_RELATIONS_MORENOPE); - return; - } + if (them == context.faction) { + context.msg(TL.COMMAND_RELATIONS_MORENOPE); + return; + } - if (context.faction.getRelationWish(them) == targetRelation) { - context.msg(TL.COMMAND_RELATIONS_ALREADYINRELATIONSHIP, them.getTag()); - return; - } + if (context.faction.getRelationWish(them) == targetRelation) { + context.msg(TL.COMMAND_RELATIONS_ALREADYINRELATIONSHIP, them.getTag()); + return; + } - if (hasMaxRelations(context.faction, them, targetRelation)) { - // We message them down there with the count. - return; - } - Relation oldRelation = context.faction.getRelationTo(them, true); - FactionRelationWishEvent wishEvent = new FactionRelationWishEvent(context.fPlayer, context.faction, them, oldRelation, targetRelation); - Bukkit.getPluginManager().callEvent(wishEvent); - if (wishEvent.isCancelled()) { - return; - } + if (hasMaxRelations(context.faction, them, targetRelation)) { + // We message them down there with the count. + return; + } + Relation oldRelation = context.faction.getRelationTo(them, true); + FactionRelationWishEvent wishEvent = new FactionRelationWishEvent(context.fPlayer, context.faction, 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 (!context.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 (!context.payForCommand(targetRelation.getRelationCost(), TL.COMMAND_RELATIONS_TOMARRY, TL.COMMAND_RELATIONS_FORMARRY)) { + return; + } - // try to set the new relation - context.faction.setRelationWish(them, targetRelation); - Relation currentRelation = context.faction.getRelationTo(them, true); - ChatColor currentRelationColor = currentRelation.getColor(); + // try to set the new relation + context.faction.setRelationWish(them, targetRelation); + Relation currentRelation = context.faction.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(context.faction, 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(context.faction, them, oldRelation, currentRelation); + Bukkit.getServer().getPluginManager().callEvent(relationEvent); - them.msg(TL.COMMAND_RELATIONS_MUTUAL, currentRelationColor + targetRelation.getTranslation(), currentRelationColor + context.faction.getTag()); - context.faction.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 + context.faction.getTag(), targetRelation.getColor() + targetRelation.getTranslation()); - them.msg(TL.COMMAND_RELATIONS_PROPOSAL_2, Conf.baseCommandAliases.get(0), targetRelation, context.faction.getTag()); - context.faction.msg(TL.COMMAND_RELATIONS_PROPOSAL_SENT, currentRelationColor + them.getTag(), "" + targetRelation.getColor() + targetRelation); - } + them.msg(TL.COMMAND_RELATIONS_MUTUAL, currentRelationColor + targetRelation.getTranslation(), currentRelationColor + context.faction.getTag()); + context.faction.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 + context.faction.getTag(), targetRelation.getColor() + targetRelation.getTranslation()); + them.msg(TL.COMMAND_RELATIONS_PROPOSAL_2, Conf.baseCommandAliases.get(0), targetRelation, context.faction.getTag()); + context.faction.msg(TL.COMMAND_RELATIONS_PROPOSAL_SENT, currentRelationColor + them.getTag(), "" + targetRelation.getColor() + targetRelation); + } - if (!targetRelation.isNeutral() && them.isPeaceful()) { - them.msg(TL.COMMAND_RELATIONS_PEACEFUL); - context.faction.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); - } + if (!targetRelation.isNeutral() && them.isPeaceful()) { + them.msg(TL.COMMAND_RELATIONS_PEACEFUL); + context.faction.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); + } - if (!targetRelation.isNeutral() && context.faction.isPeaceful()) { - them.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); - context.faction.msg(TL.COMMAND_RELATIONS_PEACEFUL); - } + if (!targetRelation.isNeutral() && context.faction.isPeaceful()) { + them.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); + context.faction.msg(TL.COMMAND_RELATIONS_PEACEFUL); + } - FTeamWrapper.updatePrefixes(context.faction); - FTeamWrapper.updatePrefixes(them); - } + FTeamWrapper.updatePrefixes(context.faction); + FTeamWrapper.updatePrefixes(them); + } - private boolean hasMaxRelations(Faction us, Faction them, Relation targetRelation) { - int max = FactionsPlugin.getInstance().getConfig().getInt("max-relations." + targetRelation.toString(), -1); - if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", false)) { - if (max != -1) { - if (us.getRelationCount(targetRelation) >= max) { - us.msg(TL.COMMAND_RELATIONS_EXCEEDS_ME, max, targetRelation.getPluralTranslation()); - return true; - } - if (them.getRelationCount(targetRelation) >= max) { - them.msg(TL.COMMAND_RELATIONS_EXCEEDS_THEY, max, targetRelation.getPluralTranslation()); - return true; - } - } - } - return false; - } + private boolean hasMaxRelations(Faction us, Faction them, Relation targetRelation) { + int max = FactionsPlugin.getInstance().getConfig().getInt("max-relations." + targetRelation.toString(), -1); + if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", false)) { + if (max != -1) { + if (us.getRelationCount(targetRelation) >= max) { + us.msg(TL.COMMAND_RELATIONS_EXCEEDS_ME, max, targetRelation.getPluralTranslation()); + return true; + } + if (them.getRelationCount(targetRelation) >= max) { + them.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/cmd/roles/CmdDemote.java b/src/main/java/com/massivecraft/factions/cmd/roles/CmdDemote.java index 56efffd6..2903b435 100644 --- a/src/main/java/com/massivecraft/factions/cmd/roles/CmdDemote.java +++ b/src/main/java/com/massivecraft/factions/cmd/roles/CmdDemote.java @@ -2,8 +2,8 @@ package com.massivecraft.factions.cmd.roles; 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/roles/CmdPromote.java b/src/main/java/com/massivecraft/factions/cmd/roles/CmdPromote.java index e1a0c32d..051c3e8f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/roles/CmdPromote.java +++ b/src/main/java/com/massivecraft/factions/cmd/roles/CmdPromote.java @@ -2,9 +2,9 @@ package com.massivecraft.factions.cmd.roles; 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/roles/FPromoteCommand.java b/src/main/java/com/massivecraft/factions/cmd/roles/FPromoteCommand.java index 360f2d3c..82beaa72 100644 --- a/src/main/java/com/massivecraft/factions/cmd/roles/FPromoteCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/roles/FPromoteCommand.java @@ -11,78 +11,78 @@ import com.massivecraft.factions.zcore.util.TL; public class FPromoteCommand extends FCommand { - public int relative = 0; + public int relative = 0; - public FPromoteCommand() { - super(); - this.requiredArgs.add("player"); + public FPromoteCommand() { + super(); + this.requiredArgs.add("player"); - this.requirements = new CommandRequirements.Builder(Permission.PROMOTE) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.PROMOTE) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.PROMOTE) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.PROMOTE) + .build(); + } - @Override - public void perform(CommandContext context) { - FPlayer target = context.argAsBestFPlayerMatch(0); - if (target == null) { - context.msg(TL.GENERIC_NOPLAYERFOUND, context.argAsString(0)); - return; - } + @Override + public void perform(CommandContext context) { + FPlayer target = context.argAsBestFPlayerMatch(0); + if (target == null) { + context.msg(TL.GENERIC_NOPLAYERFOUND, context.argAsString(0)); + return; + } - if (!target.getFaction().equals(context.faction)) { - context.msg(TL.COMMAND_PROMOTE_WRONGFACTION, target.getName()); - return; - } + if (!target.getFaction().equals(context.faction)) { + context.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 (!context.fPlayer.isAdminBypassing()) { - if (target == context.fPlayer) { - context.msg(TL.COMMAND_PROMOTE_NOTSELF); - return; - } - // Don't allow people to manage role of their same rank - if (context.fPlayer.getRole() == current) { - context.msg(TL.COMMAND_PROMOTE_NOT_SAME); - return; - } - // Don't allow people to promote people to their same or higher rank. - if (context.fPlayer.getRole().value <= promotion.value) { - context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); - return; - } - } + // Now it ain't that messy + if (!context.fPlayer.isAdminBypassing()) { + if (target == context.fPlayer) { + context.msg(TL.COMMAND_PROMOTE_NOTSELF); + return; + } + // Don't allow people to manage role of their same rank + if (context.fPlayer.getRole() == current) { + context.msg(TL.COMMAND_PROMOTE_NOT_SAME); + return; + } + // Don't allow people to promote people to their same or higher rank. + if (context.fPlayer.getRole().value <= promotion.value) { + context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); + return; + } + } - if (promotion == null) { - context.msg(TL.COMMAND_PROMOTE_NOTTHATPLAYER); - return; - } + if (promotion == null) { + context.msg(TL.COMMAND_PROMOTE_NOTTHATPLAYER); + return; + } - // Don't allow people to promote people to their same or higher rnak. - if (context.fPlayer.getRole().value <= promotion.value) { - context.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); - return; - } + // Don't allow people to promote people to their same or higher rnak. + if (context.fPlayer.getRole().value <= promotion.value) { + context.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); + } - context.msg(TL.COMMAND_PROMOTE_SUCCESS, action, target.getName(), promotion.nicename); - } + context.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/tnt/CmdTnt.java b/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTnt.java index cbb091e5..ef808464 100644 --- a/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTnt.java +++ b/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTnt.java @@ -14,158 +14,158 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class CmdTnt extends FCommand { - public CmdTnt() { - super(); - this.aliases.add("tnt"); - this.optionalArgs.put("add/take", ""); - this.optionalArgs.put("amount", "number"); + public CmdTnt() { + super(); + this.aliases.add("tnt"); + this.optionalArgs.put("add/take", ""); + this.optionalArgs.put("amount", "number"); - this.requirements = new CommandRequirements.Builder(Permission.TNT) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.TNTBANK) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.TNT) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.TNTBANK) + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("ftnt.Enabled")) { - context.msg(TL.COMMAND_TNT_DISABLED_MSG); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("ftnt.Enabled")) { + context.msg(TL.COMMAND_TNT_DISABLED_MSG); + return; + } - if (context.args.size() == 2) { - if (context.args.get(0).equalsIgnoreCase("add") || context.args.get(0).equalsIgnoreCase("a")) { - try { - Integer.parseInt(context.args.get(1)); - } catch (NumberFormatException e) { - context.msg(TL.COMMAND_TNT_INVALID_NUM); - return; - } - int amount = Integer.parseInt(context.args.get(1)); - if (amount < 0) { - context.msg(TL.COMMAND_TNT_POSITIVE); - return; - } - Inventory inv = context.player.getInventory(); - int invTnt = 0; - for (int i = 0; i <= inv.getSize(); i++) { - if (inv.getItem(i) == null) { - continue; + if (context.args.size() == 2) { + if (context.args.get(0).equalsIgnoreCase("add") || context.args.get(0).equalsIgnoreCase("a")) { + try { + Integer.parseInt(context.args.get(1)); + } catch (NumberFormatException e) { + context.msg(TL.COMMAND_TNT_INVALID_NUM); + return; } - if (inv.getItem(i).getType() == Material.TNT) { - invTnt += inv.getItem(i).getAmount(); + int amount = Integer.parseInt(context.args.get(1)); + if (amount < 0) { + context.msg(TL.COMMAND_TNT_POSITIVE); + return; } - } - if (amount > invTnt) { - context.msg(TL.COMMAND_TNT_DEPOSIT_NOTENOUGH); + Inventory inv = context.player.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) { + context.msg(TL.COMMAND_TNT_DEPOSIT_NOTENOUGH); + return; + } + ItemStack tnt = new ItemStack(Material.TNT, amount); + if (context.faction.getTnt() + amount > FactionsPlugin.getInstance().getConfig().getInt("ftnt.Bank-Limit")) { + context.msg(TL.COMMAND_TNT_EXCEEDLIMIT); + return; + } + removeFromInventory(context.player.getInventory(), tnt); + context.player.updateInventory(); + + context.faction.addTnt(amount); + context.msg(TL.COMMAND_TNT_DEPOSIT_SUCCESS); + context.fPlayer.sendMessage(FactionsPlugin.getInstance().color(TL.COMMAND_TNT_AMOUNT.toString().replace("{amount}", context.fPlayer.getFaction().getTnt() + ""))); return; - } - ItemStack tnt = new ItemStack(Material.TNT, amount); - if (context.faction.getTnt() + amount > FactionsPlugin.getInstance().getConfig().getInt("ftnt.Bank-Limit")) { - context.msg(TL.COMMAND_TNT_EXCEEDLIMIT); - return; - } - removeFromInventory(context.player.getInventory(), tnt); - context.player.updateInventory(); - context.faction.addTnt(amount); - context.msg(TL.COMMAND_TNT_DEPOSIT_SUCCESS); - context.fPlayer.sendMessage(FactionsPlugin.getInstance().color(TL.COMMAND_TNT_AMOUNT.toString().replace("{amount}", context.fPlayer.getFaction().getTnt() + ""))); - return; + } + if (context.args.get(0).equalsIgnoreCase("take") || context.args.get(0).equalsIgnoreCase("t")) { + try { + Integer.parseInt(context.args.get(1)); + } catch (NumberFormatException e) { + context.msg(TL.COMMAND_TNT_INVALID_NUM); + return; + } + int amount = Integer.parseInt(context.args.get(1)); + if (amount < 0) { + context.msg(TL.COMMAND_TNT_POSITIVE); + return; + } + if (context.faction.getTnt() < amount) { + context.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); + return; + } + int fullStacks = Math.round(amount / 64); + int remainderAmt = amount - (fullStacks * 64); + if ((remainderAmt == 0 && !hasAvaliableSlot(context.player, fullStacks))) { + context.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE); + return; + } + if (!hasAvaliableSlot(context.player, fullStacks + 1)) { + context.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE); + return; + } - } - if (context.args.get(0).equalsIgnoreCase("take") || context.args.get(0).equalsIgnoreCase("t")) { - try { - Integer.parseInt(context.args.get(1)); - } catch (NumberFormatException e) { - context.msg(TL.COMMAND_TNT_INVALID_NUM); - return; - } - int amount = Integer.parseInt(context.args.get(1)); - if (amount < 0) { - context.msg(TL.COMMAND_TNT_POSITIVE); - return; - } - if (context.faction.getTnt() < amount) { - context.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); - return; - } - int fullStacks = Math.round(amount / 64); - int remainderAmt = amount - (fullStacks * 64); - if ((remainderAmt == 0 && !hasAvaliableSlot(context.player, fullStacks))) { - context.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE); - return; - } - if (!hasAvaliableSlot(context.player, fullStacks + 1)) { - context.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE); - return; - } + for (int i = 0; i <= fullStacks - 1; i++) + context.player.getInventory().addItem(new ItemStack(XMaterial.TNT.parseMaterial(), 64)); + if (remainderAmt != 0) + context.player.getInventory().addItem(new ItemStack(XMaterial.TNT.parseMaterial(), remainderAmt)); - for (int i = 0; i <= fullStacks - 1; i++) - context.player.getInventory().addItem(new ItemStack(XMaterial.TNT.parseMaterial(), 64)); - if (remainderAmt != 0) - context.player.getInventory().addItem(new ItemStack(XMaterial.TNT.parseMaterial(), remainderAmt)); - - context.faction.takeTnt(amount); - context.player.updateInventory(); - context.msg(TL.COMMAND_TNT_WIDTHDRAW_SUCCESS); - } - } else if (context.args.size() == 1) { - context.msg(TL.GENERIC_ARGS_TOOFEW); - context.msg(context.args.get(0).equalsIgnoreCase("take") || context.args.get(0).equalsIgnoreCase("t") ? TL.COMMAND_TNT_TAKE_DESCRIPTION : TL.COMMAND_TNT_ADD_DESCRIPTION); - } - context.sendMessage(TL.COMMAND_TNT_AMOUNT.toString().replace("{amount}", context.faction.getTnt() + "")); - } + context.faction.takeTnt(amount); + context.player.updateInventory(); + context.msg(TL.COMMAND_TNT_WIDTHDRAW_SUCCESS); + } + } else if (context.args.size() == 1) { + context.msg(TL.GENERIC_ARGS_TOOFEW); + context.msg(context.args.get(0).equalsIgnoreCase("take") || context.args.get(0).equalsIgnoreCase("t") ? TL.COMMAND_TNT_TAKE_DESCRIPTION : TL.COMMAND_TNT_ADD_DESCRIPTION); + } + context.sendMessage(TL.COMMAND_TNT_AMOUNT.toString().replace("{amount}", context.faction.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/tnt/CmdTntFill.java b/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTntFill.java index edd9f749..a6e7a7bd 100644 --- a/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTntFill.java +++ b/src/main/java/com/massivecraft/factions/cmd/tnt/CmdTntFill.java @@ -24,208 +24,208 @@ import java.util.List; 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.requirements = new CommandRequirements.Builder(Permission.TNTFILL) - .playerOnly() - .memberOnly() - .withAction(PermissableAction.TNTFILL) - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.TNTFILL) + .playerOnly() + .memberOnly() + .withAction(PermissableAction.TNTFILL) + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("Tntfill.enabled")) { - context.msg(TL.GENERIC_DISABLED); - return; - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("Tntfill.enabled")) { + context.msg(TL.GENERIC_DISABLED); + return; + } - // Don't do I/O unless necessary - try { - Integer.parseInt(context.args.get(0)); - Integer.parseInt(context.args.get(1)); - } catch (NumberFormatException e) { - context.msg(TL.COMMAND_TNT_INVALID_NUM); - return; - } + // Don't do I/O unless necessary + try { + Integer.parseInt(context.args.get(0)); + Integer.parseInt(context.args.get(1)); + } catch (NumberFormatException e) { + context.msg(TL.COMMAND_TNT_INVALID_NUM); + return; + } - context.msg(TL.COMMAND_TNTFILL_HEADER); - int radius = context.argAsInt(0, 0); // We don't know the max yet, so let's not assume. - int amount = context.argAsInt(1, 0); // We don't know the max yet, so let's not assume. + context.msg(TL.COMMAND_TNTFILL_HEADER); + int radius = context.argAsInt(0, 0); // We don't know the max yet, so let's not assume. + int amount = context.argAsInt(1, 0); // We don't know the max yet, so let's not assume. - if (amount < 0) { - context.msg(TL.COMMAND_TNT_POSITIVE); - return; - } - if (radius > FactionsPlugin.getInstance().getConfig().getInt("Tntfill.max-radius")) { - context.msg(TL.COMMAND_TNTFILL_RADIUSMAX.toString().replace("{max}", FactionsPlugin.getInstance().getConfig().getInt("Tntfill.max-radius") + "")); - return; - } - if (amount > FactionsPlugin.getInstance().getConfig().getInt("Tntfill.max-amount")) { - context.msg(TL.COMMAND_TNTFILL_AMOUNTMAX.toString().replace("{max}", FactionsPlugin.getInstance().getConfig().getInt("Tntfill.max-amount") + "")); - return; - } + if (amount < 0) { + context.msg(TL.COMMAND_TNT_POSITIVE); + return; + } + if (radius > FactionsPlugin.getInstance().getConfig().getInt("Tntfill.max-radius")) { + context.msg(TL.COMMAND_TNTFILL_RADIUSMAX.toString().replace("{max}", FactionsPlugin.getInstance().getConfig().getInt("Tntfill.max-radius") + "")); + return; + } + if (amount > FactionsPlugin.getInstance().getConfig().getInt("Tntfill.max-amount")) { + context.msg(TL.COMMAND_TNTFILL_AMOUNTMAX.toString().replace("{max}", FactionsPlugin.getInstance().getConfig().getInt("Tntfill.max-amount") + "")); + return; + } - // How many dispensers are we to fill in? + // How many dispensers are we to fill in? - Location start = context.player.getLocation(); - // Keep it on the stack for CPU saving. - List opDispensers = new ArrayList<>(); + Location start = context.player.getLocation(); + // Keep it on the stack for CPU saving. + List opDispensers = new ArrayList<>(); - Block startBlock = start.getBlock(); - for (int x = -radius; x <= radius; x++) - for (int y = -radius; y <= radius; y++) - for (int z = -radius; z <= radius; z++) { - Block block = startBlock.getRelative(x, y, z); - if (block == null) continue; - BlockState blockState = block.getState(); - if (!(blockState instanceof Dispenser)) continue; - opDispensers.add((Dispenser) blockState); - } - if (opDispensers.isEmpty()) { - context.fPlayer.msg(TL.COMMAND_TNTFILL_NODISPENSERS.toString().replace("{radius}", radius + "")); - return; - } + Block startBlock = start.getBlock(); + for (int x = -radius; x <= radius; x++) + for (int y = -radius; y <= radius; y++) + for (int z = -radius; z <= radius; z++) { + Block block = startBlock.getRelative(x, y, z); + if (block == null) continue; + BlockState blockState = block.getState(); + if (!(blockState instanceof Dispenser)) continue; + opDispensers.add((Dispenser) blockState); + } + if (opDispensers.isEmpty()) { + context.fPlayer.msg(TL.COMMAND_TNTFILL_NODISPENSERS.toString().replace("{radius}", radius + "")); + return; + } - // What's the required amount of resources - int requiredTnt = (opDispensers.size() * amount); + // What's the required amount of resources + int requiredTnt = (opDispensers.size() * amount); - // Do I have enough tnt in my inventory? - int playerTnt = inventoryItemCount(context.player.getInventory(), Material.TNT); - if (playerTnt < requiredTnt) { - // How much TNT will I take from bank? - int getFactionTnt = requiredTnt - playerTnt; + // Do I have enough tnt in my inventory? + int playerTnt = inventoryItemCount(context.player.getInventory(), Material.TNT); + if (playerTnt < requiredTnt) { + // How much TNT will I take from bank? + int getFactionTnt = requiredTnt - playerTnt; - // Do I have enough tnt in bank? - if ((context.faction.getTnt() < getFactionTnt)) { - context.fPlayer.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); - return; - } + // Do I have enough tnt in bank? + if ((context.faction.getTnt() < getFactionTnt)) { + context.fPlayer.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); + return; + } - // Take TNT from the bank. - removeFromBank(context, getFactionTnt); - } - fillDispensers(context.fPlayer, opDispensers, amount); - // Remove used TNT from player inventory. - context.sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", requiredTnt + "").replace("{dispensers}", opDispensers.size() + "")); - } + // Take TNT from the bank. + removeFromBank(context, getFactionTnt); + } + fillDispensers(context.fPlayer, opDispensers, amount); + // Remove used TNT from player inventory. + context.sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", requiredTnt + "").replace("{dispensers}", opDispensers.size() + "")); + } - // Actually fill every dispenser with the precise amount. - private void fillDispensers(FPlayer fPlayer, List dispensers, int count) { - for (Dispenser dispenser : dispensers) { - takeTnt(fPlayer, count); - dispenser.getInventory().addItem(new ItemStack(Material.TNT, count)); - } - } + // Actually fill every dispenser with the precise amount. + private void fillDispensers(FPlayer fPlayer, List dispensers, int count) { + for (Dispenser dispenser : dispensers) { + takeTnt(fPlayer, count); + dispenser.getInventory().addItem(new ItemStack(Material.TNT, count)); + } + } - private void removeFromBank(CommandContext context, int amount) { - try { - Integer.parseInt(context.args.get(1)); - } catch (NumberFormatException e) { - context.fPlayer.msg(TL.COMMAND_TNT_INVALID_NUM.toString()); - return; - } - if (amount < 0) { - context.fPlayer.msg(TL.COMMAND_TNT_POSITIVE.toString()); - return; - } - if (context.faction.getTnt() < amount) { - context.fPlayer.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); - return; - } - int fullStacks = amount / 64; - int remainderAmt = amount % 64; - if ((remainderAmt == 0 && getEmptySlots(context.player) <= fullStacks)) { - context.fPlayer.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); - return; - } - if (getEmptySlots(context.player) + 1 <= fullStacks) { - context.fPlayer.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); - return; - } - ItemStack tnt64 = new ItemStack(Material.TNT, 64); - for (int i = 0; i <= fullStacks - 1; i++) { - context.player.getInventory().addItem(tnt64); - } - if (remainderAmt != 0) { - ItemStack tnt = new ItemStack(Material.TNT, remainderAmt); - context.player.getInventory().addItem(tnt); - } - context.faction.takeTnt(amount); - context.player.updateInventory(); - } + private void removeFromBank(CommandContext context, int amount) { + try { + Integer.parseInt(context.args.get(1)); + } catch (NumberFormatException e) { + context.fPlayer.msg(TL.COMMAND_TNT_INVALID_NUM.toString()); + return; + } + if (amount < 0) { + context.fPlayer.msg(TL.COMMAND_TNT_POSITIVE.toString()); + return; + } + if (context.faction.getTnt() < amount) { + context.fPlayer.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); + return; + } + int fullStacks = amount / 64; + int remainderAmt = amount % 64; + if ((remainderAmt == 0 && getEmptySlots(context.player) <= fullStacks)) { + context.fPlayer.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); + return; + } + if (getEmptySlots(context.player) + 1 <= fullStacks) { + context.fPlayer.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_TNT.toString()); + return; + } + ItemStack tnt64 = new ItemStack(Material.TNT, 64); + for (int i = 0; i <= fullStacks - 1; i++) { + context.player.getInventory().addItem(tnt64); + } + if (remainderAmt != 0) { + ItemStack tnt = new ItemStack(Material.TNT, remainderAmt); + context.player.getInventory().addItem(tnt); + } + context.faction.takeTnt(amount); + context.player.updateInventory(); + } - private void takeTnt(FPlayer fme, int amount) { - Inventory inv = fme.getPlayer().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.toString()); - return; - } - ItemStack tnt = new ItemStack(Material.TNT, amount); - if (fme.getFaction().getTnt() + amount > FactionsPlugin.getInstance().getConfig().getInt("ftnt.Bank-Limit")) { - fme.msg(TL.COMMAND_TNT_EXCEEDLIMIT.toString()); - return; - } - removeFromInventory(fme.getPlayer().getInventory(), tnt); - } + private void takeTnt(FPlayer fme, int amount) { + Inventory inv = fme.getPlayer().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.toString()); + return; + } + ItemStack tnt = new ItemStack(Material.TNT, amount); + if (fme.getFaction().getTnt() + amount > FactionsPlugin.getInstance().getConfig().getInt("ftnt.Bank-Limit")) { + fme.msg(TL.COMMAND_TNT_EXCEEDLIMIT.toString()); + return; + } + removeFromInventory(fme.getPlayer().getInventory(), tnt); + } - // Counts the item type available in the inventory. - private int inventoryItemCount(Inventory inventory, Material mat) { - int count = 0; - HashMap items = inventory.all(mat); - for (int item : items.keySet()) - count += inventory.getItem(item).getAmount(); - return count; - } + // Counts the item type available in the inventory. + private int inventoryItemCount(Inventory inventory, Material mat) { + int count = 0; + HashMap items = inventory.all(mat); + for (int item : items.keySet()) + count += inventory.getItem(item).getAmount(); + return count; + } - private 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); - } + private 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); + } - private 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; - } + private 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; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerEnteredFactionEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerEnteredFactionEvent.java index d22632c1..745fa5c8 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..3a2985eb 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..9fa8b6fe 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/FPlayerRoleChangeEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerRoleChangeEvent.java index 3c4d13b7..c06ae99a 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerRoleChangeEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerRoleChangeEvent.java @@ -12,40 +12,40 @@ import org.bukkit.event.Cancellable; */ public class FPlayerRoleChangeEvent extends FactionPlayerEvent implements Cancellable { - private final Role from; - private boolean cancelled; - private Role to; + private final Role from; + private boolean cancelled; + private Role to; - public FPlayerRoleChangeEvent(Faction faction, FPlayer fPlayer, Role from, Role to) { - super(faction, fPlayer); - this.from = from; - this.to = to; - } + public FPlayerRoleChangeEvent(Faction faction, FPlayer fPlayer, Role from, Role to) { + super(faction, fPlayer); + this.from = from; + this.to = to; + } - public FPlayerRoleChangeEvent(Faction faction, FPlayer fPlayer, Role to) { - this(faction, fPlayer, fPlayer.getRole(), to); - } + public FPlayerRoleChangeEvent(Faction faction, FPlayer fPlayer, Role to) { + this(faction, fPlayer, fPlayer.getRole(), to); + } - @Override - public boolean isCancelled() { - return false; - } + @Override + public boolean isCancelled() { + return false; + } - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } - public Role getFrom() { - return from; - } + public Role getFrom() { + return from; + } - public Role getTo() { - return to; - } + public Role getTo() { + return to; + } - public void setTo(Role to) { - this.to = to; - } + public void setTo(Role to) { + this.to = to; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerStoppedFlying.java b/src/main/java/com/massivecraft/factions/event/FPlayerStoppedFlying.java index f2f283c8..d18ea6f5 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..05b3ef06 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..8d36520d 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..b895d0c8 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..77850675 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..7de95ac6 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..03f67346 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..7929fbec 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..9dafa5e7 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..1bf568f4 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..c9870511 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..6b657275 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..342f418d 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..70cad9e8 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..2300cfd1 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 d499542b..eb7ea2e1 100644 --- a/src/main/java/com/massivecraft/factions/integration/Econ.java +++ b/src/main/java/com/massivecraft/factions/integration/Econ.java @@ -24,425 +24,425 @@ 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) { - FactionsPlugin.getInstance().log(integrationFail + "is not installed."); - return; - } + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { + FactionsPlugin.getInstance().log(integrationFail + "is not installed."); + return; + } - RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); - if (rsp == null) { - FactionsPlugin.getInstance().log(integrationFail + "is not hooked into an economy plugin."); - return; - } - econ = rsp.getProvider(); + RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (rsp == null) { + FactionsPlugin.getInstance().log(integrationFail + "is not hooked into an economy plugin."); + return; + } + econ = rsp.getProvider(); - FactionsPlugin.getInstance().log("Economy integration through Vault plugin successful."); + FactionsPlugin.getInstance().log("Economy integration through Vault plugin successful."); - if (!Conf.econEnabled) { - FactionsPlugin.getInstance().log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); - } + if (!Conf.econEnabled) { + FactionsPlugin.getInstance().log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); + } - //FactionsPlugin.getInstance().cmdBase.cmdHelp.updateHelp(); - } + //FactionsPlugin.getInstance().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(CommandSender to, Faction about) { - if (!shouldBeUsed()) { - FactionsPlugin.getInstance().log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); - return; - } - to.sendMessage(String.format("%s's balance is %s.", about.getTag(), Econ.moneyString(econ.getBalance(about.getAccountId())))); - } + public static void sendBalanceInfo(CommandSender to, Faction about) { + if (!shouldBeUsed()) { + FactionsPlugin.getInstance().log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); + return; + } + to.sendMessage(String.format("%s's balance is %s.", about.getTag(), 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()) { - invoker.msg(TL.ECON_OFF); - return false; - } + public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) { + if (!shouldBeUsed()) { + invoker.msg(TL.ECON_OFF); + 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; + } - // Check if the new balance is over Essential's money cap. - if (Essentials.isOverBalCap(to, econ.getBalance(toAcc) + amount)) { - invoker.msg(TL.ECON_OVER_BAL_CAP, amount); - return false; - } + // Check if the new balance is over Essential's money cap. + if (Essentials.isOverBalCap(to, econ.getBalance(toAcc) + amount)) { + invoker.msg(TL.ECON_OVER_BAL_CAP, amount); + 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 2c189919..85227a8c 100644 --- a/src/main/java/com/massivecraft/factions/integration/Essentials.java +++ b/src/main/java/com/massivecraft/factions/integration/Essentials.java @@ -17,41 +17,41 @@ 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; + } + } - public static boolean isOverBalCap(EconomyParticipator participator, double amount) { - if (essentials == null) { - return false; - } - return amount > essentials.getSettings().getMaxMoney().doubleValue(); - } + public static boolean isOverBalCap(EconomyParticipator participator, double amount) { + if (essentials == null) { + return false; + } + return amount > essentials.getSettings().getMaxMoney().doubleValue(); + } - // 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) { - if (essentials == null) return false; - User user = essentials.getUser(player); - return user != null && user.isVanished(); - } + public static boolean isVanished(Player player) { + if (essentials == null) return false; + User user = essentials.getUser(player); + return user != null && user.isVanished(); + } } diff --git a/src/main/java/com/massivecraft/factions/integration/Worldguard.java b/src/main/java/com/massivecraft/factions/integration/Worldguard.java index 457f2a7d..ac125bab 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; - FactionsPlugin.getInstance().log("Could not hook to WorldGuard. WorldGuard checks are disabled."); - } else { - wg = (WorldGuardPlugin) wgplug; - enabled = true; - FactionsPlugin.getInstance().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; + FactionsPlugin.getInstance().log("Could not hook to WorldGuard. WorldGuard checks are disabled."); + } else { + wg = (WorldGuardPlugin) wgplug; + enabled = true; + FactionsPlugin.getInstance().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..d2fdc6bd 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 120c8564..351af292 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java @@ -17,747 +17,747 @@ import java.util.Map.Entry; // This source code is a heavily modified version of mikeprimms plugin Dynmap-Factions. public class EngineDynmap { - // -------------------------------------------- // - // CONSTANTS - // -------------------------------------------- // + // -------------------------------------------- // + // CONSTANTS + // -------------------------------------------- // - public final static int BLOCKS_PER_CHUNK = 16; + public final static int BLOCKS_PER_CHUNK = 16; - public final static String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e"; + 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 = "factions"; + public final static String FACTIONS_ = FACTIONS + "_"; - public final static String FACTIONS_MARKERSET = FACTIONS_ + "markerset"; + 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_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 + "_"; + public final static String FACTIONS_PLAYERSET = FACTIONS_ + "playerset"; + public final static String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_"; - // -------------------------------------------- // - // INSTANCE & CONSTRUCT - // -------------------------------------------- // + // -------------------------------------------- // + // INSTANCE & CONSTRUCT + // -------------------------------------------- // - private static final EngineDynmap i = new EngineDynmap(); - public DynmapAPI dynmapApi; - public MarkerAPI markerApi; - public MarkerSet markerset; + private static final EngineDynmap i = new EngineDynmap(); + public DynmapAPI dynmapApi; + public MarkerAPI markerApi; + public MarkerSet markerset; - private EngineDynmap() { - } + private EngineDynmap() { + } - public static EngineDynmap getInstance() { - return i; - } + 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 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 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(); - } + 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); - } + // Thread Safe / Asynchronous: Yes + public static void info(String msg) { + System.out.println(DYNMAP_INTEGRATION + msg); + } - // -------------------------------------------- // - // UPDATE: HOMES - // -------------------------------------------- // + // -------------------------------------------- // + // UPDATE: HOMES + // -------------------------------------------- // - // Thread Safe / Asynchronous: Yes - public static void severe(String msg) { - System.out.println(DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg); - } + // 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"); + public void init() { + Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); - if (dynmap == null || !dynmap.isEnabled()) { - return; - } + 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; - } + // 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(FactionsPlugin.getInstance(), () -> { + // Shedule non thread safe sync at the end! + Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { - final Map homes = createHomes(); - final Map areas = createAreas(); - final Map> playerSets = createPlayersets(); + final Map homes = createHomes(); + final Map areas = createAreas(); + final Map> playerSets = createPlayersets(); - if (!updateCore()) { - return; - } + 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; - } + // 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); - } + updateHomes(homes); + updateAreas(areas); + updatePlayersets(playerSets); + }, 100L, 100L); + } - // -------------------------------------------- // - // UPDATE: AREAS - // -------------------------------------------- // + // -------------------------------------------- // + // 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; - } + // 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; - } + // Get MarkerAPI + this.markerApi = this.dynmapApi.getMarkerAPI(); + if (this.markerApi == null) { + severe("Could not retrieve the MarkerAPI."); + return false; + } - return true; - } + 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: 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: 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<>(); + // 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; - } + // Loop current factions + for (Faction faction : Factions.getInstance().getAllFactions()) { + Location ps = faction.getHome(); + if (ps == null) { + continue; + } - DynmapStyle style = getStyle(faction); + DynmapStyle style = getStyle(faction); - String markerId = FACTIONS_HOME_ + faction.getId(); + 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); + 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); - } + ret.put(markerId, temp); + } - return ret; - } + 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); - } + // 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(); + // 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; + // 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, keep it in the list for the next polygon - else { - if (newChunks == null) { - newChunks = new LinkedList<>(); + } 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; } - newChunks.add(chunk); - } - } + // 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; + // Replace list (null if no more to process) + allChunks = newChunks; - if (ourChunkFlags == null) { - continue; - } + 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; - } - } + // 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; - } + 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; + // 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; + 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.lineColor = style.getLineColor(); + temp.lineOpacity = style.getLineOpacity(); + temp.lineWeight = style.getLineWeight(); - temp.fillColor = style.getFillColor(); - temp.fillOpacity = style.getFillOpacity(); + temp.fillColor = style.getFillColor(); + temp.fillOpacity = style.getFillOpacity(); - temp.boost = style.getBoost(); + temp.boost = style.getBoost(); - ret.put(markerId, temp); + ret.put(markerId, temp); - markerIndex++; - } + markerIndex++; + } - return ret; - } + return ret; + } - // -------------------------------------------- // - // UTIL & SHARED - // -------------------------------------------- // + // -------------------------------------------- // + // 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); - } + // 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(); + // 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); - } - } + // 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(); - } - } + // 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 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; - } + // Thread Safe / Asynchronous: Yes + public Set createPlayerset(Faction faction) { + if (faction == null) { + return null; + } + if (faction.isWilderness()) { + return null; + } - Set ret = new HashSet<>(); + 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()); - } + 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; - } + return ret; + } - // Thread Safe / Asynchronous: Yes - public Map> createPlayersets() { - if (!Conf.dynmapVisibilityByFaction) { - return null; - } + // Thread Safe / Asynchronous: Yes + public Map> createPlayersets() { + if (!Conf.dynmapVisibilityByFaction) { + return null; + } - Map> ret = new HashMap<>(); + 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); - } + 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; - } + return ret; + } - // Thread Safe / Asynchronous: No - public void updatePlayersets(Map> playersets) { - if (playersets == null) { - return; - } + // 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; - } + // Remove + for (PlayerSet set : this.markerApi.getPlayerSets()) { + if (!set.getSetID().startsWith(FACTIONS_PLAYERSET_)) { + continue; + } - // (Null means remove all) - if (playersets.containsKey(set.getSetID())) { - continue; - } + // (Null means remove all) + if (playersets.containsKey(set.getSetID())) { + continue; + } - set.deleteSet(); - } + set.deleteSet(); + } - // Add / Update - for (Entry> entry : playersets.entrySet()) { - // Extract from Entry - String setId = entry.getKey(); - Set playerIds = entry.getValue(); + // 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; - } + // 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); - } - } + // Set Content + set.setPlayers(playerIds); + } + } - // Thread Safe / Asynchronous: Yes - private String getDescription(Faction faction) { - String ret = "
" + Conf.dynmapDescription + "
"; + // 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); + // 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); + // Description + String description = faction.getDescription(); + description = escapeHtml(ChatColor.stripColor(description)); + ret = ret.replace("%description%", description); - // Money + // Money - String money = "unavailable"; - if (Conf.bankEnabled && Conf.dynmapDescriptionMoney) - money = String.format("%.2f", Econ.getBalance(faction.getAccountId())); - ret = ret.replace("%money%", 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); + // Players + Set playersList = faction.getFPlayers(); + String playersCount = String.valueOf(playersList.size()); + String players = getHtmlPlayerString(playersList); - FPlayer playersLeaderObject = faction.getFPlayerAdmin(); - String playersLeader = getHtmlPlayerName(playersLeaderObject); + 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 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 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); + 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); + 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; - } + 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; - } + // 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; + Set visible = Conf.dynmapVisibleFactions; + Set hidden = Conf.dynmapHiddenFactions; - if (!visible.isEmpty() && !visible.contains(factionId) && !visible.contains(factionName) && !visible.contains("world:" + world)) { - return false; - } + 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); - } + return !hidden.contains(factionId) && !hidden.contains(factionName) && !hidden.contains("world:" + world); + } - // Thread Safe / Asynchronous: Yes - public DynmapStyle getStyle(Faction faction) { - DynmapStyle ret; + // 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.getId()); + if (ret != null) { + return ret; + } - ret = Conf.dynmapFactionStyles.get(faction.getTag()); - if (ret != null) { - return ret; - } + ret = Conf.dynmapFactionStyles.get(faction.getTag()); + if (ret != null) { + return ret; + } - return Conf.dynmapDefaultStyle; - } + 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}); + // 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; - } + 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 - } + 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..d2c3d109 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..896841bb 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..92b10ff3 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/EssentialsHomeHandler.java b/src/main/java/com/massivecraft/factions/listeners/EssentialsHomeHandler.java index 61ea94f5..ce7f74f8 100644 --- a/src/main/java/com/massivecraft/factions/listeners/EssentialsHomeHandler.java +++ b/src/main/java/com/massivecraft/factions/listeners/EssentialsHomeHandler.java @@ -17,28 +17,28 @@ import java.util.logging.Level; public class EssentialsHomeHandler implements Listener { - private IEssentials ess; + private IEssentials ess; - public EssentialsHomeHandler(IEssentials essentials) { - this.ess = essentials; - } + public EssentialsHomeHandler(IEssentials essentials) { + this.ess = essentials; + } - @EventHandler - public void onLeave(FPlayerLeaveEvent event) throws Exception { - Faction faction = event.getFaction(); - User user = ess.getUser(UUID.fromString(event.getfPlayer().getId())); - List homes = user.getHomes(); - if (homes == null || homes.isEmpty()) { - return; - } - for (String homeName : user.getHomes()) { - Location loc = user.getHome(homeName); - FLocation floc = new FLocation(loc); - Faction factionAt = Board.getInstance().getFactionAt(floc); - if (factionAt.equals(faction) && factionAt.isNormal()) { - user.delHome(homeName); - FactionsPlugin.getInstance().log(Level.INFO, "FactionLeaveEvent: Removing home %s, player %s, in territory of %s", homeName, event.getfPlayer().getName(), faction.getTag()); - } - } - } + @EventHandler + public void onLeave(FPlayerLeaveEvent event) throws Exception { + Faction faction = event.getFaction(); + User user = ess.getUser(UUID.fromString(event.getfPlayer().getId())); + List homes = user.getHomes(); + if (homes == null || homes.isEmpty()) { + return; + } + for (String homeName : user.getHomes()) { + Location loc = user.getHome(homeName); + FLocation floc = new FLocation(loc); + Faction factionAt = Board.getInstance().getFactionAt(floc); + if (factionAt.equals(faction) && factionAt.isNormal()) { + user.delHome(homeName); + FactionsPlugin.getInstance().log(Level.INFO, "FactionLeaveEvent: Removing home %s, player %s, in territory of %s", homeName, event.getfPlayer().getName(), faction.getTag()); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java index ffadf8b0..8254670f 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java @@ -36,530 +36,530 @@ 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(); + public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) { + String name = player.getName(); - if (Conf.playersWhoBypassAllProtection.contains(name)) - return true; + if (Conf.playersWhoBypassAllProtection.contains(name)) + return true; - FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); - Faction myFaction = me.getFaction(); - if (me.isAdminBypassing()) - return true; + FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); + Faction myFaction = me.getFaction(); + if (me.isAdminBypassing()) + return true; - FLocation loc = new FLocation(location); - Faction otherFaction = Board.getInstance().getFactionAt(loc); + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getInstance().getFactionAt(loc); - if (otherFaction.isWilderness()) { - if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) - return true; + 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 (!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."); + 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; + 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 (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) + return true; - if (!justCheck) - me.msg("You can't " + action + " in a safe zone."); + 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; + 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 (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) + return true; - if (!justCheck) - me.msg("You can't " + action + " in a war zone."); + if (!justCheck) + me.msg("You can't " + action + " in a war zone."); - return false; - } else if (!otherFaction.getId().equals(myFaction.getId())) { // If the faction target is not my own - if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) - return true; - // Get faction pain build access relation to me - boolean pain = !justCheck && otherFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; - return CheckActionState(otherFaction, loc, me, PermissableAction.fromString(action), pain); - } else if (otherFaction.getId().equals(myFaction.getId())) { - boolean pain = !justCheck && myFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; - return CheckActionState(myFaction, loc, me, PermissableAction.fromString(action), pain); - } + return false; + } else if (!otherFaction.getId().equals(myFaction.getId())) { // If the faction target is not my own + if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) + return true; + // Get faction pain build access relation to me + boolean pain = !justCheck && otherFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; + return CheckActionState(otherFaction, loc, me, PermissableAction.fromString(action), pain); + } else if (otherFaction.getId().equals(myFaction.getId())) { + boolean pain = !justCheck && myFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; + return CheckActionState(myFaction, loc, me, PermissableAction.fromString(action), pain); + } - // Something failed prevent build - return false; - } + // Something failed prevent build + return false; + } - public static boolean graceisEnabled() { - return Conf.gracePeriod; - } + public static boolean graceisEnabled() { + return Conf.gracePeriod; + } - private static boolean CheckPlayerAccess(Player player, FPlayer me, FLocation loc, Faction myFaction, Access access, PermissableAction action, boolean shouldHurt) { - boolean landOwned = (myFaction.doesLocationHaveOwnersSet(loc) && !myFaction.getOwnerList(loc).isEmpty()); - if ((landOwned && myFaction.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(myFaction.getId()))) - return true; - else if (landOwned && !myFaction.getOwnerListString(loc).contains(player.getName())) { - me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc))); - if (shouldHurt) { - player.damage(Conf.actionDeniedPainAmount); - me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); - } - return false; - } else if (!landOwned && access == Access.DENY) { // If land is not owned but access is set to DENY anyway - if (shouldHurt) { - player.damage(Conf.actionDeniedPainAmount); - me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); - } - me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); - return false; - } else if (access == Access.ALLOW) return true; - me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); - return false; - } + private static boolean CheckPlayerAccess(Player player, FPlayer me, FLocation loc, Faction myFaction, Access access, PermissableAction action, boolean shouldHurt) { + boolean landOwned = (myFaction.doesLocationHaveOwnersSet(loc) && !myFaction.getOwnerList(loc).isEmpty()); + if ((landOwned && myFaction.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(myFaction.getId()))) + return true; + else if (landOwned && !myFaction.getOwnerListString(loc).contains(player.getName())) { + me.msg(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc))); + if (shouldHurt) { + player.damage(Conf.actionDeniedPainAmount); + me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); + } + return false; + } else if (!landOwned && access == Access.DENY) { // If land is not owned but access is set to DENY anyway + if (shouldHurt) { + player.damage(Conf.actionDeniedPainAmount); + me.msg(TL.ACTIONS_NOPERMISSIONPAIN.toString().replace("{action}", action.toString()).replace("{faction}", Board.getInstance().getFactionAt(loc).getTag(myFaction))); + } + me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); + return false; + } else if (access == Access.ALLOW) return true; + me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", action.toString())); + return false; + } - private static boolean CheckActionState(Faction target, FLocation location, FPlayer me, PermissableAction action, boolean pain) { - if (Conf.ownedAreasEnabled && target.doesLocationHaveOwnersSet(location) && !target.playerHasOwnershipRights(me, location)) { - // If pain should be applied - if (pain && Conf.ownedAreaPainBuild) - me.msg(TL.ACTIONS_OWNEDTERRITORYPAINDENY.toString().replace("{action}", action.toString()).replace("{faction}", target.getOwnerListString(location))); - if (Conf.ownedAreaDenyBuild && pain) return false; - else if (Conf.ownedAreaDenyBuild) { - me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", target.getTag(me.getFaction())).replace("{action}", action.toString())); - return false; - } - } - return CheckPlayerAccess(me.getPlayer(), me, location, target, target.getAccess(me, action), action, pain); - } + private static boolean CheckActionState(Faction target, FLocation location, FPlayer me, PermissableAction action, boolean pain) { + if (Conf.ownedAreasEnabled && target.doesLocationHaveOwnersSet(location) && !target.playerHasOwnershipRights(me, location)) { + // If pain should be applied + if (pain && Conf.ownedAreaPainBuild) + me.msg(TL.ACTIONS_OWNEDTERRITORYPAINDENY.toString().replace("{action}", action.toString()).replace("{faction}", target.getOwnerListString(location))); + if (Conf.ownedAreaDenyBuild && pain) return false; + else if (Conf.ownedAreaDenyBuild) { + me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", target.getTag(me.getFaction())).replace("{action}", action.toString())); + return false; + } + } + return CheckPlayerAccess(me.getPlayer(), me, location, target, target.getAccess(me, action), action, pain); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - if (!event.canBuild()) { - return; - } + @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; - } + // 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); - } - } + 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; + @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 target block as done above + */ + } + + @EventHandler + public void onVaultPlace(BlockPlaceEvent e) { + if (e.getItemInHand().getType() == Material.CHEST) { + ItemStack vault = FactionsPlugin.getInstance().createItem(Material.CHEST, 1, (short) 0, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fvault.Item.Name")), FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().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 || (FactionsPlugin.getInstance().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 && !FactionsPlugin.getInstance().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; + } + + if (event.getBlocks().isEmpty()) { + return; + } + Location targetLoc = event.getBlocks().get(0).getLocation(); + 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() && FactionsPlugin.getInstance().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 onBannerBreak(BlockBreakEvent e) { + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + if (FactionsPlugin.getInstance().mc17) { + return; + } + + if (bannerLocations.containsValue(e.getBlock().getLocation())) { + if (e.getBlock().getType().name().contains("BANNER")) { + e.setCancelled(true); + fme.msg(TL.BANNER_CANNOT_BREAK); + } + } + } + + @EventHandler + public void onBannerPlace(BlockPlaceEvent e) { + if (FactionsPlugin.getInstance().mc17) { + return; + } + if (e.getItemInHand().getType().name().contains("BANNER")) { + ItemStack bannerInHand = e.getItemInHand(); + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + ItemStack warBanner = fme.getFaction().getBanner(); + if (warBanner == null) { + return; + } + ItemMeta warmeta = warBanner.getItemMeta(); + warmeta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.Item.Name"))); + warmeta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Item.Lore"))); + warBanner.setItemMeta(warmeta); + if (warBanner.isSimilar(bannerInHand)) { + if (fme.getFaction().isWilderness()) { + fme.msg(TL.WARBANNER_NOFACTION); + e.setCancelled(true); + return; + } + int bannerTime = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Time") * 20; + Location placedLoc = e.getBlockPlaced().getLocation(); + FLocation fplacedLoc = new FLocation(placedLoc); + if ((Board.getInstance().getFactionAt(fplacedLoc).isWarZone() && FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Placeable.Warzone")) || (fme.getFaction().getRelationTo(Board.getInstance().getFactionAt(fplacedLoc)) == Relation.ENEMY && FactionsPlugin.getInstance().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 (XMaterial.isVersionOrHigher(XMaterial.MinecraftVersion.VERSION_1_9)) { + fplayer.getPlayer().sendTitle(FactionsPlugin.getInstance().color(fme.getTag() + " Placed A WarBanner!"), FactionsPlugin.getInstance().color("&7use &c/f tpbanner&7 to tp to the banner!"), 10, 70, 20); + } else { + fplayer.getPlayer().sendTitle(FactionsPlugin.getInstance().color(fme.getTag() + " Placed A WarBanner!"), FactionsPlugin.getInstance().color("&7use &c/f tpbanner&7 to tp to the banner!")); + } + } + bannerCooldownMap.put(fme.getTag(), true); + FactionsBlockListener.bannerLocations.put(fme.getTag(), e.getBlockPlaced().getLocation()); + int bannerCooldown = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Place-Cooldown"); + ArmorStand as = (ArmorStand) e.getBlockPlaced().getLocation().add(0.5, 1.0, 0.5).getWorld().spawnEntity(e.getBlockPlaced().getLocation().add(0.5, 1.0, 0.5), EntityType.ARMOR_STAND); + as.setVisible(false); + as.setGravity(false); + as.setCanPickupItems(false); + as.setCustomName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.BannerHolo").replace("{Faction}", fme.getTag()))); + as.setCustomNameVisible(true); + String tag = fme.getTag(); + Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> bannerCooldownMap.remove(tag), Long.parseLong(bannerCooldown + "")); + Block banner = e.getBlockPlaced(); + Material bannerType = banner.getType(); + Faction bannerFaction = fme.getFaction(); + banner.getWorld().strikeLightningEffect(banner.getLocation()); + int radius = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Effect-Radius"); + List effects = FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Effects"); + int affectorTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { + for (Entity e1 : banner.getLocation().getWorld().getNearbyEntities(banner.getLocation(), (double) radius, 255.0, (double) radius)) { + if (e1 instanceof Player) { + Player player = (Player) e1; + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (fplayer.getFaction() != bannerFaction) { + continue; + } + 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.0f, 1.0f, 1.0f, 1.0f, 10, banner.getLocation(), 16.0); + ParticleEffect.FLAME.display(1.0f, 1.0f, 1.0f, 1.0f, 10, banner.getLocation(), 16.0); + if (banner.getType() == bannerType) { + continue; + } + banner.setType(bannerType); + } + } + }, 0L, 20L); + Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> { + banner.setType(Material.AIR); + as.remove(); + banner.getWorld().strikeLightningEffect(banner.getLocation()); + Bukkit.getScheduler().cancelTask(affectorTask); + FactionsBlockListener.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); + } + } + + @EventHandler + public void onFallingBlock(EntityChangeBlockEvent event) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("Falling-Block-Fix.Enabled")) + return; + + Faction faction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + if (faction.isWarZone() || faction.isSafeZone()) { + event.getBlock().setType(Material.AIR); + event.setCancelled(true); + } + } + + //Grace + @EventHandler + public void onBreak(EntityExplodeEvent e) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-grace.Enabled")) + return; + + if (!graceisEnabled()) { + e.setCancelled(true); + } + } + + @EventHandler + public void entityDamage(EntityDamageEvent e) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-grace.Enabled")) + return; + + if (!graceisEnabled()) { + if (e.getEntity() instanceof Player) { + if (e.getCause() == EntityDamageEvent.DamageCause.PROJECTILE) { + e.setCancelled(true); + } + } + } + } + + @EventHandler + public void onTNTPlace(BlockPlaceEvent e1) { + FPlayer fp = FPlayers.getInstance().getByPlayer(e1.getPlayer()); + if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-grace.Enabled")) + return; + + if (!graceisEnabled() && !fp.isAdminBypassing()) { + if (e1.getBlock().getType().equals(Material.TNT)) { + e1.setCancelled(true); + + fp.msg(TL.COMMAND_GRACE_ENABLED, e1.getBlockPlaced().getType().toString()); + } + } + } + + 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) { + FPlayer fme = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { + event.setCancelled(true); + return; + } + if (!fme.hasFaction()) + return; + + if (event.getBlock().getType() == XMaterial.SPAWNER.parseMaterial()) { + 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"); + } + } + } + } + + @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); - } - } - } - } - - @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 target block as done above - */ - } - - @EventHandler - public void onVaultPlace(BlockPlaceEvent e) { - if (e.getItemInHand().getType() == Material.CHEST) { - ItemStack vault = FactionsPlugin.getInstance().createItem(Material.CHEST, 1, (short) 0, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fvault.Item.Name")), FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().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 || (FactionsPlugin.getInstance().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 && !FactionsPlugin.getInstance().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; - } - - if (event.getBlocks().isEmpty()) { - return; - } - Location targetLoc = event.getBlocks().get(0).getLocation(); - 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() && FactionsPlugin.getInstance().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 onBannerBreak(BlockBreakEvent e){ - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - if (FactionsPlugin.getInstance().mc17) { - return; - } - - if(bannerLocations.containsValue(e.getBlock().getLocation())){ - if(e.getBlock().getType().name().contains("BANNER")) { - e.setCancelled(true); - fme.msg(TL.BANNER_CANNOT_BREAK); - } - } - } - - @EventHandler - public void onBannerPlace(BlockPlaceEvent e) { - if (FactionsPlugin.getInstance().mc17) { - return; - } - if (e.getItemInHand().getType().name().contains("BANNER")) { - ItemStack bannerInHand = e.getItemInHand(); - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - ItemStack warBanner = fme.getFaction().getBanner(); - if (warBanner == null) { - return; - } - ItemMeta warmeta = warBanner.getItemMeta(); - warmeta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.Item.Name"))); - warmeta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Item.Lore"))); - warBanner.setItemMeta(warmeta); - if (warBanner.isSimilar(bannerInHand)) { - if (fme.getFaction().isWilderness()) { - fme.msg(TL.WARBANNER_NOFACTION); - e.setCancelled(true); - return; - } - int bannerTime = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Time") * 20; - Location placedLoc = e.getBlockPlaced().getLocation(); - FLocation fplacedLoc = new FLocation(placedLoc); - if ((Board.getInstance().getFactionAt(fplacedLoc).isWarZone() && FactionsPlugin.getInstance().getConfig().getBoolean("fbanners.Placeable.Warzone")) || (fme.getFaction().getRelationTo(Board.getInstance().getFactionAt(fplacedLoc)) == Relation.ENEMY && FactionsPlugin.getInstance().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 (XMaterial.isVersionOrHigher(XMaterial.MinecraftVersion.VERSION_1_9)) { - fplayer.getPlayer().sendTitle(FactionsPlugin.getInstance().color(fme.getTag() + " Placed A WarBanner!"), FactionsPlugin.getInstance().color("&7use &c/f tpbanner&7 to tp to the banner!"), 10, 70, 20); - } else { - fplayer.getPlayer().sendTitle(FactionsPlugin.getInstance().color(fme.getTag() + " Placed A WarBanner!"), FactionsPlugin.getInstance().color("&7use &c/f tpbanner&7 to tp to the banner!")); - } - } - bannerCooldownMap.put(fme.getTag(), true); - FactionsBlockListener.bannerLocations.put(fme.getTag(), e.getBlockPlaced().getLocation()); - int bannerCooldown = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Place-Cooldown"); - ArmorStand as = (ArmorStand) e.getBlockPlaced().getLocation().add(0.5, 1.0, 0.5).getWorld().spawnEntity(e.getBlockPlaced().getLocation().add(0.5, 1.0, 0.5), EntityType.ARMOR_STAND); - as.setVisible(false); - as.setGravity(false); - as.setCanPickupItems(false); - as.setCustomName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fbanners.BannerHolo").replace("{Faction}", fme.getTag()))); - as.setCustomNameVisible(true); - String tag = fme.getTag(); - Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> bannerCooldownMap.remove(tag), Long.parseLong(bannerCooldown + "")); - Block banner = e.getBlockPlaced(); - Material bannerType = banner.getType(); - Faction bannerFaction = fme.getFaction(); - banner.getWorld().strikeLightningEffect(banner.getLocation()); - int radius = FactionsPlugin.getInstance().getConfig().getInt("fbanners.Banner-Effect-Radius"); - List effects = FactionsPlugin.getInstance().getConfig().getStringList("fbanners.Effects"); - int affectorTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { - for (Entity e1 : banner.getLocation().getWorld().getNearbyEntities(banner.getLocation(), (double) radius, 255.0, (double) radius)) { - if (e1 instanceof Player) { - Player player = (Player) e1; - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - if (fplayer.getFaction() != bannerFaction) { - continue; - } - 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.0f, 1.0f, 1.0f, 1.0f, 10, banner.getLocation(), 16.0); - ParticleEffect.FLAME.display(1.0f, 1.0f, 1.0f, 1.0f, 10, banner.getLocation(), 16.0); - if (banner.getType() == bannerType) { - continue; - } - banner.setType(bannerType); - } - } - }, 0L, 20L); - Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> { - banner.setType(Material.AIR); - as.remove(); - banner.getWorld().strikeLightningEffect(banner.getLocation()); - Bukkit.getScheduler().cancelTask(affectorTask); - FactionsBlockListener.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); - } - } - - @EventHandler - public void onFallingBlock(EntityChangeBlockEvent event) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("Falling-Block-Fix.Enabled")) - return; - - Faction faction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); - if (faction.isWarZone() || faction.isSafeZone()) { - event.getBlock().setType(Material.AIR); - event.setCancelled(true); - } - } - - //Grace - @EventHandler - public void onBreak(EntityExplodeEvent e) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-grace.Enabled")) - return; - - if (!graceisEnabled()) { - e.setCancelled(true); - } - } - - @EventHandler - public void entityDamage(EntityDamageEvent e) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-grace.Enabled")) - return; - - if (!graceisEnabled()) { - if (e.getEntity() instanceof Player) { - if (e.getCause() == EntityDamageEvent.DamageCause.PROJECTILE) { - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onTNTPlace(BlockPlaceEvent e1) { - FPlayer fp = FPlayers.getInstance().getByPlayer(e1.getPlayer()); - if (!FactionsPlugin.getInstance().getConfig().getBoolean("f-grace.Enabled")) - return; - - if (!graceisEnabled() && !fp.isAdminBypassing()) { - if (e1.getBlock().getType().equals(Material.TNT)) { - e1.setCancelled(true); - - fp.msg(TL.COMMAND_GRACE_ENABLED, e1.getBlockPlaced().getType().toString()); - } - } - } - - 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) { - FPlayer fme = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { - event.setCancelled(true); - return; - } - if (!fme.hasFaction()) - return; - - if (event.getBlock().getType() == XMaterial.SPAWNER.parseMaterial()) { - 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"); - } - } - } - } - - @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 4b8227cb..50df43ec 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java @@ -19,190 +19,190 @@ 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); + //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); - me.setChatMode(ChatMode.FACTION); - return; - } - - - Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("Mod Chat: " + message)); - - 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); - - 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); - } - } - - event.setCancelled(true); - } else if (chat == ChatMode.ALLIANCE) { - Faction myFaction = me.getFaction(); - - String message = String.format(Conf.allianceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); - - //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); - } - } - - Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("AllianceChat: " + message)); - - event.setCancelled(true); - } else if (chat == ChatMode.TRUCE) { - Faction myFaction = me.getFaction(); - - String message = String.format(Conf.truceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); - - //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); - } - } - - 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; - } - - 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()); - } - - 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 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; - FactionsPlugin.getInstance().log(Level.SEVERE, "Critical error in chat message formatting!"); - FactionsPlugin.getInstance().log(Level.SEVERE, "NOTE: This has been automatically fixed right now by setting chatTagInsertIndex to 0."); - FactionsPlugin.getInstance().log(Level.SEVERE, "For a more proper fix, please read this regarding chat configuration: http://massivecraft.com/plugins/factions/config#Chat_configuration"); + } else { + // Just in case player gets demoted while in faction chat. + me.msg(TL.COMMAND_CHAT_MOD_ONLY); + event.setCancelled(true); + me.setChatMode(ChatMode.FACTION); 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); - } - private void doWarmup(final String warp, final FPlayer fme) { - WarmUpUtil.process(fme, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, () -> { - Player player = Bukkit.getPlayer(fme.getPlayer().getUniqueId()); - if (player != null) { - player.teleport(fme.getFaction().getWarp(warp).getLocation()); - fme.msg(TL.COMMAND_FWARP_WARPED, warp); - } - }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-warp", 0)); - } + Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("Mod Chat: " + message)); + + 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); + + 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); + } + } + + event.setCancelled(true); + } else if (chat == ChatMode.ALLIANCE) { + Faction myFaction = me.getFaction(); + + String message = String.format(Conf.allianceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); + + //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); + } + } + + Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("AllianceChat: " + message)); + + event.setCancelled(true); + } else if (chat == ChatMode.TRUCE) { + Faction myFaction = me.getFaction(); + + String message = String.format(Conf.truceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); + + //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); + } + } + + 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; + } + + 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()); + } + + 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 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; + FactionsPlugin.getInstance().log(Level.SEVERE, "Critical error in chat message formatting!"); + FactionsPlugin.getInstance().log(Level.SEVERE, "NOTE: This has been automatically fixed right now by setting chatTagInsertIndex to 0."); + FactionsPlugin.getInstance().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); + } + + private void doWarmup(final String warp, final FPlayer fme) { + WarmUpUtil.process(fme, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, () -> { + Player player = Bukkit.getPlayer(fme.getPlayer().getUniqueId()); + if (player != null) { + player.teleport(fme.getFaction().getWarp(warp).getLocation()); + fme.msg(TL.COMMAND_FWARP_WARPED, warp); + } + }, FactionsPlugin.getInstance().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 1d8daa28..14dd0d89 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java @@ -30,490 +30,490 @@ 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)); + 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; - } + @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())); + 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()); - } + 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 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()); - } - } + // 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 + /** + * 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 + Entity damagee = sub.getEntity(); + Entity damager = sub.getDamager(); + if (damagee instanceof 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); - } + 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 { - // 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); - } + + // 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; } - // 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 (FactionsPlugin.getInstance().getStuckMap().containsKey(uuid)) { - FPlayers.getInstance().getByPlayer(player).msg(TL.COMMAND_STUCK_CANCELLED); - FactionsPlugin.getInstance().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 - - // The block don't have to explode - event.blockList().removeIf(block -> !this.checkExplosionForBlock(boomer, block)); - - // Cancel the event if no block will explode - if (!event.blockList().isEmpty() && (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 != 90 && id != 116 && id != 119 && id != 120 && id != 130) { - target.breakNaturally(); + //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 + } + } - private boolean checkExplosionForBlock(Entity boomer, Block block) { - Faction faction = Board.getInstance().getFactionAt(new FLocation(block.getLocation())); + // 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); + } + } + } - if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && Conf.peacefulTerritoryDisableBoom)) { - // faction is peaceful and has explosions set to disabled - return false; - } + private void cancelFFly(Player player) { + if (player == null) { + return; + } - boolean online = faction.hasPlayersOnline(); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (fPlayer.isFlying()) { + fPlayer.setFFlying(false, true); + } + } - 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 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)); + public void cancelFStuckTeleport(Player player) { + if (player == null) { + return; + } + UUID uuid = player.getUniqueId(); + if (FactionsPlugin.getInstance().getStuckMap().containsKey(uuid)) { + FPlayers.getInstance().getByPlayer(player).msg(TL.COMMAND_STUCK_CANCELLED); + FactionsPlugin.getInstance().getStuckMap().remove(uuid); + } + } - // No condition retained, destroy the block! - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityExplode(EntityExplodeEvent event) { + Entity boomer = event.getEntity(); - // 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); - } - } + // Before we need to check the location where the block is placed + if (!this.checkExplosionForBlock(boomer, event.getLocation().getBlock())) { + event.setCancelled(true); + return; + } - @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; - } + // Loop the blocklist to run checks on each aimed block - ProjectileSource thrower = event.getPotion().getShooter(); - if (!(thrower instanceof Entity)) { - return; - } + // The block don't have to explode + event.blockList().removeIf(block -> !this.checkExplosionForBlock(boomer, block)); - if (thrower instanceof Player) { - Player player = (Player) thrower; - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - if (badjuju && fPlayer.getFaction().isPeaceful()) { - event.setCancelled(true); - return; - } - } + // Cancel the event if no block will explode + if (!event.blockList().isEmpty() && (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(); - // 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 - } - } - } + 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)); - public boolean isPlayerInSafeZone(Entity damagee) { - if (!(damagee instanceof Player)) { - return false; - } - return Board.getInstance().getFactionAt(new FLocation(damagee.getLocation())).isSafeZone(); - } + 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 != 90 && id != 116 && id != 119 && id != 120 && id != 130) { + target.breakNaturally(); + } + } + } + } + } - public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { - return canDamagerHurtDamagee(sub, true); - } + private boolean checkExplosionForBlock(Entity boomer, Block block) { + Faction faction = Board.getInstance().getFactionAt(new FLocation(block.getLocation())); - public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) { - Entity damager = sub.getDamager(); - Entity damagee = sub.getEntity(); + if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && Conf.peacefulTerritoryDisableBoom)) { + // faction is peaceful and has explosions set to disabled + return false; + } - if (!(damagee instanceof Player)) { - return true; - } + boolean online = faction.hasPlayersOnline(); - FPlayer defender = FPlayers.getInstance().getByPlayer((Player) damagee); + 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 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)); - if (defender == null || defender.getPlayer() == null) { - return true; - } + // No condition retained, destroy the block! + } - Location defenderLoc = defender.getPlayer().getLocation(); - Faction defLocFaction = Board.getInstance().getFactionAt(new FLocation(defenderLoc)); + // 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); + } + } - // 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; + @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; + } - if (!(projectile.getShooter() instanceof Entity)) { - return true; - } + ProjectileSource thrower = event.getPotion().getShooter(); + if (!(thrower instanceof Entity)) { + return; + } - damager = (Entity) projectile.getShooter(); - } + if (thrower instanceof Player) { + Player player = (Player) thrower; + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (badjuju && fPlayer.getFaction().isPeaceful()) { + event.setCancelled(true); + return; + } + } - if (damager == damagee) // ender pearl usage and other self-inflicted damage - { - return true; - } + // 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 + } + } + } - // 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(); - } + public boolean isPlayerInSafeZone(Entity damagee) { + if (!(damagee instanceof Player)) { + return false; + } + return Board.getInstance().getFactionAt(new FLocation(damagee.getLocation())).isSafeZone(); + } - if (!(damager instanceof Player)) { - return true; - } + public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { + return canDamagerHurtDamagee(sub, true); + } - FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); + public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) { + Entity damager = sub.getDamager(); + Entity damagee = sub.getEntity(); - if (attacker == null || attacker.getPlayer() == null) { - return true; - } + if (!(damagee instanceof Player)) { + return true; + } - if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) { - return true; - } + FPlayer defender = FPlayers.getInstance().getByPlayer((Player) damagee); - if (attacker.hasLoginPvpDisabled()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_LOGIN, Conf.noPVPDamageToOthersForXSecondsAfterLogin); - } - return false; - } + if (defender == null || defender.getPlayer() == null) { + return true; + } - Faction locFaction = Board.getInstance().getFactionAt(new FLocation(attacker)); + Location defenderLoc = defender.getPlayer().getLocation(); + Faction defLocFaction = Board.getInstance().getFactionAt(new FLocation(defenderLoc)); - // 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; - } + // 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 (locFaction.isWarZone() && Conf.warZoneFriendlyFire) { - return true; - } + if (!(projectile.getShooter() instanceof Entity)) { + return true; + } - if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) { - return true; - } + damager = (Entity) projectile.getShooter(); + } - Faction defendFaction = defender.getFaction(); - Faction attackFaction = attacker.getFaction(); + if (damager == damagee) // ender pearl usage and other self-inflicted damage + { + return true; + } - 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; - } - } + // 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 (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; - } + if (!(damager instanceof Player)) { + return true; + } - Relation relation = defendFaction.getRelationTo(attackFaction); + FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); - // You can not hurt neutral factions - if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_NEUTRAL); - } - return false; - } + if (attacker == null || attacker.getPlayer() == null) { + return true; + } - // Players without faction may be hurt anywhere - if (!defender.hasFaction()) { - return true; - } + if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) { + return true; + } - // You can never hurt faction members or allies - if (relation.isMember() || relation.isAlly() || relation.isTruce()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_CANTHURT, defender.describeTo(attacker)); - } - return false; - } + if (attacker.hasLoginPvpDisabled()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_LOGIN, Conf.noPVPDamageToOthersForXSecondsAfterLogin); + } + return false; + } - boolean ownTerritory = defender.isInOwnTerritory(); + Faction locFaction = Board.getInstance().getFactionAt(new FLocation(attacker)); - // 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; - } + // 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; + } - // Damage will be dealt. However check if the damage should be reduced. + 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() || relation.isTruce()) { + 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)); @@ -526,228 +526,228 @@ 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); + } + } + } - @EventHandler - public void onHangerBreak(HangingBreakByEntityEvent e) { - if (e.getRemover() == null) return; - if (!(e.getRemover() instanceof Player)) return; - Player p = (Player) e.getRemover(); - if (e.getEntity().getType().equals(EntityType.PAINTING)) { - if (!FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) { - e.setCancelled(true); - } - } else if (e.getEntity().getType().equals(EntityType.ITEM_FRAME)) { - if (!FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) { - e.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPaintingPlace(HangingPlaceEvent event) { - if (event.getEntity().getType().equals(EntityType.PAINTING)) { - if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false)) { - event.setCancelled(true); - // Fix: update player's inventory to avoid items glitches - event.getPlayer().updateInventory(); - } - } else if (event.getEntity().getType().equals(EntityType.ITEM_FRAME)) { - if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getEntity().getLocation(), "build", 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(); - - // for now, only interested in Enderman and Wither boss tomfoolery - if (!(entity instanceof Enderman) && !(entity instanceof Wither)) { - return; - } - - 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); - } - } - } - - @EventHandler - public void onTravel(PlayerPortalEvent event) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("portals.limit", false)) { - return; // Don't do anything if they don't want us to. - } - - 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; - } - - FPlayer fp = FPlayers.getInstance().getByPlayer(event.getPlayer()); - String mininumRelation = FactionsPlugin.getInstance().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)); + @EventHandler + public void onHangerBreak(HangingBreakByEntityEvent e) { + if (e.getRemover() == null) return; + if (!(e.getRemover() instanceof Player)) return; + Player p = (Player) e.getRemover(); + if (e.getEntity().getType().equals(EntityType.PAINTING)) { + if (!FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) { e.setCancelled(true); - } - } - } - } + } + } else if (e.getEntity().getType().equals(EntityType.ITEM_FRAME)) { + if (!FactionsBlockListener.playerCanBuildDestroyBlock(p, e.getEntity().getLocation(), "destroy", false)) { + 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(); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPaintingPlace(HangingPlaceEvent event) { + if (event.getEntity().getType().equals(EntityType.PAINTING)) { + if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false)) { + event.setCancelled(true); + // Fix: update player's inventory to avoid items glitches + event.getPlayer().updateInventory(); + } + } else if (event.getEntity().getType().equals(EntityType.ITEM_FRAME)) { + if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getEntity().getLocation(), "build", 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(); + + // for now, only interested in Enderman and Wither boss tomfoolery + if (!(entity instanceof Enderman) && !(entity instanceof Wither)) { + return; + } + + 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); + } + } + } + + @EventHandler + public void onTravel(PlayerPortalEvent event) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("portals.limit", false)) { + return; // Don't do anything if they don't want us to. + } + + 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; + } + + FPlayer fp = FPlayers.getInstance().getByPlayer(event.getPlayer()); + String mininumRelation = FactionsPlugin.getInstance().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(); - FPlayer fdamager = FPlayers.getInstance().getByPlayer(damager); + Player attacker = (Player) e.getDamager(); FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim); - if (fvictim.getRelationTo(fdamager) == Relation.TRUCE) { - fdamager.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fdamager)); - e.setCancelled(true); + FPlayer fattacker = FPlayers.getInstance().getByPlayer(attacker); + if (fattacker.getRelationTo(fvictim) == Relation.TRUCE) { + fattacker.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fattacker)); + 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() == null) return; - if (!event.getRightClicked().getType().equals(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() == null) return; + if (!event.getRightClicked().getType().equals(EntityType.ITEM_FRAME)) return; - if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getRightClicked().getLocation(), "build", false)) { - event.setCancelled(true); - } - } + if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getRightClicked().getLocation(), "build", 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 7804cc73..45fc7d28 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java @@ -15,65 +15,65 @@ 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(); + // thanks to ObGenBlocker and WorldGuard for this method + Block block = event.getToBlock(); - // Added this so it wont die on 1.14 :) - if (FactionsPlugin.getInstance().mc114) { - Material source = event.getBlock().getType(); - Material target = block.getType(); - if ((target == Material.REDSTONE_WIRE || target == Material.TRIPWIRE) && (source == Material.AIR || source == Material.LEGACY_STATIONARY_LAVA || source == Material.LEGACY_LAVA)) { - block.setType(Material.AIR); - } - return; - } + // Added this so it wont die on 1.14 :) + if (FactionsPlugin.getInstance().mc114) { + Material source = event.getBlock().getType(); + Material target = block.getType(); + if ((target == Material.REDSTONE_WIRE || target == Material.TRIPWIRE) && (source == Material.AIR || source == Material.LEGACY_STATIONARY_LAVA || source == Material.LEGACY_LAVA)) { + block.setType(Material.AIR); + } + return; + } - // run this for all versions below 1.14 - 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); - } + // run this for all versions below 1.14 + 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 == XMaterial.GLASS_PANE.parseMaterial() - || mat == XMaterial.IRON_BARS.parseMaterial()) && clippingThrough(target, from, 0.65)) - || ((mat == XMaterial.OAK_FENCE.parseMaterial() || mat == XMaterial.NETHER_BRICK_FENCE.parseMaterial()) && 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 == XMaterial.GLASS_PANE.parseMaterial() + || mat == XMaterial.IRON_BARS.parseMaterial()) && clippingThrough(target, from, 0.65)) + || ((mat == XMaterial.OAK_FENCE.parseMaterial() || mat == XMaterial.NETHER_BRICK_FENCE.parseMaterial()) && 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 7f5c8ae2..9cd6cd5c 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java @@ -46,989 +46,990 @@ import java.util.logging.Level; public class FactionsPlayerListener implements Listener { - HashMap fallMap = new HashMap<>(); - private Set corners; - // 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() { - this.corners = new HashSet<>(); - for (Player player : FactionsPlugin.getInstance().getServer().getOnlinePlayers()) { - initPlayer(player); - } - for (World world : FactionsPlugin.getInstance().getServer().getWorlds()) { - WorldBorder border = world.getWorldBorder(); - if (border != null) { - int cornerCoord = (int) ((border.getSize() - 1.0) / 2.0); - this.corners.add(new FLocation(world.getName(), FLocation.blockToChunk(cornerCoord), FLocation.blockToChunk(cornerCoord))); - this.corners.add(new FLocation(world.getName(), FLocation.blockToChunk(cornerCoord), FLocation.blockToChunk(-cornerCoord))); - this.corners.add(new FLocation(world.getName(), FLocation.blockToChunk(-cornerCoord), FLocation.blockToChunk(cornerCoord))); - this.corners.add(new FLocation(world.getName(), FLocation.blockToChunk(-cornerCoord), FLocation.blockToChunk(-cornerCoord))); - } - } - } - - 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(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc))); - } - return false; - } - - if (me.getFaction() == otherFaction) return true; - - if (FactionsPlugin.getInstance().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); - return CheckPlayerAccess(player, me, loc, otherFaction, access, PermissableAction.ITEM, false); - } - - @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.isSystemFaction()) return true; - if (myFaction.isWilderness()) { - me.msg(TL.GENERIC_NOPERMISSION, TL.GENERIC_DOTHAT); - return false; - } - - if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) - return true; - - if (otherFaction.getId().equals(myFaction.getId()) && me.getRole() == Role.LEADER) return true; - PermissableAction action = GetPermissionFromUsableBlock(block); - if (action == null) return false; - // We only care about some material types. - /// Who was the idiot? - if (otherFaction.hasPlayersOnline()) { - if (Conf.territoryProtectedMaterials.contains(material)) { - return false; - } - } else { - if (Conf.territoryProtectedMaterialsWhenOffline.contains(material)) { - return false; - } - } - - // Move up access check to check for exceptions - if (!otherFaction.getId().equals(myFaction.getId())) { // If the faction target is not my own - // Get faction pain build access relation to me - boolean pain = !justCheck && otherFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; - return CheckPlayerAccess(player, me, loc, otherFaction, otherFaction.getAccess(me, action), action, pain); - } else if (otherFaction.getId().equals(myFaction.getId())) { - return CheckPlayerAccess(player, me, loc, myFaction, myFaction.getAccess(me, action), action, (!justCheck && myFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW)); - } - return CheckPlayerAccess(player, me, loc, myFaction, otherFaction.getAccess(me, action), action, Conf.territoryPainBuild); - } - - - 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; - } - - /// - /// This checks if the current player can execute an action based on it's factions access and surroundings - /// It will grant access in the following priorities: - /// - If Faction Land is Owned and the Owner is the current player, or player is faction leader. - /// - If Faction Land is not Owned and my access value is not set to DENY - /// - If none of the filters above matches, then we consider access is set to ALLOW|UNDEFINED - /// This check does not performs any kind of bypass check (i.e.: me.isAdminBypassing()) - /// - /// The player entity which the check will be made upon - /// The Faction player object related to the player - /// The World location where the action is being executed - /// The faction of the player being checked - /// The current's faction access permission for the action - private static boolean CheckPlayerAccess(Player player, FPlayer me, FLocation loc, Faction factionToCheck, Access access, PermissableAction action, boolean pain) { - boolean doPain = pain && Conf.handleExploitInteractionSpam; - if (access != null && access != Access.UNDEFINED) { - // TODO: Update this once new access values are added other than just allow / deny. - boolean landOwned = (factionToCheck.doesLocationHaveOwnersSet(loc) && !factionToCheck.getOwnerList(loc).isEmpty()); - if ((landOwned && factionToCheck.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(factionToCheck.getId()))) { - return true; - } else if (landOwned && !factionToCheck.getOwnerListString(loc).contains(player.getName())) { - me.msg("You can't do that in this territory, it is owned by: " + factionToCheck.getOwnerListString(loc)); - if (doPain) { - player.damage(Conf.actionDeniedPainAmount); - } - return false; - } else if (!landOwned && access == Access.ALLOW) { - return true; - } else { - me.msg("You cannot " + action + " in the territory of " + factionToCheck.getTag(me.getFaction())); - return false; - } - } - // Approves any permission check if the player in question is a leader AND owns the faction. - if (me.getRole().equals(Role.LEADER) && me.getFaction().equals(factionToCheck)) return true; - if (factionToCheck != null) { - me.msg(TL.PLAYER_USE_TERRITORY, action, factionToCheck.getTag(me.getFaction())); - } - return false; - } - - /// - /// This will try to resolve a permission action based on the item material, if it's not usable, will return null - /// - private static PermissableAction GetPermissionFromUsableBlock(Block block) { - return GetPermissionFromUsableBlock(block.getType()); - } - - ///
- /// This will try to resolve a permission action based on the item material, if it's not usable, will return null - /// - private static PermissableAction GetPermissionFromUsableBlock(Material material) { - // Check for doors that might have diff material name in old version. - if (material.name().contains("DOOR") || material.name().contains("FENCE_GATE")) - return PermissableAction.DOOR; - if (material.name().toUpperCase().contains("BUTTON") || material.name().toUpperCase().contains("PRESSURE")) - return PermissableAction.BUTTON; - if (FactionsPlugin.getInstance().mc113) { - switch (material) { - case LEVER: - return PermissableAction.LEVER; - - case ACACIA_BUTTON: - case BIRCH_BUTTON: - case DARK_OAK_BUTTON: - case JUNGLE_BUTTON: - case OAK_BUTTON: - case SPRUCE_BUTTON: - case STONE_BUTTON: - return PermissableAction.BUTTON; - - 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: - return PermissableAction.DOOR; - - 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: - return PermissableAction.CONTAINER; - default: - return null; - } - } else { - switch (material) { - case LEVER: - return PermissableAction.LEVER; - 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 OAK_FENCE_GATE: - case JUNGLE_FENCE_GATE: - case SPRUCE_FENCE_GATE: - return PermissableAction.DOOR; - 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: - return PermissableAction.CONTAINER; - default: - return null; - } - } - } - - @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(FactionsPlugin.getInstance(), () -> { - if (me.isOnline()) { - me.getFaction().sendUnreadAnnouncements(me); - } - }, 33L); // Don't ask me why. - - if (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-enabled", false)) { - FScoreboard.init(me); - FScoreboard.get(me).setDefaultSidebar(new FDefaultSidebar(), FactionsPlugin.getInstance().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(FactionsPlugin.getInstance(), () -> fallMap.remove(me.getPlayer()), 180L); - - - if (me.isSpyingChat() && !player.hasPermission(Permission.CHATSPY.node)) { - me.setSpyingChat(false); - FactionsPlugin.getInstance().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); - FactionsPlugin.getInstance().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 (FactionsPlugin.getInstance().getStuckMap().containsKey(me.getPlayer().getUniqueId())) { - FPlayers.getInstance().getByPlayer(me.getPlayer()).msg(TL.COMMAND_STUCK_CANCELLED); - FactionsPlugin.getInstance().getStuckMap().remove(me.getPlayer().getUniqueId()); - FactionsPlugin.getInstance().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 (!me.getPlayer().hasPermission("factions.fly")) return; - - if (FactionsPlugin.getInstance().getConfig().getBoolean("ffly.AutoEnable")) { - me.setFlying(true); - CmdFly.flyMap.put(me.getName(), true); - if (CmdFly.id == -1) { - if (FactionsPlugin.getInstance().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); + HashMap fallMap = new HashMap<>(); + private Set corners; + // 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() { + this.corners = new HashSet<>(); + for (Player player : FactionsPlugin.getInstance().getServer().getOnlinePlayers()) { + initPlayer(player); + } + for (World world : FactionsPlugin.getInstance().getServer().getWorlds()) { + WorldBorder border = world.getWorldBorder(); + if (border != null) { + int cornerCoord = (int) ((border.getSize() - 1.0) / 2.0); + this.corners.add(new FLocation(world.getName(), FLocation.blockToChunk(cornerCoord), FLocation.blockToChunk(cornerCoord))); + this.corners.add(new FLocation(world.getName(), FLocation.blockToChunk(cornerCoord), FLocation.blockToChunk(-cornerCoord))); + this.corners.add(new FLocation(world.getName(), FLocation.blockToChunk(-cornerCoord), FLocation.blockToChunk(cornerCoord))); + this.corners.add(new FLocation(world.getName(), FLocation.blockToChunk(-cornerCoord), FLocation.blockToChunk(-cornerCoord))); + } + } + } + + 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(TL.ACTIONS_OWNEDTERRITORYDENY.toString().replace("{owners}", myFaction.getOwnerListString(loc))); + } + return false; + } + + if (me.getFaction() == otherFaction) return true; + + if (FactionsPlugin.getInstance().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); + return CheckPlayerAccess(player, me, loc, otherFaction, access, PermissableAction.ITEM, false); + } + + @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.isSystemFaction()) return true; + if (myFaction.isWilderness()) { + me.msg(TL.GENERIC_NOPERMISSION, TL.GENERIC_DOTHAT); + return false; + } + + if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) + return true; + + if (otherFaction.getId().equals(myFaction.getId()) && me.getRole() == Role.LEADER) return true; + PermissableAction action = GetPermissionFromUsableBlock(block); + if (action == null) return false; + // We only care about some material types. + /// Who was the idiot? + if (otherFaction.hasPlayersOnline()) { + if (Conf.territoryProtectedMaterials.contains(material)) { + return false; + } + } else { + if (Conf.territoryProtectedMaterialsWhenOffline.contains(material)) { + return false; + } + } + + // Move up access check to check for exceptions + if (!otherFaction.getId().equals(myFaction.getId())) { // If the faction target is not my own + // Get faction pain build access relation to me + boolean pain = !justCheck && otherFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW; + return CheckPlayerAccess(player, me, loc, otherFaction, otherFaction.getAccess(me, action), action, pain); + } else if (otherFaction.getId().equals(myFaction.getId())) { + return CheckPlayerAccess(player, me, loc, myFaction, myFaction.getAccess(me, action), action, (!justCheck && myFaction.getAccess(me, PermissableAction.PAIN_BUILD) == Access.ALLOW)); + } + return CheckPlayerAccess(player, me, loc, myFaction, otherFaction.getAccess(me, action), action, Conf.territoryPainBuild); + } + + + 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; + } + + /// + /// This checks if the current player can execute an action based on it's factions access and surroundings + /// It will grant access in the following priorities: + /// - If Faction Land is Owned and the Owner is the current player, or player is faction leader. + /// - If Faction Land is not Owned and my access value is not set to DENY + /// - If none of the filters above matches, then we consider access is set to ALLOW|UNDEFINED + /// This check does not performs any kind of bypass check (i.e.: me.isAdminBypassing()) + /// + /// The player entity which the check will be made upon + /// The Faction player object related to the player + /// The World location where the action is being executed + /// The faction of the player being checked + /// The current's faction access permission for the action + private static boolean CheckPlayerAccess(Player player, FPlayer me, FLocation loc, Faction factionToCheck, Access access, PermissableAction action, boolean pain) { + boolean doPain = pain && Conf.handleExploitInteractionSpam; + if (access != null && access != Access.UNDEFINED) { + // TODO: Update this once new access values are added other than just allow / deny. + boolean landOwned = (factionToCheck.doesLocationHaveOwnersSet(loc) && !factionToCheck.getOwnerList(loc).isEmpty()); + if ((landOwned && factionToCheck.getOwnerListString(loc).contains(player.getName())) || (me.getRole() == Role.LEADER && me.getFactionId().equals(factionToCheck.getId()))) { + return true; + } else if (landOwned && !factionToCheck.getOwnerListString(loc).contains(player.getName())) { + me.msg("You can't do that in this territory, it is owned by: " + factionToCheck.getOwnerListString(loc)); + if (doPain) { + player.damage(Conf.actionDeniedPainAmount); + } + return false; + } else if (!landOwned && access == Access.ALLOW) { + return true; + } else { + me.msg("You cannot " + action + " in the territory of " + factionToCheck.getTag(me.getFaction())); + return false; + } + } + // Approves any permission check if the player in question is a leader AND owns the faction. + if (me.getRole().equals(Role.LEADER) && me.getFaction().equals(factionToCheck)) return true; + if (factionToCheck != null) { + me.msg(TL.PLAYER_USE_TERRITORY, action, factionToCheck.getTag(me.getFaction())); + } + return false; + } + + /// + /// This will try to resolve a permission action based on the item material, if it's not usable, will return null + /// + private static PermissableAction GetPermissionFromUsableBlock(Block block) { + return GetPermissionFromUsableBlock(block.getType()); + } + + /// + /// This will try to resolve a permission action based on the item material, if it's not usable, will return null + /// + private static PermissableAction GetPermissionFromUsableBlock(Material material) { + // Check for doors that might have diff material name in old version. + if (material.name().contains("DOOR") || material.name().contains("FENCE_GATE")) + return PermissableAction.DOOR; + if (material.name().toUpperCase().contains("BUTTON") || material.name().toUpperCase().contains("PRESSURE")) + return PermissableAction.BUTTON; + if (FactionsPlugin.getInstance().mc113) { + switch (material) { + case LEVER: + return PermissableAction.LEVER; + + case ACACIA_BUTTON: + case BIRCH_BUTTON: + case DARK_OAK_BUTTON: + case JUNGLE_BUTTON: + case OAK_BUTTON: + case SPRUCE_BUTTON: + case STONE_BUTTON: + return PermissableAction.BUTTON; + + 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: + return PermissableAction.DOOR; + + 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: + return PermissableAction.CONTAINER; + default: + return null; + } + } else { + switch (material) { + case LEVER: + return PermissableAction.LEVER; + 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 OAK_FENCE_GATE: + case JUNGLE_FENCE_GATE: + case SPRUCE_FENCE_GATE: + return PermissableAction.DOOR; + 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: + return PermissableAction.CONTAINER; + default: + return null; + } + } + } + + @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(FactionsPlugin.getInstance(), () -> { + if (me.isOnline()) { + me.getFaction().sendUnreadAnnouncements(me); + } + }, 33L); // Don't ask me why. + + if (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-enabled", false)) { + FScoreboard.init(me); + FScoreboard.get(me).setDefaultSidebar(new FDefaultSidebar(), FactionsPlugin.getInstance().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(FactionsPlugin.getInstance(), () -> fallMap.remove(me.getPlayer()), 180L); + + + if (me.isSpyingChat() && !player.hasPermission(Permission.CHATSPY.node)) { + me.setSpyingChat(false); + FactionsPlugin.getInstance().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); + FactionsPlugin.getInstance().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 (FactionsPlugin.getInstance().getStuckMap().containsKey(me.getPlayer().getUniqueId())) { + FPlayers.getInstance().getByPlayer(me.getPlayer()).msg(TL.COMMAND_STUCK_CANCELLED); + FactionsPlugin.getInstance().getStuckMap().remove(me.getPlayer().getUniqueId()); + FactionsPlugin.getInstance().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 (!me.getPlayer().hasPermission("factions.fly")) return; + + if (FactionsPlugin.getInstance().getConfig().getBoolean("ffly.AutoEnable")) { + me.setFlying(true); + CmdFly.flyMap.put(me.getName(), true); + if (CmdFly.id == -1) { + if (FactionsPlugin.getInstance().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; - } - if (fplayer.getFaction() != Board.getInstance().getFactionAt(new FLocation(e.getPlayer().getLocation()))) { - fplayer.msg(TL.COMMAND_INSPECT_NOTINCLAIM); + } + 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; - } - } 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(i)); - player.sendMessage(rowFormat - .replace("{time}", convertTime(row.getTime())) - .replace("{action}", row.getActionString()) - .replace("{player}", row.getPlayer()) - .replace("{block-type}", row.getType().toString().toLowerCase())); - } - } - } + } + 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(i)); + 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 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); + } + } + } + } - 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"; - } + 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); + @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); - } - } + // 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; - } + // 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()); + // Did we change coord? + FLocation from = me.getLastStoodAt(); + FLocation to = new FLocation(event.getTo()); - if (from.equals(to)) { - return; - } + if (from.equals(to)) { + return; + } - // Yes we did change coord (: + // Yes we did change coord (: - me.setLastStoodAt(to); + me.setLastStoodAt(to); - // Did we change "host"(faction)? - Faction factionFrom = Board.getInstance().getFactionAt(from); - Faction factionTo = Board.getInstance().getFactionAt(to); - boolean changedFaction = (factionFrom != factionTo); + // 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 (FactionsPlugin.getInstance().getConfig().getBoolean("Title.Show-Title")) { - String title = FactionsPlugin.getInstance().getConfig().getString("Title.Format.Title"); - title = title.replace("{Faction}", factionTo.getColorTo(me) + factionTo.getTag()); - title = parseAllPlaceholders(title, factionTo, player); - String subTitle = FactionsPlugin.getInstance().getConfig().getString("Title.Format.Subtitle").replace("{Description}", factionTo.getDescription()).replace("{Faction}", factionTo.getColorTo(me) + factionTo.getTag()); - subTitle = parseAllPlaceholders(subTitle, factionTo, player); - if (!FactionsPlugin.getInstance().mc17) { - if (!FactionsPlugin.getInstance().mc18) { - me.getPlayer().sendTitle(FactionsPlugin.getInstance().color(title), FactionsPlugin.getInstance().color(subTitle), FactionsPlugin.getInstance().getConfig().getInt("Title.Options.FadeInTime"), - FactionsPlugin.getInstance().getConfig().getInt("Title.Options.ShowTime"), - FactionsPlugin.getInstance().getConfig().getInt("Title.Options.FadeOutTime")); + if (changedFaction) { + Bukkit.getServer().getPluginManager().callEvent(new FPlayerEnteredFactionEvent(factionTo, factionFrom, me)); + if (FactionsPlugin.getInstance().getConfig().getBoolean("Title.Show-Title")) { + String title = FactionsPlugin.getInstance().getConfig().getString("Title.Format.Title"); + title = title.replace("{Faction}", factionTo.getColorTo(me) + factionTo.getTag()); + title = parseAllPlaceholders(title, factionTo, player); + String subTitle = FactionsPlugin.getInstance().getConfig().getString("Title.Format.Subtitle").replace("{Description}", factionTo.getDescription()).replace("{Faction}", factionTo.getColorTo(me) + factionTo.getTag()); + subTitle = parseAllPlaceholders(subTitle, factionTo, player); + if (!FactionsPlugin.getInstance().mc17) { + if (!FactionsPlugin.getInstance().mc18) { + me.getPlayer().sendTitle(FactionsPlugin.getInstance().color(title), FactionsPlugin.getInstance().color(subTitle), FactionsPlugin.getInstance().getConfig().getInt("Title.Options.FadeInTime"), + FactionsPlugin.getInstance().getConfig().getInt("Title.Options.ShowTime"), + FactionsPlugin.getInstance().getConfig().getInt("Title.Options.FadeOutTime")); + } else { + me.getPlayer().sendTitle(FactionsPlugin.getInstance().color(title), FactionsPlugin.getInstance().color(subTitle)); + } + } + } + + // enable fly :) + if (FactionsPlugin.getInstance().factionsFlight && 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.getAutoClaimFor() != null) { + me.attemptClaim(me.getAutoClaimFor(), event.getTo(), true); + if (Conf.disableFlightOnFactionClaimChange && event.getPlayer().getGameMode() != GameMode.CREATIVE) + CmdFly.disableFlight(me); + } else if (me.isAutoSafeClaimEnabled()) { + if (!Permission.MANAGE_SAFE_ZONE.has(player)) { + me.setIsAutoSafeClaimEnabled(false); } else { - me.getPlayer().sendTitle(FactionsPlugin.getInstance().color(title), FactionsPlugin.getInstance().color(subTitle)); + if (!Board.getInstance().getFactionAt(to).isSafeZone()) { + Board.getInstance().setFactionAt(Factions.getInstance().getSafeZone(), to); + me.msg(TL.PLAYER_SAFEAUTO); + } } - } - } - - // enable fly :) - if (FactionsPlugin.getInstance().factionsFlight && 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.getAutoClaimFor() != null) { - me.attemptClaim(me.getAutoClaimFor(), event.getTo(), true); - if (Conf.disableFlightOnFactionClaimChange && event.getPlayer().getGameMode() != GameMode.CREATIVE) CmdFly.disableFlight(me); - } 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); + } } - } - } 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); + } + } + + + if (me.isMapAutoUpdating()) { + if (showTimes.containsKey(player.getUniqueId()) && (showTimes.get(player.getUniqueId()) > System.currentTimeMillis())) { + if (FactionsPlugin.getInstance().getConfig().getBoolean("findfactionsexploit.log", false)) { + FactionsPlugin.getInstance().log(Level.WARNING, "%s tried to show a faction map too soon and triggered exploit blocker.", player.getName()); } - } - } - } - - - if (me.isMapAutoUpdating()) { - if (showTimes.containsKey(player.getUniqueId()) && (showTimes.get(player.getUniqueId()) > System.currentTimeMillis())) { - if (FactionsPlugin.getInstance().getConfig().getBoolean("findfactionsexploit.log", false)) { - FactionsPlugin.getInstance().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() + FactionsPlugin.getInstance().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.hasNotificationsEnabled()) { - 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) && me.hasNotificationsEnabled()) { - if (!ownersTo.isEmpty()) { - me.sendMessage(TL.GENERIC_OWNERS.format(ownersTo)); - } else if (!TL.GENERIC_PUBLICLAND.toString().isEmpty()) { - me.sendMessage(TL.GENERIC_PUBLICLAND.toString()); + } else { + me.sendFancyMessage(Board.getInstance().getMap(me, to, player.getLocation().getYaw())); + showTimes.put(player.getUniqueId(), System.currentTimeMillis() + FactionsPlugin.getInstance().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.hasNotificationsEnabled()) { + 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) && me.hasNotificationsEnabled()) { + if (!ownersTo.isEmpty()) { + me.sendMessage(TL.GENERIC_OWNERS.format(ownersTo)); + } else if (!TL.GENERIC_PUBLICLAND.toString().isEmpty()) { + me.sendMessage(TL.GENERIC_PUBLICLAND.toString()); + } + } + } + } + } - @EventHandler - public void onClose(InventoryCloseEvent e) { - FPlayer fme = FPlayers.getInstance().getById(e.getPlayer().getUniqueId().toString()); - if (fme.isInVault()) - fme.setInVault(false); - } + @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) { - // only need to check right-clicks and physical as of MC 1.4+; good performance boost - if (event.getAction().equals(Action.LEFT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_AIR)) - return; - Block block = event.getClickedBlock(); - Player player = event.getPlayer(); - // Check if the material is bypassing protection - if (block == null) return; // clicked in air, apparently - if(event.getItem() != null) { - if (Conf.territoryBypassProtectedMaterials.contains(event.getItem().getType())) return; - } - if (GetPermissionFromUsableBlock(event.getClickedBlock().getType()) != null) { - if (!canPlayerUseBlock(player, block, false)) { - event.setCancelled(true); - event.setUseInteractedBlock(Event.Result.DENY); - return; - } - } - if (event.getPlayer().getItemInHand() != null) { - Material handItem = event.getPlayer().getItemInHand().getType(); - if (handItem.isEdible() - || handItem.equals(XMaterial.POTION.parseMaterial()) - || handItem.equals(XMaterial.LINGERING_POTION.parseMaterial()) - || handItem.equals(XMaterial.SPLASH_POTION.parseMaterial())) { - return; - } - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerInteract(PlayerInteractEvent event) { + // only need to check right-clicks and physical as of MC 1.4+; good performance boost + if (event.getAction().equals(Action.LEFT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_AIR)) + return; + Block block = event.getClickedBlock(); + Player player = event.getPlayer(); + // Check if the material is bypassing protection + if (block == null) return; // clicked in air, apparently + if (event.getItem() != null) { + if (Conf.territoryBypassProtectedMaterials.contains(event.getItem().getType())) return; + } + if (GetPermissionFromUsableBlock(event.getClickedBlock().getType()) != null) { + if (!canPlayerUseBlock(player, block, false)) { + event.setCancelled(true); + event.setUseInteractedBlock(Event.Result.DENY); + return; + } + } + if (event.getPlayer().getItemInHand() != null) { + Material handItem = event.getPlayer().getItemInHand().getType(); + if (handItem.isEdible() + || handItem.equals(XMaterial.POTION.parseMaterial()) + || handItem.equals(XMaterial.LINGERING_POTION.parseMaterial()) + || handItem.equals(XMaterial.SPLASH_POTION.parseMaterial())) { + return; + } + } - if (event.getItem() == null) return; - if (!playerCanUseItemHere(player, block.getLocation(), event.getItem().getType(), false)) { - event.setCancelled(true); - event.setUseInteractedBlock(Event.Result.DENY); - } - } + if (event.getItem() == null) return; + if (!playerCanUseItemHere(player, block.getLocation(), event.getItem().getType(), false)) { + event.setCancelled(true); + event.setUseInteractedBlock(Event.Result.DENY); + } + } - @EventHandler - public void onInentorySee(InventoryClickEvent e) { - if (e.getCurrentItem() == null) - return; + @EventHandler + public void onInentorySee(InventoryClickEvent e) { + if (e.getCurrentItem() == null) + return; - if (!e.getView().getTitle().endsWith("'s Inventory")) - return; + if (!e.getView().getTitle().endsWith("'s Inventory")) + return; - e.setCancelled(true); - } + e.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() == XMaterial.GRASS_BLOCK.parseMaterial() - && event.hasItem() && event.getItem().getType() == XMaterial.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() == XMaterial.GRASS_BLOCK.parseMaterial() + && event.hasItem() && event.getItem().getType() == XMaterial.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(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", "use bone meal")); - event.setCancelled(true); - } - } - } + me.msg(TL.ACTIONS_NOPERMISSION.toString().replace("{faction}", myFaction.getTag(me.getFaction())).replace("{action}", "use bone meal")); + 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 - public void onLogoutMove(PlayerMoveEvent e) { - LogoutHandler handler = LogoutHandler.getByName(e.getPlayer().getName()); - if (handler.isLogoutActive(e.getPlayer())) { - handler.cancelLogout(e.getPlayer()); - e.getPlayer().sendMessage(String.valueOf(TL.COMMAND_LOGOUT_MOVED)); - } - } + @EventHandler + public void onLogoutMove(PlayerMoveEvent e) { + LogoutHandler handler = LogoutHandler.getByName(e.getPlayer().getName()); + if (handler.isLogoutActive(e.getPlayer())) { + handler.cancelLogout(e.getPlayer()); + e.getPlayer().sendMessage(String.valueOf(TL.COMMAND_LOGOUT_MOVED)); + } + } - @EventHandler - public void onDamage(EntityDamageEvent e) { - if (e.getEntity() instanceof Player) { - Player player = (Player) e.getEntity(); - LogoutHandler handler = LogoutHandler.getByName(player.getName()); - if (handler.isLogoutActive(player)) { - handler.cancelLogout(player); - player.sendMessage(String.valueOf(TL.COMMAND_LOGOUT_DAMAGE_TAKEN)); - } - } - } + @EventHandler + public void onDamage(EntityDamageEvent e) { + if (e.getEntity() instanceof Player) { + Player player = (Player) e.getEntity(); + LogoutHandler handler = LogoutHandler.getByName(player.getName()); + if (handler.isLogoutActive(player)) { + handler.cancelLogout(player); + player.sendMessage(String.valueOf(TL.COMMAND_LOGOUT_DAMAGE_TAKEN)); + } + } + } - @EventHandler - public void onTeleport(PlayerTeleportEvent e) { - Player player = e.getPlayer(); + @EventHandler + public void onTeleport(PlayerTeleportEvent e) { + Player player = e.getPlayer(); - if (player == null) return; - LogoutHandler handler = LogoutHandler.getByName(player.getName()); - if (handler.isLogoutActive(player)) { - handler.cancelLogout(player); - player.sendMessage(String.valueOf(TL.COMMAND_LOGOUT_TELEPORTED)); - } - } + if (player == null) return; + LogoutHandler handler = LogoutHandler.getByName(player.getName()); + if (handler.isLogoutActive(player)) { + handler.cancelLogout(player); + player.sendMessage(String.valueOf(TL.COMMAND_LOGOUT_TELEPORTED)); + } + } - @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()); + } - public Set getCorners() { - return this.corners; - } + public Set getCorners() { + return this.corners; + } - @EventHandler - public void AsyncPlayerChatEvent(AsyncPlayerChatEvent e) { - Player p = e.getPlayer(); + @EventHandler + public void AsyncPlayerChatEvent(AsyncPlayerChatEvent e) { + Player p = e.getPlayer(); - if (CmdFGlobal.toggled.contains(p.getUniqueId())) { - //they're muted, check status of Faction Chat - if (FPlayers.getInstance().getByPlayer(p).getFaction() == null) { - //they're muted, and not in a faction, cancel and return - e.setCancelled(true); - return; - } else { - //are in a faction that's not Wilderness, SafeZone, or Warzone, check their chat status - if (!FPlayers.getInstance().getByPlayer(p).getChatMode().isAtLeast(ChatMode.ALLIANCE)) { - //their Faction Chat Mode is not at-least a Alliance, cancel and return + if (CmdFGlobal.toggled.contains(p.getUniqueId())) { + //they're muted, check status of Faction Chat + if (FPlayers.getInstance().getByPlayer(p).getFaction() == null) { + //they're muted, and not in a faction, cancel and return e.setCancelled(true); return; - } - } - } + } else { + //are in a faction that's not Wilderness, SafeZone, or Warzone, check their chat status + if (!FPlayers.getInstance().getByPlayer(p).getChatMode().isAtLeast(ChatMode.ALLIANCE)) { + //their Faction Chat Mode is not at-least a Alliance, cancel and return + e.setCancelled(true); + return; + } + } + } - //we made it this far, since we didn't return yet, we must have sent the chat event through - //iterate through all of recipients and check if they're muted, then remove them from the event list + //we made it this far, since we didn't return yet, we must have sent the chat event through + //iterate through all of recipients and check if they're muted, then remove them from the event list - List l = new ArrayList<>(e.getRecipients()); + List l = new ArrayList<>(e.getRecipients()); - for (int i = l.size() - 1; i >= 0; i--) { // going backwards in the list to prevent a ConcurrentModificationException - Player recipient = l.get(i); - if (recipient != null) { - if (CmdFGlobal.toggled.contains(recipient.getUniqueId())) { - e.getRecipients().remove(recipient); - } - } - } - } + for (int i = l.size() - 1; i >= 0; i--) { // going backwards in the list to prevent a ConcurrentModificationException + Player recipient = l.get(i); + if (recipient != null) { + if (CmdFGlobal.toggled.contains(recipient.getUniqueId())) { + e.getRecipients().remove(recipient); + } + } + } + } - 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/missions/CmdMissions.java b/src/main/java/com/massivecraft/factions/missions/CmdMissions.java index 6b816121..47cccdea 100644 --- a/src/main/java/com/massivecraft/factions/missions/CmdMissions.java +++ b/src/main/java/com/massivecraft/factions/missions/CmdMissions.java @@ -9,32 +9,32 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdMissions extends FCommand { - public CmdMissions() { - this.aliases.add("missions"); - this.aliases.add("mission"); - this.aliases.add("objectives"); - this.aliases.add("objective"); + public CmdMissions() { + this.aliases.add("missions"); + this.aliases.add("mission"); + this.aliases.add("objectives"); + this.aliases.add("objective"); - this.requirements = new CommandRequirements.Builder(Permission.MISSIONS) - .memberOnly() - .playerOnly() - .build(); - } + this.requirements = new CommandRequirements.Builder(Permission.MISSIONS) + .memberOnly() + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (context.faction == null) { - return; - } - final MissionGUI missionsGUI = new MissionGUI(FactionsPlugin.getInstance(), context.fPlayer); - missionsGUI.build(); - context.player.openInventory(missionsGUI.getInventory()); - } + @Override + public void perform(CommandContext context) { + if (context.faction == null) { + return; + } + final MissionGUI missionsGUI = new MissionGUI(FactionsPlugin.getInstance(), context.fPlayer); + missionsGUI.build(); + context.player.openInventory(missionsGUI.getInventory()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MISSION_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MISSION_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/missions/Mission.java b/src/main/java/com/massivecraft/factions/missions/Mission.java index 55e2cc3d..eea6ed3b 100644 --- a/src/main/java/com/massivecraft/factions/missions/Mission.java +++ b/src/main/java/com/massivecraft/factions/missions/Mission.java @@ -1,28 +1,28 @@ package com.massivecraft.factions.missions; public class Mission { - private long progress; - private String name; - private String type; + private long progress; + private String name; + private String type; - public Mission(String name, String type) { - this.name = name; - this.type = type; - } + public Mission(String name, String type) { + this.name = name; + this.type = type; + } - public long getProgress() { - return progress; - } + public long getProgress() { + return progress; + } - public void incrementProgress() { - ++progress; - } + public void incrementProgress() { + ++progress; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getType() { - return type; - } + public String getType() { + return type; + } } diff --git a/src/main/java/com/massivecraft/factions/missions/MissionGUI.java b/src/main/java/com/massivecraft/factions/missions/MissionGUI.java index 3e5163a6..7721f218 100644 --- a/src/main/java/com/massivecraft/factions/missions/MissionGUI.java +++ b/src/main/java/com/massivecraft/factions/missions/MissionGUI.java @@ -20,86 +20,86 @@ import java.util.List; import java.util.Map; public class MissionGUI implements FactionGUI { - private FactionsPlugin plugin; - private FPlayer fPlayer; - private Inventory inventory; - private Map slots; + private FactionsPlugin plugin; + private FPlayer fPlayer; + private Inventory inventory; + private Map slots; - public MissionGUI(FactionsPlugin plugin, FPlayer fPlayer) { - this.slots = new HashMap<>(); - this.plugin = plugin; - this.fPlayer = fPlayer; - this.inventory = plugin.getServer().createInventory(this, plugin.getConfig().getInt("MissionGUISize") * 9, plugin.color(plugin.getConfig().getString("Missions-GUI-Title"))); - } + public MissionGUI(FactionsPlugin plugin, FPlayer fPlayer) { + this.slots = new HashMap<>(); + this.plugin = plugin; + this.fPlayer = fPlayer; + this.inventory = plugin.getServer().createInventory(this, plugin.getConfig().getInt("MissionGUISize") * 9, plugin.color(plugin.getConfig().getString("Missions-GUI-Title"))); + } - @Override - public void onClick(int slot, ClickType action) { - ConfigurationSection configurationSection = plugin.getConfig().getConfigurationSection("Missions"); - if (configurationSection == null) { - return; - } - int max = plugin.getConfig().getInt("MaximumMissionsAllowedAtOnce"); - if (fPlayer.getFaction().getMissions().size() >= max) { - fPlayer.msg(TL.MISSION_MISSION_MAX_ALLOWED, max); - return; - } - String missionName = slots.get(slot); - if (missionName == null) { - return; - } - if (fPlayer.getFaction().getMissions().containsKey(missionName)) { - fPlayer.msg(TL.MISSION_MISSION_ACTIVE); - return; - } - ConfigurationSection section = configurationSection.getConfigurationSection(missionName); - if (section == null) { - return; - } - ConfigurationSection missionSection = section.getConfigurationSection("Mission"); - if (missionSection == null) { - return; - } - Mission mission = new Mission(missionName, missionSection.getString("Type")); - fPlayer.getFaction().getMissions().put(missionName, mission); - fPlayer.msg(TL.MISSION_MISSION_STARTED, fPlayer.describeTo(fPlayer.getFaction()), plugin.color(section.getString("Name"))); - build(); - fPlayer.getPlayer().openInventory(inventory); - } + @Override + public void onClick(int slot, ClickType action) { + ConfigurationSection configurationSection = plugin.getConfig().getConfigurationSection("Missions"); + if (configurationSection == null) { + return; + } + int max = plugin.getConfig().getInt("MaximumMissionsAllowedAtOnce"); + if (fPlayer.getFaction().getMissions().size() >= max) { + fPlayer.msg(TL.MISSION_MISSION_MAX_ALLOWED, max); + return; + } + String missionName = slots.get(slot); + if (missionName == null) { + return; + } + if (fPlayer.getFaction().getMissions().containsKey(missionName)) { + fPlayer.msg(TL.MISSION_MISSION_ACTIVE); + return; + } + ConfigurationSection section = configurationSection.getConfigurationSection(missionName); + if (section == null) { + return; + } + ConfigurationSection missionSection = section.getConfigurationSection("Mission"); + if (missionSection == null) { + return; + } + Mission mission = new Mission(missionName, missionSection.getString("Type")); + fPlayer.getFaction().getMissions().put(missionName, mission); + fPlayer.msg(TL.MISSION_MISSION_STARTED, fPlayer.describeTo(fPlayer.getFaction()), plugin.color(section.getString("Name"))); + build(); + fPlayer.getPlayer().openInventory(inventory); + } - @Override - public void build() { - ConfigurationSection configurationSection = plugin.getConfig().getConfigurationSection("Missions"); - if (configurationSection == null) { - return; - } - for (String key : configurationSection.getKeys(false)) { - ConfigurationSection section = configurationSection.getConfigurationSection(key); - int slot = section.getInt("Slot"); + @Override + public void build() { + ConfigurationSection configurationSection = plugin.getConfig().getConfigurationSection("Missions"); + if (configurationSection == null) { + return; + } + for (String key : configurationSection.getKeys(false)) { + ConfigurationSection section = configurationSection.getConfigurationSection(key); + int slot = section.getInt("Slot"); - ItemStack itemStack = XMaterial.matchXMaterial(section.getString("Material")).parseItem(); - ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', section.getString("Name"))); - List loreLines = new ArrayList<>(); - for (String line : section.getStringList("Lore")) { - loreLines.add(ChatColor.translateAlternateColorCodes('&', line)); - } - if (fPlayer.getFaction().getMissions().containsKey(key)) { - Mission mission = fPlayer.getFaction().getMissions().get(key); - itemMeta.addEnchant(Enchantment.SILK_TOUCH, 1, true); - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - loreLines.add(""); - loreLines.add(plugin.color(plugin.getConfig().getString("Mission-Progress-Format") - .replace("{progress}", String.valueOf(mission.getProgress())) - .replace("{total}", String.valueOf(section.getConfigurationSection("Mission").get("Amount"))))); - } - itemMeta.setLore(loreLines); - itemStack.setItemMeta(itemMeta); - inventory.setItem(slot, itemStack); - slots.put(slot, key); - } - } + ItemStack itemStack = XMaterial.matchXMaterial(section.getString("Material")).parseItem(); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', section.getString("Name"))); + List loreLines = new ArrayList<>(); + for (String line : section.getStringList("Lore")) { + loreLines.add(ChatColor.translateAlternateColorCodes('&', line)); + } + if (fPlayer.getFaction().getMissions().containsKey(key)) { + Mission mission = fPlayer.getFaction().getMissions().get(key); + itemMeta.addEnchant(Enchantment.SILK_TOUCH, 1, true); + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + loreLines.add(""); + loreLines.add(plugin.color(plugin.getConfig().getString("Mission-Progress-Format") + .replace("{progress}", String.valueOf(mission.getProgress())) + .replace("{total}", String.valueOf(section.getConfigurationSection("Mission").get("Amount"))))); + } + itemMeta.setLore(loreLines); + itemStack.setItemMeta(itemMeta); + inventory.setItem(slot, itemStack); + slots.put(slot, key); + } + } - public Inventory getInventory() { - return inventory; - } + public Inventory getInventory() { + return inventory; + } } diff --git a/src/main/java/com/massivecraft/factions/missions/MissionHandler.java b/src/main/java/com/massivecraft/factions/missions/MissionHandler.java index c756c14e..b4958bb8 100644 --- a/src/main/java/com/massivecraft/factions/missions/MissionHandler.java +++ b/src/main/java/com/massivecraft/factions/missions/MissionHandler.java @@ -4,14 +4,12 @@ import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.zcore.util.TL; -import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.entity.EntityBreedEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerFishEvent; @@ -20,91 +18,91 @@ import java.util.stream.Collectors; public class MissionHandler implements Listener { - private FactionsPlugin plugin; + private FactionsPlugin plugin; - public MissionHandler(FactionsPlugin plugin) { - this.plugin = plugin; - } + public MissionHandler(FactionsPlugin plugin) { + this.plugin = plugin; + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityDeath(EntityDeathEvent event) { - if (event.getEntity() == null || event.getEntity().getKiller() == null) { - return; - } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getEntity().getKiller()); - if (fPlayer == null) { - return; - } - List missions = fPlayer.getFaction().getMissions().values().stream().filter(mission -> mission.getType().equalsIgnoreCase("kill")).collect(Collectors.toList()); - for (Mission mission2 : missions) { - ConfigurationSection section = plugin.getConfig().getConfigurationSection("Missions").getConfigurationSection(mission2.getName()); - if (!event.getEntityType().toString().equals(section.getConfigurationSection("Mission").getString("EntityType"))) { - continue; - } - mission2.incrementProgress(); - checkIfDone(fPlayer, mission2, section); - } - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityDeath(EntityDeathEvent event) { + if (event.getEntity() == null || event.getEntity().getKiller() == null) { + return; + } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getEntity().getKiller()); + if (fPlayer == null) { + return; + } + List missions = fPlayer.getFaction().getMissions().values().stream().filter(mission -> mission.getType().equalsIgnoreCase("kill")).collect(Collectors.toList()); + for (Mission mission2 : missions) { + ConfigurationSection section = plugin.getConfig().getConfigurationSection("Missions").getConfigurationSection(mission2.getName()); + if (!event.getEntityType().toString().equals(section.getConfigurationSection("Mission").getString("EntityType"))) { + continue; + } + mission2.incrementProgress(); + checkIfDone(fPlayer, mission2, section); + } + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (fPlayer == null) { - return; - } - List missions = fPlayer.getFaction().getMissions().values().stream().filter(mission -> mission.getType().equalsIgnoreCase("mine")).collect(Collectors.toList()); - for (Mission mission2 : missions) { - ConfigurationSection section = plugin.getConfig().getConfigurationSection("Missions").getConfigurationSection(mission2.getName()); - if (!event.getBlock().getType().toString().equals(section.getConfigurationSection("Mission").getString("Material"))) { - continue; - } - mission2.incrementProgress(); - checkIfDone(fPlayer, mission2, section); - } - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (fPlayer == null) { + return; + } + List missions = fPlayer.getFaction().getMissions().values().stream().filter(mission -> mission.getType().equalsIgnoreCase("mine")).collect(Collectors.toList()); + for (Mission mission2 : missions) { + ConfigurationSection section = plugin.getConfig().getConfigurationSection("Missions").getConfigurationSection(mission2.getName()); + if (!event.getBlock().getType().toString().equals(section.getConfigurationSection("Mission").getString("Material"))) { + continue; + } + mission2.incrementProgress(); + checkIfDone(fPlayer, mission2, section); + } + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (fPlayer == null) { - return; - } - List missions = fPlayer.getFaction().getMissions().values().stream().filter(mission -> mission.getType().equalsIgnoreCase("place")).collect(Collectors.toList()); - for (Mission mission2 : missions) { - ConfigurationSection section = plugin.getConfig().getConfigurationSection("Missions").getConfigurationSection(mission2.getName()); - if (!event.getBlock().getType().toString().equals(section.getConfigurationSection("Mission").getString("Material"))) { - continue; - } - mission2.incrementProgress(); - checkIfDone(fPlayer, mission2, section); - } - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (fPlayer == null) { + return; + } + List missions = fPlayer.getFaction().getMissions().values().stream().filter(mission -> mission.getType().equalsIgnoreCase("place")).collect(Collectors.toList()); + for (Mission mission2 : missions) { + ConfigurationSection section = plugin.getConfig().getConfigurationSection("Missions").getConfigurationSection(mission2.getName()); + if (!event.getBlock().getType().toString().equals(section.getConfigurationSection("Mission").getString("Material"))) { + continue; + } + mission2.incrementProgress(); + checkIfDone(fPlayer, mission2, section); + } + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerFish(PlayerFishEvent event) { - if (event.getState() != PlayerFishEvent.State.CAUGHT_FISH) { - return; - } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (fPlayer == null) { - return; - } - List missions = fPlayer.getFaction().getMissions().values().stream().filter(mission -> mission.getType().equalsIgnoreCase("fish")).collect(Collectors.toList()); - for (Mission mission2 : missions) { - ConfigurationSection section = plugin.getConfig().getConfigurationSection("Missions").getConfigurationSection(mission2.getName()); - mission2.incrementProgress(); - checkIfDone(fPlayer, mission2, section); - } - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerFish(PlayerFishEvent event) { + if (event.getState() != PlayerFishEvent.State.CAUGHT_FISH) { + return; + } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (fPlayer == null) { + return; + } + List missions = fPlayer.getFaction().getMissions().values().stream().filter(mission -> mission.getType().equalsIgnoreCase("fish")).collect(Collectors.toList()); + for (Mission mission2 : missions) { + ConfigurationSection section = plugin.getConfig().getConfigurationSection("Missions").getConfigurationSection(mission2.getName()); + mission2.incrementProgress(); + checkIfDone(fPlayer, mission2, section); + } + } - private void checkIfDone(FPlayer fPlayer, Mission mission, ConfigurationSection section) { - if (mission.getProgress() < section.getConfigurationSection("Mission").getLong("Amount")) { - return; - } - for (String command : section.getConfigurationSection("Reward").getStringList("Commands")) { - FactionsPlugin.getInstance().getServer().dispatchCommand(FactionsPlugin.getInstance().getServer().getConsoleSender(), command.replace("%faction%", fPlayer.getFaction().getTag())); - } - fPlayer.getFaction().getMissions().remove(mission.getName()); - fPlayer.getFaction().msg(TL.MISSION_MISSION_FINISHED, plugin.color(section.getString("Name"))); - } + private void checkIfDone(FPlayer fPlayer, Mission mission, ConfigurationSection section) { + if (mission.getProgress() < section.getConfigurationSection("Mission").getLong("Amount")) { + return; + } + for (String command : section.getConfigurationSection("Reward").getStringList("Commands")) { + FactionsPlugin.getInstance().getServer().dispatchCommand(FactionsPlugin.getInstance().getServer().getConsoleSender(), command.replace("%faction%", fPlayer.getFaction().getTag())); + } + fPlayer.getFaction().getMissions().remove(mission.getName()); + fPlayer.getFaction().msg(TL.MISSION_MISSION_FINISHED, plugin.color(section.getString("Name"))); + } } diff --git a/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java b/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java index d21d3898..d1841726 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 58c5d269..3df49cac 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(FactionsPlugin.getInstance(), updateInterval, updateInterval); - } + if (temporaryProvider == null) { + updateObjective(); + } + } + }.runTaskTimer(FactionsPlugin.getInstance(), 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(FactionsPlugin.getInstance(), FactionsPlugin.getInstance().getConfig().getInt("scoreboard.expiration", 7) * 20); - } + if (temporaryProvider == provider) { + temporaryProvider = null; + updateObjective(); + } + } + }.runTaskLater(FactionsPlugin.getInstance(), FactionsPlugin.getInstance().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 720df2ac..3638ce0f 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java @@ -11,32 +11,32 @@ import java.util.Objects; 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(Objects.requireNonNull(TagUtil.parsePlain(faction, fPlayer, s))); - } + return qualityAssure(Objects.requireNonNull(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 FactionsPlugin.getInstance().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 FactionsPlugin.getInstance().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 c91501b0..8bf33a39 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java @@ -12,212 +12,212 @@ 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 (!FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false) || FactionsPlugin.getInstance().getConfig().getBoolean("See-Invisible-Faction-Members")) { - return; - } + if (!FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false) || FactionsPlugin.getInstance().getConfig().getBoolean("See-Invisible-Faction-Members")) { + return; + } - if (updating.add(faction)) { - Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> { - updating.remove(faction); - applyUpdates(faction); - }); - } - } + if (updating.add(faction)) { + Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> { + 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 (!FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false) || FactionsPlugin.getInstance().getConfig().getBoolean("See-Invisible-Faction-Members")) { - return; - } + if (!FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false) || FactionsPlugin.getInstance().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 (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false)) { - for (FScoreboard fboard : teams.keySet()) { - updatePrefix(fboard); - } - } - } + private void updatePrefixes() { + if (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false)) { + for (FScoreboard fboard : teams.keySet()) { + updatePrefix(fboard); + } + } + } - private void updatePrefix(FScoreboard fboard) { - if (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false)) { - FPlayer fplayer = fboard.getFPlayer(); - Team team = teams.get(fboard); - boolean focused = false; + private void updatePrefix(FScoreboard fboard) { + if (FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-prefixes", false)) { + FPlayer fplayer = fboard.getFPlayer(); + Team team = teams.get(fboard); + boolean focused = false; - if (FactionsPlugin.getInstance().getConfig().getBoolean("See-Invisible-Faction-Members", false)) { - team.setCanSeeFriendlyInvisibles(true); - } + if (FactionsPlugin.getInstance().getConfig().getBoolean("See-Invisible-Faction-Members", false)) { + team.setCanSeeFriendlyInvisibles(true); + } - if ((FactionsPlugin.getInstance().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('&', FactionsPlugin.getInstance().getConfig().getString("ffocus.Prefix", "&7»&b"))); - focused = true; + if ((FactionsPlugin.getInstance().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('&', FactionsPlugin.getInstance().getConfig().getString("ffocus.Prefix", "&7»&b"))); + focused = true; + } } - } - } - if (!focused) { - String prefix = TL.DEFAULT_PREFIX.toString(); + } + 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 40903582..d355ea0a 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, FactionsPlugin.getInstance().getConfig().getString("scoreboard.default-title", "{name}")); - } + @Override + public String getTitle(FPlayer fplayer) { + return replaceTags(fplayer, FactionsPlugin.getInstance().getConfig().getString("scoreboard.default-title", "{name}")); + } - @Override - public List getLines(FPlayer fplayer) { - if (fplayer.hasFaction()) { - return getOutput(fplayer, "scoreboard.default"); - } else if (FactionsPlugin.getInstance().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 (FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().getConfig().getStringList(list); + public List getOutput(FPlayer fplayer, String list) { + List lines = FactionsPlugin.getInstance().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 56ccbb5f..12db848b 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 = FactionsPlugin.getInstance().getConfig().getStringList("scoreboard.finfo"); + @Override + public List getLines(FPlayer fplayer) { + List lines = FactionsPlugin.getInstance().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/shop/CmdShop.java b/src/main/java/com/massivecraft/factions/shop/CmdShop.java index a795308d..12f371e0 100644 --- a/src/main/java/com/massivecraft/factions/shop/CmdShop.java +++ b/src/main/java/com/massivecraft/factions/shop/CmdShop.java @@ -9,26 +9,26 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdShop extends FCommand { - public CmdShop() { - super(); - this.aliases.add("shop"); - this.requirements = new CommandRequirements.Builder(Permission.SHOP) - .memberOnly() - .playerOnly() - .build(); - } + public CmdShop() { + super(); + this.aliases.add("shop"); + this.requirements = new CommandRequirements.Builder(Permission.SHOP) + .memberOnly() + .playerOnly() + .build(); + } - @Override - public void perform(CommandContext context) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("F-Shop.Enabled")) { - return; - } - ShopGUI.openShop(context.fPlayer); - } + @Override + public void perform(CommandContext context) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("F-Shop.Enabled")) { + return; + } + ShopGUI.openShop(context.fPlayer); + } - @Override - public TL getUsageTranslation() { - return null; - } + @Override + public TL getUsageTranslation() { + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/shop/ShopClickPersistence.java b/src/main/java/com/massivecraft/factions/shop/ShopClickPersistence.java index 9387b0c9..871b8a7e 100644 --- a/src/main/java/com/massivecraft/factions/shop/ShopClickPersistence.java +++ b/src/main/java/com/massivecraft/factions/shop/ShopClickPersistence.java @@ -18,75 +18,75 @@ import java.util.List; public class ShopClickPersistence implements Listener { - public static String color(String line) { - line = ChatColor.translateAlternateColorCodes('&', line); - return line; - } + public static String color(String line) { + line = ChatColor.translateAlternateColorCodes('&', line); + return line; + } - public static List colorList(List lore) { - for (int i = 0; i <= lore.size() - 1; i++) { - lore.set(i, color(lore.get(i))); - } - return lore; - } + public static List colorList(List lore) { + for (int i = 0; i <= lore.size() - 1; i++) { + lore.set(i, color(lore.get(i))); + } + return lore; + } - public void runCommands(List list, Player p) { - for (String cmd : list) { - cmd = cmd.replace("%player%", p.getName()); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - } + public void runCommands(List list, Player p) { + for (String cmd : list) { + cmd = cmd.replace("%player%", p.getName()); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); + } + } - @EventHandler - public void click(InventoryClickEvent e) { - Inventory i = e.getClickedInventory(); - Player p = (Player) e.getWhoClicked(); - FileConfiguration config = FactionsPlugin.getInstance().getConfig(); - FPlayer fplayer = FPlayers.getInstance().getByPlayer(p); + @EventHandler + public void click(InventoryClickEvent e) { + Inventory i = e.getClickedInventory(); + Player p = (Player) e.getWhoClicked(); + FileConfiguration config = FactionsPlugin.getInstance().getConfig(); + FPlayer fplayer = FPlayers.getInstance().getByPlayer(p); - if (e.getView().getTitle().equalsIgnoreCase(color(config.getString("F-Shop.GUI.Name")))) { - ItemStack item = e.getCurrentItem(); - if (item == null) return; - String name = color(item.getItemMeta().getDisplayName()); - e.setCancelled(true); - int t = e.getSlot(); - int items = ShopConfig.getShop().getConfigurationSection("items").getKeys(false).size(); - for (int a = 1; a <= items; a++) { - String s = a + ""; - int slot = ShopConfig.getShop().getInt("items." + s + ".slot"); - if (t == slot) { - String n = ShopConfig.getShop().getString("items." + s + ".name"); - if (name.contains(color(n))) { - String c = ChatColor.stripColor(color(name)); - c = c.replace(ChatColor.stripColor(color(n)), ""); - c = c.replace(color(" ("), ""); - c = c.replace(color(" Points)"), ""); - int cost = Integer.parseInt(c); - if (fplayer.getFaction().getPoints() >= cost) { + if (e.getView().getTitle().equalsIgnoreCase(color(config.getString("F-Shop.GUI.Name")))) { + ItemStack item = e.getCurrentItem(); + if (item == null) return; + String name = color(item.getItemMeta().getDisplayName()); + e.setCancelled(true); + int t = e.getSlot(); + int items = ShopConfig.getShop().getConfigurationSection("items").getKeys(false).size(); + for (int a = 1; a <= items; a++) { + String s = a + ""; + int slot = ShopConfig.getShop().getInt("items." + s + ".slot"); + if (t == slot) { + String n = ShopConfig.getShop().getString("items." + s + ".name"); + if (name.contains(color(n))) { + String c = ChatColor.stripColor(color(name)); + c = c.replace(ChatColor.stripColor(color(n)), ""); + c = c.replace(color(" ("), ""); + c = c.replace(color(" Points)"), ""); + int cost = Integer.parseInt(c); + if (fplayer.getFaction().getPoints() >= cost) { - fplayer.getFaction().setPoints(fplayer.getFaction().getPoints() - cost); - runCommands(ShopConfig.getShop().getStringList("items." + s + ".cmds"), fplayer.getPlayer()); - for (FPlayer fplayerBuy : fplayer.getFaction().getFPlayers()) { - // if (fplayer == fme) { continue; } //Idk if I wanna not send the title to the player - fplayerBuy.getPlayer().sendMessage(TL.SHOP_BOUGHT_BROADCAST_FACTION.toString() - .replace("{player}", fplayer.getPlayer().getName()) - .replace("{item}", name)); - } - fplayer.sendMessage(color(ShopConfig.getShop().getString("prefix").replace("%item%", n).replace("%points%", cost + ""))); - p.closeInventory(); + fplayer.getFaction().setPoints(fplayer.getFaction().getPoints() - cost); + runCommands(ShopConfig.getShop().getStringList("items." + s + ".cmds"), fplayer.getPlayer()); + for (FPlayer fplayerBuy : fplayer.getFaction().getFPlayers()) { + // if (fplayer == fme) { continue; } //Idk if I wanna not send the title to the player + fplayerBuy.getPlayer().sendMessage(TL.SHOP_BOUGHT_BROADCAST_FACTION.toString() + .replace("{player}", fplayer.getPlayer().getName()) + .replace("{item}", name)); + } + fplayer.sendMessage(color(ShopConfig.getShop().getString("prefix").replace("%item%", n).replace("%points%", cost + ""))); + p.closeInventory(); - } else { - fplayer.sendMessage(TL.SHOP_NOT_ENOUGH_POINTS.toString()); - p.closeInventory(); - } - } else { - e.setCancelled(true); - return; + } else { + fplayer.sendMessage(TL.SHOP_NOT_ENOUGH_POINTS.toString()); + p.closeInventory(); + } + } else { + e.setCancelled(true); + return; + } } - } - } - } - } + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/shop/ShopConfig.java b/src/main/java/com/massivecraft/factions/shop/ShopConfig.java index c867b0a8..abff22e7 100644 --- a/src/main/java/com/massivecraft/factions/shop/ShopConfig.java +++ b/src/main/java/com/massivecraft/factions/shop/ShopConfig.java @@ -9,47 +9,47 @@ import java.util.ArrayList; public class ShopConfig { - //TODO: Shop YAML Converter mySQL + //TODO: Shop YAML Converter mySQL - public static File shop = new File("plugins/Factions/shop.yml"); - public static FileConfiguration s = YamlConfiguration.loadConfiguration(shop); + public static File shop = new File("plugins/Factions/shop.yml"); + public static FileConfiguration s = YamlConfiguration.loadConfiguration(shop); - public static FileConfiguration getShop() { - return s; - } + public static FileConfiguration getShop() { + return s; + } - public static void loadShop() { - s = YamlConfiguration.loadConfiguration(shop); - } + public static void loadShop() { + s = YamlConfiguration.loadConfiguration(shop); + } - public static void saveShop() { - try { - getShop().save(shop); - } catch (IOException e) { - e.printStackTrace(); - } - } + public static void saveShop() { + try { + getShop().save(shop); + } catch (IOException e) { + e.printStackTrace(); + } + } - public static void setup() { - if (!shop.exists()) { - try { - shop.createNewFile(); - getShop().set("prefix", "&4&lFactionShop&8» &7Purchased &f%item% &7for &b%points% Points&7!"); - getShop().set("items.1.slot", 1); - getShop().set("items.1.block", "STONE"); - getShop().set("items.1.name", "&aTest Shop"); - ArrayList lore = new ArrayList(); - lore.add("&cFully Customizable Lore!"); - getShop().set("items.1.lore", lore); - ArrayList t = new ArrayList(); - t.add("broadcast %player% bought Test Shop!"); - getShop().set("items.1.cmds", t); - getShop().set("items.1.cost", 5); - getShop().set("items.1.glowing", true); - saveShop(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } + public static void setup() { + if (!shop.exists()) { + try { + shop.createNewFile(); + getShop().set("prefix", "&4&lFactionShop&8» &7Purchased &f%item% &7for &b%points% Points&7!"); + getShop().set("items.1.slot", 1); + getShop().set("items.1.block", "STONE"); + getShop().set("items.1.name", "&aTest Shop"); + ArrayList lore = new ArrayList(); + lore.add("&cFully Customizable Lore!"); + getShop().set("items.1.lore", lore); + ArrayList t = new ArrayList(); + t.add("broadcast %player% bought Test Shop!"); + getShop().set("items.1.cmds", t); + getShop().set("items.1.cost", 5); + getShop().set("items.1.glowing", true); + saveShop(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/shop/ShopGUI.java b/src/main/java/com/massivecraft/factions/shop/ShopGUI.java index d5db5891..cbd704e6 100644 --- a/src/main/java/com/massivecraft/factions/shop/ShopGUI.java +++ b/src/main/java/com/massivecraft/factions/shop/ShopGUI.java @@ -22,79 +22,79 @@ public class ShopGUI { Made simplistic format for shop for the time being until I get time. */ - public static void openShop(FPlayer p) { - FileConfiguration config = FactionsPlugin.getInstance().getConfig(); - Faction fac = p.getFaction(); + public static void openShop(FPlayer p) { + FileConfiguration config = FactionsPlugin.getInstance().getConfig(); + Faction fac = p.getFaction(); - Inventory i = Bukkit.createInventory(null, FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Size"), color(config.getString("F-Shop.GUI.Name"))); - ItemStack glass = new ItemStack(XMaterial.BLACK_STAINED_GLASS_PANE.parseMaterial(), 1, (short) 7); - ItemMeta glassmeta = glass.getItemMeta(); - glassmeta.setDisplayName(ChatColor.GOLD + " "); - glass.setItemMeta(glassmeta); + Inventory i = Bukkit.createInventory(null, FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Size"), color(config.getString("F-Shop.GUI.Name"))); + ItemStack glass = new ItemStack(XMaterial.BLACK_STAINED_GLASS_PANE.parseMaterial(), 1, (short) 7); + ItemMeta glassmeta = glass.getItemMeta(); + glassmeta.setDisplayName(ChatColor.GOLD + " "); + glass.setItemMeta(glassmeta); - for (int fill = 0; fill < FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Size"); ++fill) { - i.setItem(fill, glass); - } + for (int fill = 0; fill < FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Size"); ++fill) { + i.setItem(fill, glass); + } - int items = ShopConfig.getShop().getConfigurationSection("items").getKeys(false).size(); - for (int shopitems = 1; shopitems <= items; shopitems++) { - String s = shopitems + ""; - int slot = ShopConfig.getShop().getInt("items." + s + ".slot"); - ItemStack material = XMaterial.matchXMaterial(ShopConfig.getShop().getString("items." + s + ".block")).parseItem(); - // int size = ShopConfig.getShop().getInt("items." + s + ".size"); - int cost = ShopConfig.getShop().getInt("items." + s + ".cost"); - String name = ShopConfig.getShop().getString("items." + s + ".name") + " &f(" + cost + " Points)"; - List lore = ShopConfig.getShop().getStringList("items." + s + ".lore"); - String command = ShopConfig.getShop().getString("items." + s + ".cmd"); - String type = ShopConfig.getShop().getString("items." + s + ".type"); - boolean glowing = ShopConfig.getShop().getBoolean("items." + s + ".glowing"); + int items = ShopConfig.getShop().getConfigurationSection("items").getKeys(false).size(); + for (int shopitems = 1; shopitems <= items; shopitems++) { + String s = shopitems + ""; + int slot = ShopConfig.getShop().getInt("items." + s + ".slot"); + ItemStack material = XMaterial.matchXMaterial(ShopConfig.getShop().getString("items." + s + ".block")).parseItem(); + // int size = ShopConfig.getShop().getInt("items." + s + ".size"); + int cost = ShopConfig.getShop().getInt("items." + s + ".cost"); + String name = ShopConfig.getShop().getString("items." + s + ".name") + " &f(" + cost + " Points)"; + List lore = ShopConfig.getShop().getStringList("items." + s + ".lore"); + String command = ShopConfig.getShop().getString("items." + s + ".cmd"); + String type = ShopConfig.getShop().getString("items." + s + ".type"); + boolean glowing = ShopConfig.getShop().getBoolean("items." + s + ".glowing"); - ItemStack count = new ItemStack(XMaterial.PAPER.parseMaterial(), 1); - ItemMeta countmeta = count.getItemMeta(); - countmeta.setDisplayName(color(config.getString("F-Shop.GUI.Information.name"))); - List PointInfo = new LinkedList<>(); - for (String list : config.getStringList("F-Shop.GUI.Information.lore")) { - PointInfo.add(list.replace("%points%", fac.getPoints() + "")); - } - countmeta.setLore(colorList(PointInfo)); - count.setItemMeta(countmeta); - i.setItem(FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Information.slot"), count); + ItemStack count = new ItemStack(XMaterial.PAPER.parseMaterial(), 1); + ItemMeta countmeta = count.getItemMeta(); + countmeta.setDisplayName(color(config.getString("F-Shop.GUI.Information.name"))); + List PointInfo = new LinkedList<>(); + for (String list : config.getStringList("F-Shop.GUI.Information.lore")) { + PointInfo.add(list.replace("%points%", fac.getPoints() + "")); + } + countmeta.setLore(colorList(PointInfo)); + count.setItemMeta(countmeta); + i.setItem(FactionsPlugin.getInstance().getConfig().getInt("F-Shop.GUI.Information.slot"), count); - ItemStack item = new ItemStack(material); - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(color(name)); - meta.addItemFlags(); + ItemStack item = new ItemStack(material); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(color(name)); + meta.addItemFlags(); - if (glowing) { - meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - meta.addEnchant(Enchantment.DURABILITY, 1, true); - } - if (!glowing) { - meta.removeEnchant(Enchantment.DURABILITY); - } + if (glowing) { + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + meta.addEnchant(Enchantment.DURABILITY, 1, true); + } + if (!glowing) { + meta.removeEnchant(Enchantment.DURABILITY); + } - if (lore.contains("")) { - meta.setLore(null); - } else { - meta.setLore(FactionsPlugin.getInstance().colorList(lore)); - } - item.setItemMeta(meta); - i.setItem(slot, item); - } - p.getPlayer().openInventory(i); - } + if (lore.contains("")) { + meta.setLore(null); + } else { + meta.setLore(FactionsPlugin.getInstance().colorList(lore)); + } + item.setItemMeta(meta); + i.setItem(slot, item); + } + p.getPlayer().openInventory(i); + } - public static String color(String line) { - line = ChatColor.translateAlternateColorCodes('&', line); - return line; - } + public static String color(String line) { + line = ChatColor.translateAlternateColorCodes('&', line); + return line; + } - public static List colorList(List lore) { - for (int i = 0; i <= lore.size() - 1; i++) { - lore.set(i, color(lore.get(i))); - } - return lore; - } + public static List colorList(List lore) { + for (int i = 0; i <= lore.size() - 1; i++) { + lore.set(i, color(lore.get(i))); + } + return lore; + } } diff --git a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerChunkLocationExpression.java b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerChunkLocationExpression.java index ca65fe11..39fd9208 100644 --- a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerChunkLocationExpression.java +++ b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerChunkLocationExpression.java @@ -12,42 +12,42 @@ import org.bukkit.event.Event; public class PlayerChunkLocationExpression extends SimpleExpression { - static { - Skript.registerExpression(PlayerChunkLocationExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction chunk at %player%", "[the] %player%['s] chunk"); - } + static { + Skript.registerExpression(PlayerChunkLocationExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction chunk at %player%", "[the] %player%['s] chunk"); + } - Expression playerExpression; + Expression playerExpression; - public Class getReturnType() { - return String.class; - } + public Class getReturnType() { + return String.class; + } - @Override - public boolean isSingle() { - return true; - } + @Override + public boolean isSingle() { + return true; + } - @Override - public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { - playerExpression = (Expression) exprs[0]; - return true; - } + @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 Location Expression with expression faction" + playerExpression.toString(event, debug); - } + @Override + public String toString(Event event, boolean debug) { + return "Player Location Expression with expression faction" + 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); - FLocation floc = new FLocation(fPlayer.getPlayer().getLocation()); - Faction fac = Board.getInstance().getFactionAt(floc); - return new String[]{String.valueOf(fac.getTag())}; - } - return null; - } + if (player != null) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + FLocation floc = new FLocation(fPlayer.getPlayer().getLocation()); + Faction fac = Board.getInstance().getFactionAt(floc); + return new String[]{String.valueOf(fac.getTag())}; + } + return null; + } } 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 794e55f2..22d11b66 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,78 +18,78 @@ 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(), false); - break; - case SET: - Faction faction = Factions.getInstance().getByTag((String) delta[0]); - if (faction == null) { - faction = Factions.getInstance().getWilderness(); - } - fPlayer.setFaction(faction, false); - break; - default: - } - } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + switch (mode) { + case DELETE: + case RESET: + fPlayer.setFaction(Factions.getInstance().getWilderness(), false); + break; + case SET: + Faction faction = Factions.getInstance().getByTag((String) delta[0]); + if (faction == null) { + faction = Factions.getInstance().getWilderness(); + } + fPlayer.setFaction(faction, false); + 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..16000a9a 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..7cbb0ca0 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..e7af166f 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..b7991cd3 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 38311d80..22caac2b 100644 --- a/src/main/java/com/massivecraft/factions/struct/Permission.java +++ b/src/main/java/com/massivecraft/factions/struct/Permission.java @@ -4,142 +4,142 @@ import com.massivecraft.factions.FactionsPlugin; import org.bukkit.command.CommandSender; public enum Permission { - MANAGE_SAFE_ZONE("managesafezone"), - MANAGE_WAR_ZONE("managewarzone"), - OWNERSHIP_BYPASS("ownershipbypass"), - ADMIN("admin"), - ALTS("alts"), - ADMIN_ANY("admin.any"), - AHOME("ahome"), - ANNOUNCE("announce"), - AUTOCLAIM("autoclaim"), - AUTO_LEAVE_BYPASS("autoleavebypass"), - BAN("ban"), - BYPASS("bypass"), - CHAT("chat"), - CHATSPY("chatspy"), - CHECK("check"), - CLAIM("claim"), - CLAIMAT("claimat"), - CLAIM_LINE("claim.line"), - CLAIM_RADIUS("claim.radius"), - CONFIG("config"), - CONVERT("convert"), - CONVERTCONFIG("convertconfig"), - CREATE("create"), - CORNER("corner"), - DEFAULTRANK("defaultrank"), - DEINVITE("deinvite"), - DELHOME("delhome"), - DESCRIPTION("description"), - DISBAND("disband"), - DISBAND_ANY("disband.any"), - FLY("fly"), - FOCUS("focus"), - GLOBALCHAT("globalchat"), - GRACE("grace"), - HELP("help"), - HOME("home"), - INVITE("invite"), - INVSEE("invsee"), - JOIN("join"), - JOIN_ANY("join.any"), - JOIN_OTHERS("join.others"), - KICK("kick"), - KICK_ANY("kick.any"), - LEAVE("leave"), - LIST("list"), - LOCK("lock"), - LOGOUT("logout"), - MAP("map"), - MAPHEIGHT("mapheight"), - MOD("mod"), - COLEADER("coleader"), - MOD_ANY("mod.any"), - COLEADER_ANY("coleader.any"), - MISSIONS("missions"), - 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"), - NEAR("near"), - NO_BOOM("noboom"), - OPEN("open"), - OWNER("owner"), - OWNERLIST("ownerlist"), - SET_PEACEFUL("setpeaceful"), - SET_PERMANENT("setpermanent"), - SET_PERMANENTPOWER("setpermanentpower"), - SHOW_INVITES("showinvites"), - PAYPAL("paypal"), - PAYPALSET("setpaypal"), - PERMISSIONS("permissions"), - POINTS("points"), - POWERBOOST("powerboost"), - POWER("power"), - POWER_ANY("power.any"), - PROMOTE("promote"), - RELATION("relation"), - RELOAD("reload"), - SAVE("save"), - SPAM("spam"), - SETHOME("sethome"), - SETHOME_ANY("sethome.any"), - SETSTRIKES("setstrikes"), - 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"), - SHOP("shop"), - TOP("top"), - VIEWCHEST("viewchest"), - ADDPOINTS("addpoints"), - REMOVEPOINTS("removepoints"), - SETPOINTS("setpoints"), - 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"); + MANAGE_SAFE_ZONE("managesafezone"), + MANAGE_WAR_ZONE("managewarzone"), + OWNERSHIP_BYPASS("ownershipbypass"), + ADMIN("admin"), + ALTS("alts"), + ADMIN_ANY("admin.any"), + AHOME("ahome"), + ANNOUNCE("announce"), + AUTOCLAIM("autoclaim"), + AUTO_LEAVE_BYPASS("autoleavebypass"), + BAN("ban"), + BYPASS("bypass"), + CHAT("chat"), + CHATSPY("chatspy"), + CHECK("check"), + CLAIM("claim"), + CLAIMAT("claimat"), + CLAIM_LINE("claim.line"), + CLAIM_RADIUS("claim.radius"), + CONFIG("config"), + CONVERT("convert"), + CONVERTCONFIG("convertconfig"), + CREATE("create"), + CORNER("corner"), + DEFAULTRANK("defaultrank"), + DEINVITE("deinvite"), + DELHOME("delhome"), + DESCRIPTION("description"), + DISBAND("disband"), + DISBAND_ANY("disband.any"), + FLY("fly"), + FOCUS("focus"), + GLOBALCHAT("globalchat"), + GRACE("grace"), + HELP("help"), + HOME("home"), + INVITE("invite"), + INVSEE("invsee"), + JOIN("join"), + JOIN_ANY("join.any"), + JOIN_OTHERS("join.others"), + KICK("kick"), + KICK_ANY("kick.any"), + LEAVE("leave"), + LIST("list"), + LOCK("lock"), + LOGOUT("logout"), + MAP("map"), + MAPHEIGHT("mapheight"), + MOD("mod"), + COLEADER("coleader"), + MOD_ANY("mod.any"), + COLEADER_ANY("coleader.any"), + MISSIONS("missions"), + 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"), + NEAR("near"), + NO_BOOM("noboom"), + OPEN("open"), + OWNER("owner"), + OWNERLIST("ownerlist"), + SET_PEACEFUL("setpeaceful"), + SET_PERMANENT("setpermanent"), + SET_PERMANENTPOWER("setpermanentpower"), + SHOW_INVITES("showinvites"), + PAYPAL("paypal"), + PAYPALSET("setpaypal"), + PERMISSIONS("permissions"), + POINTS("points"), + POWERBOOST("powerboost"), + POWER("power"), + POWER_ANY("power.any"), + PROMOTE("promote"), + RELATION("relation"), + RELOAD("reload"), + SAVE("save"), + SPAM("spam"), + SETHOME("sethome"), + SETHOME_ANY("sethome.any"), + SETSTRIKES("setstrikes"), + 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"), + SHOP("shop"), + TOP("top"), + VIEWCHEST("viewchest"), + ADDPOINTS("addpoints"), + REMOVEPOINTS("removepoints"), + SETPOINTS("setpoints"), + 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; + public final String node; - Permission(final String node) { - this.node = "factions." + node; - } + Permission(final String node) { + this.node = "factions." + node; + } - public boolean has(CommandSender sender, boolean informSenderIfNot) { - return FactionsPlugin.getInstance().perm.has(sender, this.node, informSenderIfNot); - } + public boolean has(CommandSender sender, boolean informSenderIfNot) { + return FactionsPlugin.getInstance().perm.has(sender, this.node, informSenderIfNot); + } - public boolean has(CommandSender sender) { - return has(sender, false); - } + public boolean has(CommandSender sender) { + return has(sender, false); + } } diff --git a/src/main/java/com/massivecraft/factions/struct/Placeholder.java b/src/main/java/com/massivecraft/factions/struct/Placeholder.java index a1b9a6cc..bbfc994a 100644 --- a/src/main/java/com/massivecraft/factions/struct/Placeholder.java +++ b/src/main/java/com/massivecraft/factions/struct/Placeholder.java @@ -3,21 +3,21 @@ package com.massivecraft.factions.struct; public class Placeholder { - private String tag; - private String replace; + private String tag; + private String replace; - public Placeholder(String tag, String replace) { - this.tag = tag; - this.replace = replace; - } + public Placeholder(String tag, String replace) { + this.tag = tag; + this.replace = replace; + } - public String getReplace() { - return replace; - } + public String getReplace() { + return replace; + } - public String getTag() { - return tag; - } + public String getTag() { + return tag; + } } diff --git a/src/main/java/com/massivecraft/factions/struct/Relation.java b/src/main/java/com/massivecraft/factions/struct/Relation.java index 7f32cb04..acd1b325 100644 --- a/src/main/java/com/massivecraft/factions/struct/Relation.java +++ b/src/main/java/com/massivecraft/factions/struct/Relation.java @@ -16,221 +16,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 = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation"); + // Utility method to build items for F Perm GUI + @Override + public ItemStack buildItem() { + final ConfigurationSection RELATION_CONFIG = FactionsPlugin.getInstance().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 = XMaterial.matchXMaterial(RELATION_CONFIG.getString("materials." + name().toLowerCase())).parseMaterial(); - if (material == null) { - return null; - } + Material material = XMaterial.matchXMaterial(RELATION_CONFIG.getString("materials." + name().toLowerCase())).parseMaterial(); + 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 cbf33bde..50775f9d 100644 --- a/src/main/java/com/massivecraft/factions/struct/Role.java +++ b/src/main/java/com/massivecraft/factions/struct/Role.java @@ -16,140 +16,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 = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation"); + // Utility method to build items for F Perm GUI + @Override + public ItemStack buildItem() { + final ConfigurationSection RELATION_CONFIG = FactionsPlugin.getInstance().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 = XMaterial.matchXMaterial(RELATION_CONFIG.getString("materials." + name().toLowerCase(), "STAINED_CLAY")).parseMaterial(); - if (material == null) { - return null; - } + Material material = XMaterial.matchXMaterial(RELATION_CONFIG.getString("materials." + name().toLowerCase(), "STAINED_CLAY")).parseMaterial(); + 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 (!FactionsPlugin.getInstance().mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - } + itemMeta.setDisplayName(displayName); + itemMeta.setLore(lore); + if (!FactionsPlugin.getInstance().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/tag/FactionTag.java b/src/main/java/com/massivecraft/factions/tag/FactionTag.java index 1224444e..c8098d60 100644 --- a/src/main/java/com/massivecraft/factions/tag/FactionTag.java +++ b/src/main/java/com/massivecraft/factions/tag/FactionTag.java @@ -12,124 +12,124 @@ import java.util.function.BiFunction; import java.util.function.Function; public enum FactionTag implements Tag { - HOME_X("{x}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : Tag.isMinimalShow() ? null : "{ig}"), - HOME_Y("{y}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : Tag.isMinimalShow() ? null : "{ig}"), - HOME_Z("{z}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : Tag.isMinimalShow() ? null : "{ig}"), - CHUNKS("{chunks}", (fac) -> String.valueOf(fac.getLandRounded())), - WARPS("{warps}", (fac) -> String.valueOf(fac.getWarps().size())), - HEADER("{header}", (fac, fp) -> FactionsPlugin.getInstance().txt.titleize(fac.getTag(fp))), - POWER("{power}", (fac) -> String.valueOf(fac.getPowerRounded())), - MAX_POWER("{maxPower}", (fac) -> String.valueOf(fac.getPowerMaxRounded())), - POWER_BOOST("{power-boost}", (fac) -> { - double powerBoost = fac.getPowerBoost(); - return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); - }), - LEADER("{leader}", (fac) -> { - FPlayer fAdmin = fac.getFPlayerAdmin(); - return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); - }), - JOINING("{joining}", (fac) -> (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString())), - FACTION("{faction}", (Function) Faction::getTag), - FACTION_RELATION_COLOR("{faction-relation-color}", (fac, fp) -> fp == null ? "" : fp.getColorTo(fac).toString()), - HOME_WORLD("{world}", (fac) -> fac.hasHome() ? fac.getHome().getWorld().getName() : Tag.isMinimalShow() ? null : "{ig}"), - RAIDABLE("{raidable}", (fac) -> { - if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false)) { - boolean raidable = fac.getLandRounded() >= fac.getPowerRounded(); - String str = raidable ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); - if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.dtr", false)) { - int dtr = raidable ? 0 : (int) Math.ceil(((double) (fac.getPowerRounded() - fac.getLandRounded())) / Conf.powerPerDeath); - str += ' ' + TL.COMMAND_SHOW_DEATHS_TIL_RAIDABLE.format(dtr); - } - return str; - } - return null; - }), - PEACEFUL("{peaceful}", (fac) -> fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""), - PERMANENT("permanent", (fac) -> fac.isPermanent() ? "permanent" : "{notPermanent}"), // no braces needed - LAND_VALUE("{land-value}", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("value")), - DESCRIPTION("{description}", Faction::getDescription), - CREATE_DATE("{create-date}", (fac) -> TL.sdf.format(fac.getFoundedDate())), - LAND_REFUND("{land-refund}", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("refund")), - BANK_BALANCE("{faction-balance}", (fac) -> { - if (Econ.shouldBeUsed()) { - return Conf.bankEnabled ? Econ.moneyString(Econ.getBalance(fac.getAccountId())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); - } - return Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); - }), - ALLIES_COUNT("{allies}", (fac) -> String.valueOf(fac.getRelationCount(Relation.ALLY))), - ENEMIES_COUNT("{enemies}", (fac) -> String.valueOf(fac.getRelationCount(Relation.ENEMY))), - TRUCES_COUNT("{truces}", (fac) -> String.valueOf(fac.getRelationCount(Relation.TRUCE))), - ONLINE_COUNT("{online}", (fac, fp) -> { - 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()); - } - }), - OFFLINE_COUNT("{offline}", (fac) -> String.valueOf(fac.getFPlayers().size() - fac.getOnlinePlayers().size())), - FACTION_SIZE("{members}", (fac) -> String.valueOf(fac.getFPlayers().size())), - FACTION_KILLS("{faction-kills}", (fac) -> String.valueOf(fac.getKills())), - FACTION_DEATHS("{faction-deaths}", (fac) -> String.valueOf(fac.getDeaths())), - FACTION_BANCOUNT("{faction-bancount}", (fac) -> String.valueOf(fac.getBannedPlayers().size())), - ; + HOME_X("{x}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : Tag.isMinimalShow() ? null : "{ig}"), + HOME_Y("{y}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : Tag.isMinimalShow() ? null : "{ig}"), + HOME_Z("{z}", (fac) -> fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : Tag.isMinimalShow() ? null : "{ig}"), + CHUNKS("{chunks}", (fac) -> String.valueOf(fac.getLandRounded())), + WARPS("{warps}", (fac) -> String.valueOf(fac.getWarps().size())), + HEADER("{header}", (fac, fp) -> FactionsPlugin.getInstance().txt.titleize(fac.getTag(fp))), + POWER("{power}", (fac) -> String.valueOf(fac.getPowerRounded())), + MAX_POWER("{maxPower}", (fac) -> String.valueOf(fac.getPowerMaxRounded())), + POWER_BOOST("{power-boost}", (fac) -> { + double powerBoost = fac.getPowerBoost(); + return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); + }), + LEADER("{leader}", (fac) -> { + FPlayer fAdmin = fac.getFPlayerAdmin(); + return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); + }), + JOINING("{joining}", (fac) -> (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString())), + FACTION("{faction}", (Function) Faction::getTag), + FACTION_RELATION_COLOR("{faction-relation-color}", (fac, fp) -> fp == null ? "" : fp.getColorTo(fac).toString()), + HOME_WORLD("{world}", (fac) -> fac.hasHome() ? fac.getHome().getWorld().getName() : Tag.isMinimalShow() ? null : "{ig}"), + RAIDABLE("{raidable}", (fac) -> { + if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.raidable", false)) { + boolean raidable = fac.getLandRounded() >= fac.getPowerRounded(); + String str = raidable ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); + if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.dtr", false)) { + int dtr = raidable ? 0 : (int) Math.ceil(((double) (fac.getPowerRounded() - fac.getLandRounded())) / Conf.powerPerDeath); + str += ' ' + TL.COMMAND_SHOW_DEATHS_TIL_RAIDABLE.format(dtr); + } + return str; + } + return null; + }), + PEACEFUL("{peaceful}", (fac) -> fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""), + PERMANENT("permanent", (fac) -> fac.isPermanent() ? "permanent" : "{notPermanent}"), // no braces needed + LAND_VALUE("{land-value}", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("value")), + DESCRIPTION("{description}", Faction::getDescription), + CREATE_DATE("{create-date}", (fac) -> TL.sdf.format(fac.getFoundedDate())), + LAND_REFUND("{land-refund}", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("refund")), + BANK_BALANCE("{faction-balance}", (fac) -> { + if (Econ.shouldBeUsed()) { + return Conf.bankEnabled ? Econ.moneyString(Econ.getBalance(fac.getAccountId())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); + } + return Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); + }), + ALLIES_COUNT("{allies}", (fac) -> String.valueOf(fac.getRelationCount(Relation.ALLY))), + ENEMIES_COUNT("{enemies}", (fac) -> String.valueOf(fac.getRelationCount(Relation.ENEMY))), + TRUCES_COUNT("{truces}", (fac) -> String.valueOf(fac.getRelationCount(Relation.TRUCE))), + ONLINE_COUNT("{online}", (fac, fp) -> { + 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()); + } + }), + OFFLINE_COUNT("{offline}", (fac) -> String.valueOf(fac.getFPlayers().size() - fac.getOnlinePlayers().size())), + FACTION_SIZE("{members}", (fac) -> String.valueOf(fac.getFPlayers().size())), + FACTION_KILLS("{faction-kills}", (fac) -> String.valueOf(fac.getKills())), + FACTION_DEATHS("{faction-deaths}", (fac) -> String.valueOf(fac.getDeaths())), + FACTION_BANCOUNT("{faction-bancount}", (fac) -> String.valueOf(fac.getBannedPlayers().size())), + ; - private final String tag; - private final BiFunction biFunction; - private final Function function; + private final String tag; + private final BiFunction biFunction; + private final Function function; - FactionTag(String tag, BiFunction function) { - this.tag = tag; - this.biFunction = function; - this.function = null; - } + FactionTag(String tag, BiFunction function) { + this.tag = tag; + this.biFunction = function; + this.function = null; + } - FactionTag(String tag, Function function) { - this.tag = tag; - this.biFunction = null; - this.function = function; - } + FactionTag(String tag, Function function) { + this.tag = tag; + this.biFunction = null; + this.function = function; + } - public static String parse(String text, Faction faction, FPlayer player) { - for (FactionTag tag : FactionTag.values()) { - text = tag.replace(text, faction, player); - } - return text; - } + public static String parse(String text, Faction faction, FPlayer player) { + for (FactionTag tag : FactionTag.values()) { + text = tag.replace(text, faction, player); + } + return text; + } - public static String parse(String text, Faction faction) { - for (FactionTag tag : FactionTag.values()) { - text = tag.replace(text, faction); - } - return text; - } + public static String parse(String text, Faction faction) { + for (FactionTag tag : FactionTag.values()) { + text = tag.replace(text, faction); + } + return text; + } - @Override - public String getTag() { - return this.tag; - } + @Override + public String getTag() { + return this.tag; + } - @Override - public boolean foundInString(String test) { - return test != null && test.contains(this.tag); - } + @Override + public boolean foundInString(String test) { + return test != null && test.contains(this.tag); + } - public String replace(String text, Faction faction, FPlayer player) { - if (!this.foundInString(text)) { - return text; - } - if (this.biFunction == null) { - return this.replace(text, faction); - } - String result = this.biFunction.apply(faction, player); - return result == null ? null : text.replace(this.tag, result); - } + public String replace(String text, Faction faction, FPlayer player) { + if (!this.foundInString(text)) { + return text; + } + if (this.biFunction == null) { + return this.replace(text, faction); + } + String result = this.biFunction.apply(faction, player); + return result == null ? null : text.replace(this.tag, result); + } - public String replace(String text, Faction faction) { - if (this.function == null || !this.foundInString(text)) { - return text; - } - String result = this.function.apply(faction); - return result == null ? null : text.replace(this.tag, result); - } + public String replace(String text, Faction faction) { + if (this.function == null || !this.foundInString(text)) { + return text; + } + String result = this.function.apply(faction); + return result == null ? null : text.replace(this.tag, result); + } } diff --git a/src/main/java/com/massivecraft/factions/tag/FancyTag.java b/src/main/java/com/massivecraft/factions/tag/FancyTag.java index 49e6beaf..09cf4da8 100644 --- a/src/main/java/com/massivecraft/factions/tag/FancyTag.java +++ b/src/main/java/com/massivecraft/factions/tag/FancyTag.java @@ -13,166 +13,166 @@ import org.bukkit.ChatColor; import java.util.*; public enum FancyTag implements Tag { - ALLIES_LIST("{allies-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ALLY)), - ENEMIES_LIST("{enemies-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ENEMY)), - TRUCES_LIST("{truces-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.TRUCE)), - ONLINE_LIST("{online-list}", (target, fme, prefix, gm) -> { - List fancyMessages = new ArrayList<>(); - FancyMessage currentOnline = FactionsPlugin.getInstance().txt.parseFancy(prefix); - boolean firstOnline = true; - for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) { - if (fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) { - continue; // skip - } - String name = p.getNameAndTitle(); - currentOnline.then(firstOnline ? name : ", " + name); - currentOnline.tooltip(tipPlayer(p, gm)).color(fme.getColorTo(p)); - firstOnline = false; - if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentOnline); - currentOnline = new FancyMessage(""); - } - } - fancyMessages.add(currentOnline); - return firstOnline && Tag.isMinimalShow() ? null : fancyMessages; - }), - OFFLINE_LIST("{offline-list}", (target, fme, prefix, gm) -> { - List fancyMessages = new ArrayList<>(); - FancyMessage currentOffline = FactionsPlugin.getInstance().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.getPlayer() != null && p.isOnline() && !fme.getPlayer().canSee(p.getPlayer()))) { - currentOffline.then(firstOffline ? name : ", " + name); - currentOffline.tooltip(tipPlayer(p, gm)).color(fme.getColorTo(p)); - firstOffline = false; - if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentOffline); - currentOffline = new FancyMessage(""); - } - } - } - fancyMessages.add(currentOffline); - return firstOffline && Tag.isMinimalShow() ? null : fancyMessages; - }), - ; - - private final String tag; - private final QuadFunction, List> function; - - FancyTag(String tag, QuadFunction, List> function) { - this.tag = tag; - this.function = function; - } - - private static List processRelation(String prefix, Faction faction, FPlayer fPlayer, Relation relation) { - List fancyMessages = new ArrayList<>(); - FancyMessage message = FactionsPlugin.getInstance().txt.parseFancy(prefix); - boolean first = true; - for (Faction otherFaction : Factions.getInstance().getAllFactions()) { - if (otherFaction == faction) { - continue; - } - String s = otherFaction.getTag(fPlayer); - if (otherFaction.getRelationTo(faction) == relation) { - message.then(first ? s : ", " + s); - message.tooltip(tipFaction(otherFaction, fPlayer)).color(fPlayer.getColorTo(otherFaction)); - first = false; - if (message.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(message); - message = new FancyMessage(""); - } - } - } - fancyMessages.add(message); - return first && Tag.isMinimalShow() ? null : fancyMessages; - } - - public static List parse(String text, Faction faction, FPlayer player, Map groupMap) { - for (FancyTag tag : FancyTag.values()) { - if (tag.foundInString(text)) { - return tag.getMessage(text, faction, player, groupMap); - } - } - return Collections.EMPTY_LIST; // We really shouldn't be here. - } - - public static boolean anyMatch(String text) { - return getMatch(text) != null; - } - - public static FancyTag getMatch(String text) { - for (FancyTag tag : FancyTag.values()) { - if (tag.foundInString(text)) { - return tag; - } - } - 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, FPlayer player) { - List lines = new ArrayList<>(); - for (String line : FactionsPlugin.getInstance().getConfig().getStringList("tooltips.list")) { - String string = Tag.parsePlain(faction, player, line); - if (string == null) { - continue; - } - lines.add(ChatColor.translateAlternateColorCodes('&', string)); - } - 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, Map groupMap) { - List lines = new ArrayList<>(); - for (String line : FactionsPlugin.getInstance().getConfig().getStringList("tooltips.show")) { - String newLine = line; - everythingOnYourWayOut: - if (line.contains("{group}")) { - if (groupMap != null) { - String group = groupMap.get(UUID.fromString(fplayer.getId())); - if (!group.trim().isEmpty()) { - newLine = newLine.replace("{group}", group); - break everythingOnYourWayOut; + ALLIES_LIST("{allies-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ALLY)), + ENEMIES_LIST("{enemies-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.ENEMY)), + TRUCES_LIST("{truces-list}", (target, fme, prefix, gm) -> processRelation(prefix, target, fme, Relation.TRUCE)), + ONLINE_LIST("{online-list}", (target, fme, prefix, gm) -> { + List fancyMessages = new ArrayList<>(); + FancyMessage currentOnline = FactionsPlugin.getInstance().txt.parseFancy(prefix); + boolean firstOnline = true; + for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) { + if (fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) { + continue; // skip + } + String name = p.getNameAndTitle(); + currentOnline.then(firstOnline ? name : ", " + name); + currentOnline.tooltip(tipPlayer(p, gm)).color(fme.getColorTo(p)); + firstOnline = false; + if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOnline); + currentOnline = new FancyMessage(""); + } + } + fancyMessages.add(currentOnline); + return firstOnline && Tag.isMinimalShow() ? null : fancyMessages; + }), + OFFLINE_LIST("{offline-list}", (target, fme, prefix, gm) -> { + List fancyMessages = new ArrayList<>(); + FancyMessage currentOffline = FactionsPlugin.getInstance().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.getPlayer() != null && p.isOnline() && !fme.getPlayer().canSee(p.getPlayer()))) { + currentOffline.then(firstOffline ? name : ", " + name); + currentOffline.tooltip(tipPlayer(p, gm)).color(fme.getColorTo(p)); + firstOffline = false; + if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOffline); + currentOffline = new FancyMessage(""); } - } - continue; - } - String string = Tag.parsePlain(fplayer, newLine); - if (string == null) { - continue; - } - lines.add(ChatColor.translateAlternateColorCodes('&', string)); - } - return lines; - } + } + } + fancyMessages.add(currentOffline); + return firstOffline && Tag.isMinimalShow() ? null : fancyMessages; + }), + ; - @Override - public String getTag() { - return this.tag; - } + private final String tag; + private final QuadFunction, List> function; - @Override - public boolean foundInString(String test) { - return test != null && test.contains(this.tag); - } + FancyTag(String tag, QuadFunction, List> function) { + this.tag = tag; + this.function = function; + } - public List getMessage(String text, Faction faction, FPlayer player, Map groupMap) { - if (!this.foundInString(text)) { - return Collections.EMPTY_LIST; // We really, really shouldn't be here. - } - return this.function.apply(faction, player, text.replace(this.getTag(), ""), groupMap); - } + private static List processRelation(String prefix, Faction faction, FPlayer fPlayer, Relation relation) { + List fancyMessages = new ArrayList<>(); + FancyMessage message = FactionsPlugin.getInstance().txt.parseFancy(prefix); + boolean first = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction == faction) { + continue; + } + String s = otherFaction.getTag(fPlayer); + if (otherFaction.getRelationTo(faction) == relation) { + message.then(first ? s : ", " + s); + message.tooltip(tipFaction(otherFaction, fPlayer)).color(fPlayer.getColorTo(otherFaction)); + first = false; + if (message.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(message); + message = new FancyMessage(""); + } + } + } + fancyMessages.add(message); + return first && Tag.isMinimalShow() ? null : fancyMessages; + } + + public static List parse(String text, Faction faction, FPlayer player, Map groupMap) { + for (FancyTag tag : FancyTag.values()) { + if (tag.foundInString(text)) { + return tag.getMessage(text, faction, player, groupMap); + } + } + return Collections.EMPTY_LIST; // We really shouldn't be here. + } + + public static boolean anyMatch(String text) { + return getMatch(text) != null; + } + + public static FancyTag getMatch(String text) { + for (FancyTag tag : FancyTag.values()) { + if (tag.foundInString(text)) { + return tag; + } + } + 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, FPlayer player) { + List lines = new ArrayList<>(); + for (String line : FactionsPlugin.getInstance().getConfig().getStringList("tooltips.list")) { + String string = Tag.parsePlain(faction, player, line); + if (string == null) { + continue; + } + lines.add(ChatColor.translateAlternateColorCodes('&', string)); + } + 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, Map groupMap) { + List lines = new ArrayList<>(); + for (String line : FactionsPlugin.getInstance().getConfig().getStringList("tooltips.show")) { + String newLine = line; + everythingOnYourWayOut: + if (line.contains("{group}")) { + if (groupMap != null) { + String group = groupMap.get(UUID.fromString(fplayer.getId())); + if (!group.trim().isEmpty()) { + newLine = newLine.replace("{group}", group); + break everythingOnYourWayOut; + } + } + continue; + } + String string = Tag.parsePlain(fplayer, newLine); + if (string == null) { + continue; + } + lines.add(ChatColor.translateAlternateColorCodes('&', string)); + } + return lines; + } + + @Override + public String getTag() { + return this.tag; + } + + @Override + public boolean foundInString(String test) { + return test != null && test.contains(this.tag); + } + + public List getMessage(String text, Faction faction, FPlayer player, Map groupMap) { + if (!this.foundInString(text)) { + return Collections.EMPTY_LIST; // We really, really shouldn't be here. + } + return this.function.apply(faction, player, text.replace(this.getTag(), ""), groupMap); + } } diff --git a/src/main/java/com/massivecraft/factions/tag/GeneralTag.java b/src/main/java/com/massivecraft/factions/tag/GeneralTag.java index 36d22286..93dbba1f 100644 --- a/src/main/java/com/massivecraft/factions/tag/GeneralTag.java +++ b/src/main/java/com/massivecraft/factions/tag/GeneralTag.java @@ -8,51 +8,51 @@ import org.bukkit.Bukkit; import java.util.function.Supplier; public enum GeneralTag implements Tag { - MAX_WARPS("{max-warps}", () -> String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-warps", 5))), - MAX_ALLIES("{max-allies}", () -> getRelation("ally")), - MAX_ENEMIES("{max-enemies}", () -> getRelation("enemy")), - MAX_TRUCES("{max-truces}", () -> getRelation("truce")), - FACTIONLESS("{factionless}", () -> String.valueOf(Factions.getInstance().getNone().getFPlayersWhereOnline(true).size())), - TOTAL_ONLINE("{total-online}", () -> String.valueOf(Bukkit.getOnlinePlayers().size())), - ; + MAX_WARPS("{max-warps}", () -> String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-warps", 5))), + MAX_ALLIES("{max-allies}", () -> getRelation("ally")), + MAX_ENEMIES("{max-enemies}", () -> getRelation("enemy")), + MAX_TRUCES("{max-truces}", () -> getRelation("truce")), + FACTIONLESS("{factionless}", () -> String.valueOf(Factions.getInstance().getNone().getFPlayersWhereOnline(true).size())), + TOTAL_ONLINE("{total-online}", () -> String.valueOf(Bukkit.getOnlinePlayers().size())), + ; - private final String tag; - private final Supplier supplier; + private final String tag; + private final Supplier supplier; - GeneralTag(String tag, Supplier supplier) { - this.tag = tag; - this.supplier = supplier; - } + GeneralTag(String tag, Supplier supplier) { + this.tag = tag; + this.supplier = supplier; + } - private static String getRelation(String relation) { - if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-relations." + relation, 10)); - } - return TL.GENERIC_INFINITY.toString(); - } + private static String getRelation(String relation) { + if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-relations." + relation, 10)); + } + return TL.GENERIC_INFINITY.toString(); + } - public static String parse(String text) { - for (GeneralTag tag : GeneralTag.values()) { - text = tag.replace(text); - } - return text; - } + public static String parse(String text) { + for (GeneralTag tag : GeneralTag.values()) { + text = tag.replace(text); + } + return text; + } - @Override - public String getTag() { - return this.tag; - } + @Override + public String getTag() { + return this.tag; + } - @Override - public boolean foundInString(String test) { - return test != null && test.contains(this.tag); - } + @Override + public boolean foundInString(String test) { + return test != null && test.contains(this.tag); + } - public String replace(String text) { - if (!this.foundInString(text)) { - return text; - } - String result = this.supplier.get(); - return result == null ? null : text.replace(this.tag, result); - } + public String replace(String text) { + if (!this.foundInString(text)) { + return text; + } + String result = this.supplier.get(); + return result == null ? null : text.replace(this.tag, result); + } } diff --git a/src/main/java/com/massivecraft/factions/tag/PlayerTag.java b/src/main/java/com/massivecraft/factions/tag/PlayerTag.java index d51cca19..ea669334 100644 --- a/src/main/java/com/massivecraft/factions/tag/PlayerTag.java +++ b/src/main/java/com/massivecraft/factions/tag/PlayerTag.java @@ -9,48 +9,48 @@ import org.bukkit.ChatColor; import java.util.function.Function; public enum PlayerTag implements Tag { - LAST_SEEN("{lastSeen}", (fp) -> { - String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; - return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); - }), - PLAYER_BALANCE("{balance}", (fp) -> Econ.isSetup() ? Econ.getFriendlyBalance(fp) : (Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"))), - PLAYER_POWER("{player-power}", (fp) -> String.valueOf(fp.getPowerRounded())), - PLAYER_MAXPOWER("{player-maxpower}", (fp) -> String.valueOf(fp.getPowerMaxRounded())), - PLAYER_KILLS("{player-kills}", (fp) -> String.valueOf(fp.getKills())), - PLAYER_DEATHS("{player-deaths}", (fp) -> String.valueOf(fp.getDeaths())), - PLAYER_NAME("{name}", FPlayer::getName), - ; + LAST_SEEN("{lastSeen}", (fp) -> { + String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; + return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); + }), + PLAYER_BALANCE("{balance}", (fp) -> Econ.isSetup() ? Econ.getFriendlyBalance(fp) : (Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"))), + PLAYER_POWER("{player-power}", (fp) -> String.valueOf(fp.getPowerRounded())), + PLAYER_MAXPOWER("{player-maxpower}", (fp) -> String.valueOf(fp.getPowerMaxRounded())), + PLAYER_KILLS("{player-kills}", (fp) -> String.valueOf(fp.getKills())), + PLAYER_DEATHS("{player-deaths}", (fp) -> String.valueOf(fp.getDeaths())), + PLAYER_NAME("{name}", FPlayer::getName), + ; - private final String tag; - private final Function function; + private final String tag; + private final Function function; - PlayerTag(String tag, Function function) { - this.tag = tag; - this.function = function; - } + PlayerTag(String tag, Function function) { + this.tag = tag; + this.function = function; + } - public static String parse(String text, FPlayer player) { - for (PlayerTag tag : PlayerTag.values()) { - text = tag.replace(text, player); - } - return text; - } + public static String parse(String text, FPlayer player) { + for (PlayerTag tag : PlayerTag.values()) { + text = tag.replace(text, player); + } + return text; + } - @Override - public String getTag() { - return this.tag; - } + @Override + public String getTag() { + return this.tag; + } - @Override - public boolean foundInString(String test) { - return test != null && test.contains(this.tag); - } + @Override + public boolean foundInString(String test) { + return test != null && test.contains(this.tag); + } - public String replace(String text, FPlayer player) { - if (!this.foundInString(text)) { - return text; - } - String result = this.function.apply(player); - return result == null ? null : text.replace(this.tag, result); - } + public String replace(String text, FPlayer player) { + if (!this.foundInString(text)) { + return text; + } + String result = this.function.apply(player); + return result == null ? null : text.replace(this.tag, result); + } } diff --git a/src/main/java/com/massivecraft/factions/tag/Tag.java b/src/main/java/com/massivecraft/factions/tag/Tag.java index 39b573e5..8ac05309 100644 --- a/src/main/java/com/massivecraft/factions/tag/Tag.java +++ b/src/main/java/com/massivecraft/factions/tag/Tag.java @@ -7,74 +7,74 @@ import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; public interface Tag { - int ARBITRARY_LIMIT = 25000; + 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 - */ - static String parsePlain(Faction faction, String line) { - return GeneralTag.parse(FactionTag.parse(line, faction)); - } + /** + * 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 + */ + static String parsePlain(Faction faction, String line) { + return GeneralTag.parse(FactionTag.parse(line, faction)); + } - /** - * 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 - */ - static String parsePlain(FPlayer fplayer, String line) { - return parsePlain(fplayer.getFaction(), fplayer, 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 + */ + static String parsePlain(FPlayer fplayer, String line) { + return parsePlain(fplayer.getFaction(), fplayer, 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 - */ - static String parsePlain(Faction faction, FPlayer fplayer, String line) { - return GeneralTag.parse(PlayerTag.parse(FactionTag.parse(line, faction, fplayer), fplayer)); - } + /** + * 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 + */ + static String parsePlain(Faction faction, FPlayer fplayer, String line) { + return GeneralTag.parse(PlayerTag.parse(FactionTag.parse(line, faction, fplayer), fplayer)); + } - static String parsePlaceholders(Player player, String line) { - if (player == null || line == null) { - return line; - } + static String parsePlaceholders(Player player, String line) { + if (player == null || line == null) { + return line; + } - if (FactionsPlugin.getInstance().isClipPlaceholderAPIHooked() && player.isOnline()) { - line = PlaceholderAPI.setPlaceholders(player, line); - } + if (FactionsPlugin.getInstance().isClipPlaceholderAPIHooked() && player.isOnline()) { + line = PlaceholderAPI.setPlaceholders(player, line); + } - if (FactionsPlugin.getInstance().isMVdWPlaceholderAPIHooked() && player.isOnline()) { - line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line); - } + if (FactionsPlugin.getInstance().isMVdWPlaceholderAPIHooked() && player.isOnline()) { + line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line); + } - return line; - } + return line; + } - static boolean isMinimalShow() { - return FactionsPlugin.getInstance().getConfig().getBoolean("minimal-show", false); - } + static boolean isMinimalShow() { + return FactionsPlugin.getInstance().getConfig().getBoolean("minimal-show", false); + } - /** - * Gets the Tag's string representation. - * - * @return tag - */ - String getTag(); + /** + * Gets the Tag's string representation. + * + * @return tag + */ + String getTag(); - /** - * Gets if the Tag can be found in the given String. - * - * @param test string to test - * @return true if the tag is found in this string - */ - boolean foundInString(String test); + /** + * Gets if the Tag can be found in the given String. + * + * @param test string to test + * @return true if the tag is found in this string + */ + boolean foundInString(String test); } diff --git a/src/main/java/com/massivecraft/factions/util/AsciiCompass.java b/src/main/java/com/massivecraft/factions/util/AsciiCompass.java index a4149c94..66b68248 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 33ca2fd2..86bd5292 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()) { - FactionsPlugin.getInstance().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()) { + FactionsPlugin.getInstance().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) { - FactionsPlugin.getInstance().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 (fplayer.isOffline() && now - fplayer.getLastLoginTime() > toleranceMillis) { + if (Conf.logFactionLeave || Conf.logFactionKick) { + FactionsPlugin.getInstance().log("Player " + fplayer.getName() + " was auto-removed due to inactivity."); } - } - fplayer.leave(false); - iterator.remove(); // go ahead and remove this list's link to the FPlayer object - if (Conf.autoLeaveDeleteFPlayerData) { - fplayer.remove(); - } - } - } + // 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); + } + } - // looks like we've finished - this.stop(); - } + fplayer.leave(false); + iterator.remove(); // go ahead and remove this list's link to the FPlayer object + if (Conf.autoLeaveDeleteFPlayerData) { + fplayer.remove(); + } + } + } - // we're done, shut down - public void stop() { - readyToGo = false; - finished = true; + // looks like we've finished + this.stop(); + } - this.cancel(); - } + // we're done, shut down + public void stop() { + readyToGo = false; + finished = true; - public boolean isFinished() { - return finished; - } + this.cancel(); + } + + 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 c24be121..b6290172 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.FactionsPlugin; 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(FactionsPlugin.getInstance(), 1, 1); + task = new AutoLeaveProcessTask(); + task.runTaskTimer(FactionsPlugin.getInstance(), 1, 1); - // maybe setting has been changed? if so, restart this task at new rate - if (this.rate != Conf.autoLeaveRoutineRunsEveryXMinutes) { - FactionsPlugin.getInstance().startAutoLeaveTask(true); - } - } + // maybe setting has been changed? if so, restart this task at new rate + if (this.rate != Conf.autoLeaveRoutineRunsEveryXMinutes) { + FactionsPlugin.getInstance().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 13b59e6f..89dab16a 100644 --- a/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java +++ b/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java @@ -15,163 +15,163 @@ 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 FactionsPlugin.getInstance().getDescription().getVersion(); - } + // Return the plugin version since this expansion is bundled with the dependency + @Override + public String getVersion() { + return FactionsPlugin.getInstance().getDescription().getVersion(); + } - @Override - public boolean persist() { - return true; - } + @Override + public boolean persist() { + return true; + } - // 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 FactionsPlugin.getInstance().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() : ""; - case "player_role_name": - return fPlayer.hasFaction() ? fPlayer.getRole().getTranslation().toString() : TL.PLACEHOLDER_ROLE_NAME.toString(); - // Then Faction stuff - case "faction_name": - return fPlayer.hasFaction() ? faction.getTag() : TL.NOFACTION_PREFIX.toString(); - 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_tntbank_balance": - return String.valueOf(faction.getTnt()); - case "faction_points": - return String.valueOf(faction.getPoints()); - 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 = FactionsPlugin.getInstance().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_grace": - return String.valueOf(Conf.gracePeriod); - 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 FactionsPlugin.getInstance().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() : ""; + case "player_role_name": + return fPlayer.hasFaction() ? fPlayer.getRole().getTranslation().toString() : TL.PLACEHOLDER_ROLE_NAME.toString(); + // Then Faction stuff + case "faction_name": + return fPlayer.hasFaction() ? faction.getTag() : TL.NOFACTION_PREFIX.toString(); + 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_tntbank_balance": + return String.valueOf(faction.getTnt()); + case "faction_points": + return String.valueOf(faction.getPoints()); + 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 = FactionsPlugin.getInstance().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_grace": + return String.valueOf(Conf.gracePeriod); + 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/CornerTask.java b/src/main/java/com/massivecraft/factions/util/CornerTask.java index 874bd158..d7af738a 100644 --- a/src/main/java/com/massivecraft/factions/util/CornerTask.java +++ b/src/main/java/com/massivecraft/factions/util/CornerTask.java @@ -8,27 +8,27 @@ import org.bukkit.scheduler.BukkitRunnable; import java.util.List; public class CornerTask extends BukkitRunnable { - private FPlayer fPlayer; - private List surrounding; - private int amount; + private FPlayer fPlayer; + private List surrounding; + private int amount; - public CornerTask(FPlayer fPlayer, List surrounding) { - this.amount = 0; - this.fPlayer = fPlayer; - this.surrounding = surrounding; - } + public CornerTask(FPlayer fPlayer, List surrounding) { + this.amount = 0; + this.fPlayer = fPlayer; + this.surrounding = surrounding; + } - public void run() { - if (surrounding.isEmpty()) { - fPlayer.sendMessage(TL.COMMAND_CORNER_CLAIMED.format(amount)); - cancel(); - } else if (fPlayer.isOffline()) { - cancel(); - } else { - FLocation fLocation = surrounding.remove(0); - if (fPlayer.attemptClaim(fPlayer.getFaction(), fLocation, true)) { - ++amount; - } - } - } + public void run() { + if (surrounding.isEmpty()) { + fPlayer.sendMessage(TL.COMMAND_CORNER_CLAIMED.format(amount)); + cancel(); + } else if (fPlayer.isOffline()) { + cancel(); + } else { + FLocation fLocation = surrounding.remove(0); + if (fPlayer.attemptClaim(fPlayer.getFaction(), fLocation, true)) { + ++amount; + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java index f5b2b975..d319ba55 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 c9d964ee..4b9d1312 100644 --- a/src/main/java/com/massivecraft/factions/util/FactionGUI.java +++ b/src/main/java/com/massivecraft/factions/util/FactionGUI.java @@ -5,8 +5,8 @@ import org.bukkit.inventory.InventoryHolder; public interface FactionGUI extends InventoryHolder { - 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/FactionWarpsFrame.java b/src/main/java/com/massivecraft/factions/util/FactionWarpsFrame.java index 1aa83f3f..5d2f38bf 100644 --- a/src/main/java/com/massivecraft/factions/util/FactionWarpsFrame.java +++ b/src/main/java/com/massivecraft/factions/util/FactionWarpsFrame.java @@ -21,92 +21,92 @@ import java.util.Map; public class FactionWarpsFrame { - private Gui gui; - private ConfigurationSection section; + private Gui gui; + private ConfigurationSection section; - public FactionWarpsFrame(final Faction f) { - this.section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fwarp-gui"); - this.gui = new Gui(FactionsPlugin.getInstance(), section.getInt("rows", 3), FactionsPlugin.getInstance().color(this.section.getString("name").replace("{faction}", f.getTag()))); - } + public FactionWarpsFrame(final Faction f) { + this.section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fwarp-gui"); + this.gui = new Gui(FactionsPlugin.getInstance(), section.getInt("rows", 3), FactionsPlugin.getInstance().color(this.section.getString("name").replace("{faction}", f.getTag()))); + } - public void buildGUI(final FPlayer fplayer) { - final PaginatedPane pane = new PaginatedPane(0, 0, 9, this.gui.getRows()); - final List GUIItems = new ArrayList<>(); - final List slots = section.getIntegerList("warp-slots"); - int count = 0; - for (int x = 0; x <= gui.getRows() * 9 - 1; ++x) - GUIItems.add(new GuiItem(buildDummyItem(), e -> e.setCancelled(true))); - slots.forEach(slot -> GUIItems.set(slot, new GuiItem(XMaterial.AIR.parseItem()))); - for (final Map.Entry warp : fplayer.getFaction().getWarps().entrySet()) { - if (count > slots.size()) continue; - GUIItems.set(slots.get(count), new GuiItem(buildWarpAsset(warp, fplayer.getFaction()), e -> { - e.setCancelled(true); - fplayer.getPlayer().closeInventory(); + public void buildGUI(final FPlayer fplayer) { + final PaginatedPane pane = new PaginatedPane(0, 0, 9, this.gui.getRows()); + final List GUIItems = new ArrayList<>(); + final List slots = section.getIntegerList("warp-slots"); + int count = 0; + for (int x = 0; x <= gui.getRows() * 9 - 1; ++x) + GUIItems.add(new GuiItem(buildDummyItem(), e -> e.setCancelled(true))); + slots.forEach(slot -> GUIItems.set(slot, new GuiItem(XMaterial.AIR.parseItem()))); + for (final Map.Entry warp : fplayer.getFaction().getWarps().entrySet()) { + if (count > slots.size()) continue; + GUIItems.set(slots.get(count), new GuiItem(buildWarpAsset(warp, fplayer.getFaction()), e -> { + e.setCancelled(true); + fplayer.getPlayer().closeInventory(); - if (!fplayer.getFaction().hasWarpPassword(warp.getKey())) { - if (transact(fplayer)) { - doWarmup(warp.getKey(), fplayer); + if (!fplayer.getFaction().hasWarpPassword(warp.getKey())) { + if (transact(fplayer)) { + doWarmup(warp.getKey(), fplayer); + } + } else { + fplayer.setEnteringPassword(true, warp.getKey()); + fplayer.msg(TL.COMMAND_FWARP_PASSWORD_REQUIRED); + Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> { + if (fplayer.isEnteringPassword()) { + fplayer.msg(TL.COMMAND_FWARP_PASSWORD_TIMEOUT); + fplayer.setEnteringPassword(false, ""); + } + }, FactionsPlugin.getInstance().getConfig().getInt("fwarp-gui.password-timeout", 5) * 20); } - } else { - fplayer.setEnteringPassword(true, warp.getKey()); - fplayer.msg(TL.COMMAND_FWARP_PASSWORD_REQUIRED); - Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> { - if (fplayer.isEnteringPassword()) { - fplayer.msg(TL.COMMAND_FWARP_PASSWORD_TIMEOUT); - fplayer.setEnteringPassword(false, ""); - } - }, FactionsPlugin.getInstance().getConfig().getInt("fwarp-gui.password-timeout", 5) * 20); - } - })); - ++count; - } - pane.populateWithGuiItems(GUIItems); - gui.addPane(pane); - gui.update(); - gui.show(fplayer.getPlayer()); - } + })); + ++count; + } + pane.populateWithGuiItems(GUIItems); + gui.addPane(pane); + gui.update(); + gui.show(fplayer.getPlayer()); + } - private ItemStack buildWarpAsset(final Map.Entry warp, final Faction faction) { - final ConfigurationSection config = this.section.getConfigurationSection("warp-item"); - final ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); - final ItemMeta meta = item.getItemMeta(); - meta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().replacePlaceholders(config.getStringList("Lore"), new Placeholder("{warp-protected}", faction.hasWarpPassword(warp.getKey()) ? "Enabled" : "Disabled"), new Placeholder("{warp-cost}", FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) ? Integer.toString(FactionsPlugin.getInstance().getConfig().getInt("warp-cost.warp", 5)) : "Disabled")))); - meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name").replace("{warp}", warp.getKey()))); - item.setItemMeta(meta); - return item; - } + private ItemStack buildWarpAsset(final Map.Entry warp, final Faction faction) { + final ConfigurationSection config = this.section.getConfigurationSection("warp-item"); + final ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); + final ItemMeta meta = item.getItemMeta(); + meta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().replacePlaceholders(config.getStringList("Lore"), new Placeholder("{warp-protected}", faction.hasWarpPassword(warp.getKey()) ? "Enabled" : "Disabled"), new Placeholder("{warp-cost}", FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) ? Integer.toString(FactionsPlugin.getInstance().getConfig().getInt("warp-cost.warp", 5)) : "Disabled")))); + meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name").replace("{warp}", warp.getKey()))); + item.setItemMeta(meta); + return item; + } - private ItemStack buildDummyItem() { - final ConfigurationSection config = this.section.getConfigurationSection("dummy-item"); - final ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); - final ItemMeta meta = item.getItemMeta(); - meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); - meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); - item.setItemMeta(meta); - return item; - } + private ItemStack buildDummyItem() { + final ConfigurationSection config = this.section.getConfigurationSection("dummy-item"); + final ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); + final ItemMeta meta = item.getItemMeta(); + meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); + meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); + item.setItemMeta(meta); + return item; + } - private void doWarmup(final String warp, FPlayer fme) { - WarmUpUtil.process(fme, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, () -> { - Player player = Bukkit.getPlayer(fme.getPlayer().getUniqueId()); - if (player != null) { - player.teleport(fme.getFaction().getWarp(warp).getLocation()); - fme.msg(TL.COMMAND_FWARP_WARPED, warp); - } - }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-warp", 0)); - } + private void doWarmup(final String warp, FPlayer fme) { + WarmUpUtil.process(fme, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, () -> { + Player player = Bukkit.getPlayer(fme.getPlayer().getUniqueId()); + if (player != null) { + player.teleport(fme.getFaction().getWarp(warp).getLocation()); + fme.msg(TL.COMMAND_FWARP_WARPED, warp); + } + }, FactionsPlugin.getInstance().getConfig().getLong("warmups.f-warp", 0)); + } - private boolean transact(FPlayer player) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing()) - return true; - double cost = FactionsPlugin.getInstance().getConfig().getDouble("warp-cost.warp", 5); - if (!Econ.shouldBeUsed() || cost == 0.0 || player.isAdminBypassing()) return true; + private boolean transact(FPlayer player) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing()) + return true; + double cost = FactionsPlugin.getInstance().getConfig().getDouble("warp-cost.warp", 5); + if (!Econ.shouldBeUsed() || cost == 0.0 || player.isAdminBypassing()) return true; - if (Conf.bankEnabled && Conf.bankFactionPaysCosts && player.hasFaction()) { - return Econ.modifyMoney(player.getFaction(), -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); - } else { - return Econ.modifyMoney(player, -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); - } - } + if (Conf.bankEnabled && Conf.bankFactionPaysCosts && player.hasFaction()) { + return Econ.modifyMoney(player.getFaction(), -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } else { + return Econ.modifyMoney(player, -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/InventoryTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/InventoryTypeAdapter.java index 0b941b1d..a78644fe 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..fd39ac37 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..c22ad7c1 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 d04383a0..09cf1e12 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().getName())); - return object; - } catch (Exception ex) { - ex.printStackTrace(); - FactionsPlugin.getInstance().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().getName())); + return object; + } catch (Exception ex) { + ex.printStackTrace(); + FactionsPlugin.getInstance().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(); - FactionsPlugin.getInstance().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(); + FactionsPlugin.getInstance().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 2006a898..6fd8f40a 100644 --- a/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java @@ -16,87 +16,87 @@ 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); - } - } - - return locationMap; - - } catch (Exception ex) { - ex.printStackTrace(); - FactionsPlugin.getInstance().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(); - - 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(); - - if (nameSet == null || nameSet.isEmpty()) { - continue; + locationMap.put(new FLocation(worldName, x, z), nameSet); } + } - nameArray = new JsonArray(); - iter = nameSet.iterator(); - while (iter.hasNext()) { - nameElement = new JsonPrimitive(iter.next()); - nameArray.add(nameElement); + return locationMap; + + } catch (Exception ex) { + ex.printStackTrace(); + FactionsPlugin.getInstance().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(); + + 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(); + + if (nameSet == null || nameSet.isEmpty()) { + continue; + } + + 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()); + } + + obj.get(locWorld).getAsJsonObject().add(loc.getCoordString(), nameArray); } + } + return obj; - if (!obj.has(locWorld)) { - obj.add(locWorld, new JsonObject()); - } - - obj.get(locWorld).getAsJsonObject().add(loc.getCoordString(), nameArray); - } - } - return obj; - - } catch (Exception ex) { - ex.printStackTrace(); - FactionsPlugin.getInstance().log(Level.WARNING, "Error encountered while serializing a Map of FLocations to String Sets."); - return obj; - } - } + } catch (Exception ex) { + ex.printStackTrace(); + FactionsPlugin.getInstance().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 18cf68a4..c53f644d 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(FactionsPlugin.getInstance().txt.parse(TL.GENERIC_FACTIONTAG_TOOSHORT.toString(), Conf.factionTagLengthMin)); - } + if (getComparisonString(str).length() < Conf.factionTagLengthMin) { + errors.add(FactionsPlugin.getInstance().txt.parse(TL.GENERIC_FACTIONTAG_TOOSHORT.toString(), Conf.factionTagLengthMin)); + } - if (str.length() > Conf.factionTagLengthMax) { - errors.add(FactionsPlugin.getInstance().txt.parse(TL.GENERIC_FACTIONTAG_TOOLONG.toString(), Conf.factionTagLengthMax)); - } + if (str.length() > Conf.factionTagLengthMax) { + errors.add(FactionsPlugin.getInstance().txt.parse(TL.GENERIC_FACTIONTAG_TOOLONG.toString(), Conf.factionTagLengthMax)); + } - for (char c : str.toCharArray()) { - if (!substanceChars.contains(String.valueOf(c))) { - errors.add(FactionsPlugin.getInstance().txt.parse(TL.GENERIC_FACTIONTAG_ALPHANUMERIC.toString(), c)); - } - } + for (char c : str.toCharArray()) { + if (!substanceChars.contains(String.valueOf(c))) { + errors.add(FactionsPlugin.getInstance().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); - FactionsPlugin.getInstance().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); + FactionsPlugin.getInstance().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/MyLocationTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java index 8ce59598..51c4bbfe 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(); - FactionsPlugin.getInstance().log(Level.WARNING, "Error encountered while deserializing a LazyLocation."); - return null; - } - } + } catch (Exception ex) { + ex.printStackTrace(); + FactionsPlugin.getInstance().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(); - FactionsPlugin.getInstance().log(Level.WARNING, "Error encountered while serializing a LazyLocation."); - return obj; - } - } + return obj; + } catch (Exception ex) { + ex.printStackTrace(); + FactionsPlugin.getInstance().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 4b58026a..2353a0c7 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 == XMaterial.WATER.parseMaterial(); - } - - /** - * 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) { + /** + * 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; - } - sendTo(center, player); - } - } + } + return entry.getValue(); + } + return null; + } - /** - * 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; + /** + * 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; + } - /** - * 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); - } - } + /** + * 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 == XMaterial.WATER.parseMaterial(); + } - /** - * 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; + /** + * 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; + } - /** - * 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); - } - } + /** + * 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); + } - /** - * 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; + /** + * 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); + } - /** - * 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); - } - } - } + /** + * 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/Particles.java b/src/main/java/com/massivecraft/factions/util/Particles/Particles.java index 2d7177a1..209624d6 100644 --- a/src/main/java/com/massivecraft/factions/util/Particles/Particles.java +++ b/src/main/java/com/massivecraft/factions/util/Particles/Particles.java @@ -8,52 +8,52 @@ import org.bukkit.Particle; public enum Particles { - // Gotta use Strings or runtime errors on 1.8, the Particle class does not exist - CLOUD(ParticleEffect.CLOUD, "CLOUD"), - REDSTONE(ParticleEffect.REDSTONE, "REDSTONE"), - NOTE(ParticleEffect.NOTE, "NOTE"); + // Gotta use Strings or runtime errors on 1.8, the Particle class does not exist + CLOUD(ParticleEffect.CLOUD, "CLOUD"), + REDSTONE(ParticleEffect.REDSTONE, "REDSTONE"), + NOTE(ParticleEffect.NOTE, "NOTE"); - private ParticleEffect sub18; - private String over19; + private ParticleEffect sub18; + private String over19; - Particles(ParticleEffect sub18, String over19) { - this.sub18 = sub18; - this.over19 = over19; - } + Particles(ParticleEffect sub18, String over19) { + this.sub18 = sub18; + this.over19 = over19; + } - public void displayAtLocation(Location location, int amt) { - if (FactionsPlugin.getInstance().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 - location.getWorld().spawnParticle(Particle.valueOf(over19), location, 0); - } else { - sub18.display((float) 0, (float) 0, (float) 0, (float) 0, amt, location, 16); - } - } + public void displayAtLocation(Location location, int amt) { + if (FactionsPlugin.getInstance().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 + location.getWorld().spawnParticle(Particle.valueOf(over19), location, 0); + } else { + sub18.display((float) 0, (float) 0, (float) 0, (float) 0, amt, location, 16); + } + } - public void displayAtLocation(Location location, int amt, ParticleEffect.OrdinaryColor color) { - if (FactionsPlugin.getInstance().useNonPacketParticles) { - // 1.9-1.11 & 1.13+ 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 + public void displayAtLocation(Location location, int amt, ParticleEffect.OrdinaryColor color) { + if (FactionsPlugin.getInstance().useNonPacketParticles) { + // 1.9-1.11 & 1.13+ 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 - // Gotta do this so colorable ones have their data :FactionsPlugin - if (this == Particles.REDSTONE || this == Particles.CLOUD || this == Particles.NOTE) { - if (FactionsPlugin.getInstance().mc112) { + // Gotta do this so colorable ones have their data :FactionsPlugin + if (this == Particles.REDSTONE || this == Particles.CLOUD || this == Particles.NOTE) { + if (FactionsPlugin.getInstance().mc112) { + location.getWorld().spawnParticle(Particle.valueOf(over19), location, 0); + } else { + location.getWorld().spawnParticle(Particle.valueOf(over19), location, 0, new Particle.DustOptions(Color.fromRGB(color.getRed(), color.getGreen(), color.getBlue()), 1)); + } + } else { location.getWorld().spawnParticle(Particle.valueOf(over19), location, 0); - } else { - location.getWorld().spawnParticle(Particle.valueOf(over19), location, 0, new Particle.DustOptions(Color.fromRGB(color.getRed(), color.getGreen(), color.getBlue()), 1)); - } - } else { - location.getWorld().spawnParticle(Particle.valueOf(over19), location, 0); - } - } else { - sub18.display(color, location, 16); + } + } else { + sub18.display(color, location, 16); - } - } + } + } } 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..050bb182 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 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 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 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 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); - } - - /** - * 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 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 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 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); - } - - /** - * 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; - - /** - * 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); - } - - /** - * 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 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; - } - } - - /** - * 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>(); - - // 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; - - /** - * 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 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 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 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; - } - - /** - * 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)) { + /** + * 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 false; - } - return true; - } + } + return constructor; + } + throw new NoSuchMethodException("There is no such constructor in this class with the specified parameter types"); + } - /** - * Returns the primitive class of this data type - * - * @return The primitive class - */ - public Class getPrimitive() { - return primitive; - } + /** + * 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 reference class of this data type - * - * @return The reference class - */ - public Class getReference() { - return reference; - } - } + /** + * 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 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); + } + + /** + * 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 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 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 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); + } + + /** + * 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 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"); + + 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 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 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); + } + + // 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); + + 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); + } + } + + 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; + } + + /** + * 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 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 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 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; + } + + /** + * 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; + } + } } \ 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 d5a7f661..1ccfaf50 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; - } - - Map> permissionsMap = new ConcurrentHashMap<>(); - - // Top level is Relation - for (Map.Entry entry : obj.entrySet()) { - Permissable permissable = getPermissable(entry.getKey()); - - 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); - } - - return permissionsMap; - - } catch (Exception ex) { - FactionsPlugin.getInstance().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")) { + try { + JsonObject obj = json.getAsJsonObject(); + if (obj == null) { return null; - } - return Relation.fromString(name); - } - } - } + } + + Map> permissionsMap = new ConcurrentHashMap<>(); + + // Top level is Relation + for (Map.Entry entry : obj.entrySet()) { + Permissable permissable = getPermissable(entry.getKey()); + + 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); + } + + return permissionsMap; + + } catch (Exception ex) { + FactionsPlugin.getInstance().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); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/Placeholder.java b/src/main/java/com/massivecraft/factions/util/Placeholder.java index 99db8eed..0f8f1aa1 100644 --- a/src/main/java/com/massivecraft/factions/util/Placeholder.java +++ b/src/main/java/com/massivecraft/factions/util/Placeholder.java @@ -2,21 +2,21 @@ package com.massivecraft.factions.util; public class Placeholder { - private String tag; - private String replace; + private String tag; + private String replace; - public Placeholder(String tag, String replace) { - this.tag = tag; - this.replace = replace; - } + public Placeholder(String tag, String replace) { + this.tag = tag; + this.replace = replace; + } - public String getReplace() { - return replace; - } + public String getReplace() { + return replace; + } - public String getTag() { - return tag; - } + public String getTag() { + return tag; + } } diff --git a/src/main/java/com/massivecraft/factions/util/QuadFunction.java b/src/main/java/com/massivecraft/factions/util/QuadFunction.java index a6a4e1fc..c2f2158c 100644 --- a/src/main/java/com/massivecraft/factions/util/QuadFunction.java +++ b/src/main/java/com/massivecraft/factions/util/QuadFunction.java @@ -2,5 +2,5 @@ package com.massivecraft.factions.util; @FunctionalInterface public interface QuadFunction { - R apply(T t, U u, V v, W w); + R apply(T t, U u, V v, W w); } diff --git a/src/main/java/com/massivecraft/factions/util/RelationUtil.java b/src/main/java/com/massivecraft/factions/util/RelationUtil.java index 4c656f84..83a8c49f 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 2733a423..753a69b0 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) { - FactionsPlugin.getInstance().log(Level.WARNING, "[SpiralTask] A valid world must be specified!"); - this.stop(); - return; - } + this.world = Bukkit.getWorld(fLocation.getWorldName()); + if (this.world == null) { + FactionsPlugin.getInstance().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(FactionsPlugin.getInstance(), this, 2, 2)); - } + // get this party started + this.setTaskID(Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), 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() { // FactionsPlugin.getInstance().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 5422ab77..d03b9953 100644 --- a/src/main/java/com/massivecraft/factions/util/UtilFly.java +++ b/src/main/java/com/massivecraft/factions/util/UtilFly.java @@ -11,87 +11,87 @@ import org.bukkit.Bukkit; public class UtilFly { - public static void run() { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) - return; + public static void run() { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) + return; - Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { - for (FPlayer fp : FPlayers.getInstance().getOnlinePlayers()) { - if (fp.isFlying()) - fp.checkIfNearbyEnemies(); - } - }, 0, FactionsPlugin.getInstance().getConfig().getInt("fly-task-interval", 10)); - } + Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.getInstance(), () -> { + for (FPlayer fp : FPlayers.getInstance().getOnlinePlayers()) { + if (fp.isFlying()) + fp.checkIfNearbyEnemies(); + } + }, 0, FactionsPlugin.getInstance().getConfig().getInt("fly-task-interval", 10)); + } - public static void setFly(FPlayer fp, boolean fly, boolean silent, boolean damage) { - if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) - return; + public static void setFly(FPlayer fp, boolean fly, boolean silent, boolean damage) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) + return; - fp.getPlayer().setAllowFlight(fly); - fp.getPlayer().setFlying(fly); - fp.setFlying(fly); + fp.getPlayer().setAllowFlight(fly); + fp.getPlayer().setFlying(fly); + fp.setFlying(fly); - 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 (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) - return; + public static void checkFly(FPlayer me, Faction factionTo) { + if (!FactionsPlugin.getInstance().getConfig().getBoolean("enable-faction-flight")) + return; - if (me.isAdminBypassing() && me.isFlying() && me.getPlayer().hasPermission("factions.fly.enemy-bypass")) - return; + if (me.isAdminBypassing() && me.isFlying() && me.getPlayer().hasPermission("factions.fly.enemy-bypass")) + return; - if (!me.isFlying()) { - if (me.isAdminBypassing() || me.getPlayer().hasPermission("factions.fly.enemy-bypass")) { - UtilFly.setFly(me, true, true, false); - return; - } + if (!me.isFlying()) { + if (me.isAdminBypassing() || me.getPlayer().hasPermission("factions.fly.enemy-bypass")) { + UtilFly.setFly(me, true, true, false); + return; + } - if (factionTo == me.getFaction() && me.getPlayer().hasPermission("factions.fly")) { - UtilFly.setFly(me, true, false, false); - } else { - 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())) { + if (factionTo == me.getFaction() && me.getPlayer().hasPermission("factions.fly")) { UtilFly.setFly(me, true, false, false); - } - } - } else { - Relation 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())) { - UtilFly.setFly(me, false, false, false); - } - } - } + } else { + 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())) { + UtilFly.setFly(me, true, false, false); + } + } + } else { + Relation 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())) { + UtilFly.setFly(me, false, false, false); + } + } + } - public static void setFallDamage(FPlayer fp, boolean fly, boolean damage) { - if (!fly) { - if (!damage) { - fp.sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3) + "")); - } + public static void setFallDamage(FPlayer fp, boolean fly, boolean damage) { + if (!fly) { + if (!damage) { + fp.sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3) + "")); + } - int cooldown = FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3); - if (cooldown > 0) { - fp.setTakeFallDamage(false); - Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> fp.setTakeFallDamage(true), 20L * cooldown); - } - } - } + int cooldown = FactionsPlugin.getInstance().getConfig().getInt("fly-falldamage-cooldown", 3); + if (cooldown > 0) { + fp.setTakeFallDamage(false); + Bukkit.getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> fp.setTakeFallDamage(true), 20L * cooldown); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java b/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java index 54825151..791710ef 100644 --- a/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java +++ b/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java @@ -9,60 +9,60 @@ 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.computeIfAbsent(uuid, k -> new HashSet<>()); - return ret; - } + public static Set getPlayerLocations(UUID uuid) { + Set ret = playerLocations.computeIfAbsent(uuid, k -> new HashSet<>()); + 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 3ddd57da..66667e58 100644 --- a/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java +++ b/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java @@ -6,34 +6,34 @@ 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 = FactionsPlugin.getInstance().getServer().getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> { - 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 = FactionsPlugin.getInstance().getServer().getScheduler().runTaskLater(FactionsPlugin.getInstance(), () -> { + 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/XMaterial.java b/src/main/java/com/massivecraft/factions/util/XMaterial.java index a238aa61..d58f7267 100644 --- a/src/main/java/com/massivecraft/factions/util/XMaterial.java +++ b/src/main/java/com/massivecraft/factions/util/XMaterial.java @@ -54,1564 +54,1564 @@ import java.util.regex.Pattern; * 1.13 and above as priority. */ public enum XMaterial { - ACACIA_BOAT(0, "BOAT_ACACIA"), - ACACIA_BUTTON(0, "WOOD_BUTTON"), - ACACIA_DOOR(0, "ACACIA_DOOR_ITEM"), - ACACIA_FENCE(0, ""), - ACACIA_FENCE_GATE(0, ""), - ACACIA_LEAVES(0, "LEAVES_2"), - ACACIA_LOG(0, "LOG_2"), - ACACIA_PLANKS(4, "WOOD"), - ACACIA_PRESSURE_PLATE(0, "WOOD_PLATE"), - ACACIA_SAPLING(4, "SAPLING"), - ACACIA_SIGN(0, "SIGN"), - ACACIA_SLAB(4, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - ACACIA_STAIRS(0, ""), - ACACIA_TRAPDOOR(0, "TRAP_DOOR"), - ACACIA_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), - ACACIA_WOOD(0, "LOG_2"), - ACTIVATOR_RAIL(0, ""), - AIR(0, ""), - ALLIUM(2, "RED_ROSE"), - ANDESITE(5, "STONEZ"), - ANDESITE_SLAB(0, ""), - ANDESITE_STAIRS(0, ""), - ANDESITE_WALL(0, ""), - ANVIL(0, ""), - APPLE(0, ""), - ARMOR_STAND(0, ""), - ARROW(0, ""), - ATTACHED_MELON_STEM(7, "MELON_STEM"), - ATTACHED_PUMPKIN_STEM(7, "PUMPKIN_STEM"), - AZURE_BLUET(3, "RED_ROSE"), - BAKED_POTATO(0, ""), - BAMBOO(0, "1.14", "SUGAR_CANE"), - BAMBOO_SAPLING(0, "1.14"), - BARREL(0, "1.14", "CHEST"), - BARRIER(0, ""), - BAT_SPAWN_EGG(65, "MONSTER_EGG"), - BEACON(0, ""), - BEDROCK(0, ""), - BEEF(0, "RAW_BEEF"), - BEETROOT(0, "BEETROOT_BLOCK"), - BEETROOTS(0, "BEETROOT"), - BEETROOT_SEEDS(0, ""), - BEETROOT_SOUP(0, ""), - BELL(0, "1.14"), - BIRCH_BOAT(0, "BOAT_BIRCH"), - BIRCH_BUTTON(0, "WOOD_BUTTON"), - BIRCH_DOOR(0, "BIRCH_DOOR_ITEM"), - BIRCH_FENCE(0, ""), - BIRCH_FENCE_GATE(0, ""), - BIRCH_LEAVES(2, "LEAVES"), - BIRCH_LOG(2, "LOG"), - BIRCH_PLANKS(2, "WOOD"), - BIRCH_PRESSURE_PLATE(0, "WOOD_PLATE"), - BIRCH_SAPLING(2, "SAPLING"), - BIRCH_SIGN(0, "SIGN"), - BIRCH_SLAB(2, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - BIRCH_STAIRS(0, "BIRCH_WOOD_STAIRS"), - BIRCH_TRAPDOOR(0, "TRAP_DOOR"), - BIRCH_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), - BIRCH_WOOD(2, "LOG"), - BLACK_BANNER(0, "BANNER", "STANDING_BANNER"), - BLACK_BED(15, "BED", "BED_BLOCK"), - BLACK_CARPET(15, "CARPET"), - BLACK_CONCRETE(15, "CONCRETE"), - BLACK_CONCRETE_POWDER(15, "CONCRETE_POWDER"), - BLACK_DYE(0, "1.14", "INK_SACK"), - BLACK_GLAZED_TERRACOTTA(15, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLACK_TERRACOTTA"), - BLACK_SHULKER_BOX(0, ""), - BLACK_STAINED_GLASS(15, "STAINED_GLASS"), - BLACK_STAINED_GLASS_PANE(15, "STAINED_GLASS_PANE"), - BLACK_TERRACOTTA(15, "HARD_CLAY", "STAINED_CLAY"), - BLACK_WALL_BANNER(0, "WALL_BANNER"), - BLACK_WOOL(15, "WOOL"), - BLAST_FURNACE(0, "1.14", "FURNACE"), - BLAZE_POWDER(0, ""), - BLAZE_ROD(0, ""), - BLAZE_SPAWN_EGG(61, "MONSTER_EGG"), - BLUE_BANNER(11, "BANNER", "STANDING_BANNER"), - BLUE_BED(4, "BED", "BED_BLOCK"), - BLUE_CARPET(11, "CARPET"), - BLUE_CONCRETE(11, "CONCRETE"), - BLUE_CONCRETE_POWDER(11, "CONCRETE_POWDER"), - BLUE_DYE(4, "INK_SACK", "LAPIS_LAZULI"), - BLUE_GLAZED_TERRACOTTA(11, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLUE_TERRACOTTA"), - BLUE_ICE(0, "1.13", "PACKED_ICE"), - BLUE_ORCHID(1, "RED_ROSE"), - BLUE_SHULKER_BOX(0, ""), - BLUE_STAINED_GLASS(11, "STAINED_GLASS"), - BLUE_STAINED_GLASS_PANE(11, "THIN_GLASS", "STAINED_GLASS_PANE"), - BLUE_TERRACOTTA(11, "STAINED_CLAY"), - BLUE_WALL_BANNER(11, "WALL_BANNER"), - BLUE_WOOL(11, "WOOL"), - BONE(0, ""), - BONE_BLOCK(0, ""), - BONE_MEAL(15, "INK_SACK"), - BOOK(0, ""), - BOOKSHELF(0, ""), - BOW(0, ""), - BOWL(0, ""), - BRAIN_CORAL(0, "1.13"), - BRAIN_CORAL_BLOCK(0, "1.13"), - BRAIN_CORAL_FAN(0, "1.13"), - BRAIN_CORAL_WALL_FAN(0, ""), - BREAD(0, ""), - BREWING_STAND(0, "BREWING_STAND_ITEM"), - BRICK(0, "CLAY_BRICK"), - BRICKS(0, "BRICK"), - BRICK_SLAB(4, "STEP"), - BRICK_STAIRS(0, ""), - BRICK_WALL(0, ""), - BROWN_BANNER(3, "BANNER", "STANDING_BANNER"), - BROWN_BED(12, "BED", "BED_BLOCK"), - BROWN_DYE(3, "INK_SACK", "COCOA", "COCOA_BEANS"), - BROWN_CARPET(12, "CARPET"), - BROWN_CONCRETE(12, "CONCRETE"), - BROWN_CONCRETE_POWDER(12, "CONCRETE_POWDER"), - BROWN_GLAZED_TERRACOTTA(12, "1.12", "HARD_CLAY", "STAINED_CLAY", "BROWN_TERRACOTTA"), - BROWN_MUSHROOM(0, ""), - BROWN_MUSHROOM_BLOCK(0, "BROWN_MUSHROOM", "HUGE_MUSHROOM_1"), - BROWN_SHULKER_BOX(0, ""), - BROWN_STAINED_GLASS(12, "STAINED_GLASS"), - BROWN_STAINED_GLASS_PANE(12, "THIN_GLASS", "STAINED_GLASS_PANE"), - BROWN_TERRACOTTA(12, "STAINED_CLAY"), - BROWN_WALL_BANNER(3, "WALL_BANNER"), - BROWN_WOOL(12, "WOOL"), - BUBBLE_COLUMN(0, "1.13"), - BUBBLE_CORAL(0, "1.13"), - BUBBLE_CORAL_BLOCK(0, "1.13"), - BUBBLE_CORAL_FAN(0, "1.13"), - BUBBLE_CORAL_WALL_FAN(0, ""), - BUCKET(0, ""), - CACTUS(0, ""), - CAKE(0, "CAKE_BLOCK"), - CAMPFIRE(0, "1.14"), - CARROT(0, "CARROT_ITEM"), - CARROTS(0, "CARROT"), - CARROT_ON_A_STICK(0, "CARROT_STICK"), - CARTOGRAPHY_TABLE(0, "1.14", "CRAFTING_TABLE"), - CARVED_PUMPKIN(1, "PUMPKIN"), - CAT_SPAWN_EGG(0, ""), - CAULDRON(0, "CAULDRON_ITEM"), - CAVE_AIR(0, "AIR"), - CAVE_SPIDER_SPAWN_EGG(59, "MONSTER_EGG"), - CHAINMAIL_BOOTS(0, ""), - CHAINMAIL_CHESTPLATE(0, ""), - CHAINMAIL_HELMET(0, ""), - CHAINMAIL_LEGGINGS(0, ""), - CHAIN_COMMAND_BLOCK(0, "COMMAND", "COMMAND_CHAIN"), - CHARCOAL(1, "COAL"), - CHEST(0, "LOCKED_CHEST"), - CHEST_MINECART(0, "STORAGE_MINECART"), - CHICKEN(0, "RAW_CHICKEN"), - CHICKEN_SPAWN_EGG(93, "MONSTER_EGG"), - CHIPPED_ANVIL(1, "ANVIL"), - CHISELED_QUARTZ_BLOCK(1, "QUARTZ_BLOCK"), - CHISELED_RED_SANDSTONE(1, "RED_SANDSTONE"), - CHISELED_SANDSTONE(1, "SANDSTONE"), - CHISELED_STONE_BRICKS(3, "SMOOTH_BRICK"), - CHORUS_FLOWER(0, ""), - CHORUS_FRUIT(0, ""), - CHORUS_PLANT(0, ""), - CLAY(0, ""), - CLAY_BALL(0, ""), - CLOCK(0, "WATCH"), - COAL(0, ""), - COAL_BLOCK(0, ""), - COAL_ORE(0, ""), - COARSE_DIRT(1, "DIRT"), - COBBLESTONE(0, ""), - COBBLESTONE_SLAB(3, "STEP"), - COBBLESTONE_STAIRS(0, ""), - COBBLESTONE_WALL(0, "COBBLE_WALL"), - COBWEB(0, "WEB"), - COCOA_BEANS(3, "INK_SACK", "COCOA"), - COD(0, "RAW_FISH"), - COD_BUCKET(0, "1.13", "BUCKET", "WATER_BUCKET"), - COD_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), - COMMAND_BLOCK(0, "COMMAND"), - COMMAND_BLOCK_MINECART(0, "COMMAND_MINECART"), - COMPARATOR(0, "REDSTONE_COMPARATOR", "REDSTONE_COMPARATOR_ON", "REDSTONE_COMPARATOR_OFF"), - COMPASS(0, ""), - COMPOSTER(0, "1.14", "CAULDRON"), - CONDUIT(0, "1.13"), - COOKED_BEEF(0, ""), - COOKED_CHICKEN(0, ""), - COOKED_COD(0, "COOKED_FISH"), - COOKED_MUTTON(0, ""), - COOKED_PORKCHOP(0, "PORK", "GRILLED_PORK"), - COOKED_RABBIT(0, ""), - COOKED_SALMON(1, "COOKED_FISH"), - COOKIE(0, ""), - CORNFLOWER(4, "1.14", "BLUE_DYE"), - COW_SPAWN_EGG(92, "MONSTER_EGG"), - CRACKED_STONE_BRICKS(2, "SMOOTH_BRICK"), - CRAFTING_TABLE(0, "WORKBENCH"), - CREEPER_BANNER_PATTERN(0, ""), - CREEPER_HEAD(4, "SKULL", "SKULL_ITEM"), - CREEPER_SPAWN_EGG(50, "MONSTER_EGG"), - CREEPER_WALL_HEAD(4, "SKULL", "SKULL_ITEM"), - CROSSBOW(0, ""), - CUT_RED_SANDSTONE(0, "1.13"), - CUT_RED_SANDSTONE_SLAB(0, "STONE_SLAB2"), - CUT_SANDSTONE(0, "1.13"), - CUT_SANDSTONE_SLAB(0, "STEP"), - CYAN_BANNER(6, "BANNER", "STANDING_BANNER"), - CYAN_BED(9, "BED", "BED_BLOCK"), - CYAN_CARPET(9, "CARPET"), - CYAN_CONCRETE(9, "CONCRETE"), - CYAN_CONCRETE_POWDER(9, "CONCRETE_POWDER"), - CYAN_DYE(6, "INK_SACK"), - CYAN_GLAZED_TERRACOTTA(9, "1.12", "HARD_CLAY", "STAINED_CLAY", "CYAN_TERRACOTTA"), - CYAN_SHULKER_BOX(0, ""), - CYAN_STAINED_GLASS(9, "STAINED_GLASS"), - CYAN_STAINED_GLASS_PANE(9, "STAINED_GLASS_PANE"), - CYAN_TERRACOTTA(9, "HARD_CLAY", "STAINED_CLAY"), - CYAN_WALL_BANNER(6, "WALL_BANNER"), - CYAN_WOOL(9, "WOOL"), - DAMAGED_ANVIL(2, "ANVIL"), - DANDELION(0, "YELLOW_FLOWER"), - DARK_OAK_BOAT(0, "BOAT_DARK_OAK"), - DARK_OAK_BUTTON(0, "WOOD_BUTTON"), - DARK_OAK_DOOR(0, "DARK_OAK_DOOR_ITEM"), - DARK_OAK_FENCE(0, ""), - DARK_OAK_FENCE_GATE(0, ""), - DARK_OAK_LEAVES(1, "LEAVES", "LEAVES_2"), - DARK_OAK_LOG(1, "LOG", "LOG_2"), - DARK_OAK_PLANKS(5, "WOOD"), - DARK_OAK_PRESSURE_PLATE(0, "WOOD_PLATE"), - DARK_OAK_SAPLING(5, "SAPLING"), - DARK_OAK_SIGN(0, "SIGN"), - DARK_OAK_SLAB(0, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - DARK_OAK_STAIRS(0, ""), - DARK_OAK_TRAPDOOR(0, "TRAP_DOOR"), - DARK_OAK_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), - DARK_OAK_WOOD(1, "LOG", "LOG_2"), - DARK_PRISMARINE(1, "PRISMARINE"), - DARK_PRISMARINE_SLAB(0, "1.13"), - DARK_PRISMARINE_STAIRS(0, "1.13"), - DAYLIGHT_DETECTOR(0, "DAYLIGHT_DETECTOR_INVERTED"), - DEAD_BRAIN_CORAL(0, ""), - DEAD_BRAIN_CORAL_BLOCK(0, "1.13"), - DEAD_BRAIN_CORAL_FAN(0, ""), - DEAD_BRAIN_CORAL_WALL_FAN(0, ""), - DEAD_BUBBLE_CORAL(0, ""), - DEAD_BUBBLE_CORAL_BLOCK(0, "1.13"), - DEAD_BUBBLE_CORAL_FAN(0, ""), - DEAD_BUBBLE_CORAL_WALL_FAN(0, ""), - DEAD_BUSH(0, ""), - DEAD_FIRE_CORAL(0, ""), - DEAD_FIRE_CORAL_BLOCK(0, "1.13"), - DEAD_FIRE_CORAL_FAN(0, ""), - DEAD_FIRE_CORAL_WALL_FAN(0, ""), - DEAD_HORN_CORAL(0, ""), - DEAD_HORN_CORAL_BLOCK(0, "1.13"), - DEAD_HORN_CORAL_FAN(0, ""), - DEAD_HORN_CORAL_WALL_FAN(0, ""), - DEAD_TUBE_CORAL(0, ""), - DEAD_TUBE_CORAL_BLOCK(0, "1.13"), - DEAD_TUBE_CORAL_FAN(0, ""), - DEAD_TUBE_CORAL_WALL_FAN(0, ""), - DEBUG_STICK(0, "1.13", "STICK"), - DETECTOR_RAIL(0, ""), - DIAMOND(0, ""), - DIAMOND_AXE(0, ""), - DIAMOND_BLOCK(0, ""), - DIAMOND_BOOTS(0, ""), - DIAMOND_CHESTPLATE(0, ""), - DIAMOND_HELMET(0, ""), - DIAMOND_HOE(0, ""), - DIAMOND_HORSE_ARMOR(0, "DIAMOND_BARDING"), - DIAMOND_LEGGINGS(0, ""), - DIAMOND_ORE(0, ""), - DIAMOND_PICKAXE(0, ""), - DIAMOND_SHOVEL(0, "DIAMOND_SPADE"), - DIAMOND_SWORD(0, ""), - DIORITE(3, "1.13"), - DIORITE_SLAB(0, ""), - DIORITE_STAIRS(0, ""), - DIORITE_WALL(0, ""), - DIRT(0, ""), - DISPENSER(0, ""), - DOLPHIN_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), - DONKEY_SPAWN_EGG(32, "MONSTER_EGG"), - DRAGON_BREATH(0, "DRAGONS_BREATH"), - DRAGON_EGG(0, ""), - DRAGON_HEAD(5, "SKULL", "SKULL_ITEM"), - DRAGON_WALL_HEAD(5, "SKULL", "SKULL_ITEM"), - DRIED_KELP(0, "1.13"), - DRIED_KELP_BLOCK(0, "1.13"), - DROPPER(0, ""), - DROWNED_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), - EGG(0, ""), - ELDER_GUARDIAN_SPAWN_EGG(4, "MONSTER_EGG"), - ELYTRA(0, ""), - EMERALD(0, ""), - EMERALD_BLOCK(0, ""), - EMERALD_ORE(0, ""), - ENCHANTED_BOOK(0, ""), - ENCHANTED_GOLDEN_APPLE(1, "GOLDEN_APPLE"), - ENCHANTING_TABLE(0, "ENCHANTMENT_TABLE"), - ENDERMAN_SPAWN_EGG(58, "MONSTER_EGG"), - ENDERMITE_SPAWN_EGG(67, "MONSTER_EGG"), - ENDER_CHEST(0, ""), - ENDER_EYE(0, "EYE_OF_ENDER"), - ENDER_PEARL(0, ""), - END_CRYSTAL(0, ""), - END_GATEWAY(0, ""), - END_PORTAL(0, "ENDER_PORTAL"), - END_PORTAL_FRAME(0, "ENDER_PORTAL_FRAME"), - END_ROD(0, ""), - END_STONE(0, "ENDER_STONE"), - END_STONE_BRICKS(0, "END_BRICKS"), - END_STONE_BRICK_SLAB(4, "STEP"), - END_STONE_BRICK_STAIRS(0, "SMOOTH_STAIRS"), - END_STONE_BRICK_WALL(0, ""), - EVOKER_SPAWN_EGG(34, "MONSTER_EGG"), - EXPERIENCE_BOTTLE(0, "EXP_BOTTLE"), - FARMLAND(0, "SOIL"), - FEATHER(0, ""), - FERMENTED_SPIDER_EYE(0, ""), - FERN(2, "LONG_GRASS"), - FILLED_MAP(0, "MAP"), - FIRE(0, ""), - FIREWORK_ROCKET(0, "FIREWORK"), - FIREWORK_STAR(0, "FIREWORK_CHARGE"), - FIRE_CHARGE(0, "FIREBALL"), - FIRE_CORAL(0, "1.13"), - FIRE_CORAL_BLOCK(0, "1.13"), - FIRE_CORAL_FAN(0, "1.13"), - FIRE_CORAL_WALL_FAN(0, ""), - FISHING_ROD(0, ""), - FLETCHING_TABLE(0, "1.14", "CRAFTING_TABLE"), - FLINT(0, ""), - FLINT_AND_STEEL(0, ""), - FLOWER_BANNER_PATTERN(0, ""), - FLOWER_POT(0, "FLOWER_POT_ITEM"), - FOX_SPAWN_EGG(0, "1.14"), - FROSTED_ICE(0, ""), - FURNACE(0, "BURNING_FURNACE"), - FURNACE_MINECART(0, "POWERED_MINECART"), - GHAST_SPAWN_EGG(56, "MONSTER_EGG"), - GHAST_TEAR(0, ""), - GLASS(0, ""), - GLASS_BOTTLE(0, ""), - GLASS_PANE(0, "THIN_GLASS"), - GLISTERING_MELON_SLICE(0, "SPECKLED_MELON"), - GLOBE_BANNER_PATTERN(0, ""), - GLOWSTONE(0, ""), - GLOWSTONE_DUST(0, ""), - GOLDEN_APPLE(0, ""), - GOLDEN_AXE(0, "GOLD_AXE"), - GOLDEN_BOOTS(0, "GOLD_BOOTS"), - GOLDEN_CARROT(0, ""), - GOLDEN_CHESTPLATE(0, "GOLD_CHESTPLATE"), - GOLDEN_HELMET(0, "GOLD_HELMET"), - GOLDEN_HOE(0, "GOLD_HOE"), - GOLDEN_HORSE_ARMOR(0, "GOLD_BARDING"), - GOLDEN_LEGGINGS(0, "GOLD_LEGGINGS"), - GOLDEN_PICKAXE(0, "GOLD_PICKAXE"), - GOLDEN_SHOVEL(0, "GOLD_SPADE"), - GOLDEN_SWORD(0, "GOLD_SWORD"), - GOLD_BLOCK(0, ""), - GOLD_INGOT(0, ""), - GOLD_NUGGET(0, ""), - GOLD_ORE(0, ""), - GRANITE(1, "1.13"), - GRANITE_SLAB(0, ""), - GRANITE_STAIRS(0, ""), - GRANITE_WALL(0, ""), - GRASS(0, ""), - GRASS_BLOCK(0, "GRASS"), - GRASS_PATH(0, ""), - GRAVEL(0, ""), - GRAY_BANNER(8, "BANNER", "STANDING_BANNER"), - GRAY_BED(7, "BED", "BED_BLOCK"), - GRAY_CARPET(7, "CARPET"), - GRAY_CONCRETE(7, "CONCRETE"), - GRAY_CONCRETE_POWDER(7, "CONCRETE_POWDER"), - GRAY_DYE(8, "INK_SACK"), - GRAY_GLAZED_TERRACOTTA(7, "1.12", "HARD_CLAY", "STAINED_CLAY", "GRAY_TERRACOTTA"), - GRAY_SHULKER_BOX(0, ""), - GRAY_STAINED_GLASS(8, "STAINED_GLASS"), - GRAY_STAINED_GLASS_PANE(7, "THIN_GLASS", "STAINED_GLASS_PANE"), - GRAY_TERRACOTTA(7, "HARD_CLAY", "STAINED_CLAY"), - GRAY_WALL_BANNER(8, "WALL_BANNER"), - GRAY_WOOL(8, "WOOL"), - GREEN_BANNER(2, "BANNER", "STANDING_BANNER"), - GREEN_BED(13, "BED", "BED_BLOCK"), - GREEN_CARPET(13, "CARPET"), - GREEN_CONCRETE(13, "CONCRETE"), - GREEN_CONCRETE_POWDER(13, "CONCRETE_POWDER"), - GREEN_DYE(2, "INK_SACK", "CACTUS_GREEN"), - GREEN_GLAZED_TERRACOTTA(13, "1.12", "HARD_CLAY", "STAINED_CLAY", "GREEN_TERRACOTTA"), - GREEN_SHULKER_BOX(0, ""), - GREEN_STAINED_GLASS(13, "STAINED_GLASS"), - GREEN_STAINED_GLASS_PANE(13, "THIN_GLASS", "STAINED_GLASS_PANE"), - GREEN_TERRACOTTA(13, "HARD_CLAY", "STAINED_CLAY"), - GREEN_WALL_BANNER(2, "WALL_BANNER"), - GREEN_WOOL(13, "WOOL"), - GRINDSTONE(0, "1.14", "ANVIL"), - GUARDIAN_SPAWN_EGG(68, "MONSTER_EGG"), - GUNPOWDER(0, "SULPHUR"), - HAY_BLOCK(0, ""), - HEART_OF_THE_SEA(0, "1.13"), - HEAVY_WEIGHTED_PRESSURE_PLATE(0, "IRON_PLATE"), - HOPPER(0, ""), - HOPPER_MINECART(0, ""), - HORN_CORAL(0, "1.13"), - HORN_CORAL_BLOCK(0, "1.13"), - HORN_CORAL_FAN(0, "1.13"), - HORN_CORAL_WALL_FAN(0, ""), - HORSE_SPAWN_EGG(100, "MONSTER_EGG"), - HUSK_SPAWN_EGG(23, "MONSTER_EGG"), - ICE(0, ""), - INFESTED_CHISELED_STONE_BRICKS(5, "MONSTER_EGGS", "SMOOTH_BRICK"), - INFESTED_COBBLESTONE(1, "MONSTER_EGGS"), - INFESTED_CRACKED_STONE_BRICKS(4, "MONSTER_EGGS", "SMOOTH_BRICK"), - INFESTED_MOSSY_STONE_BRICKS(3, "MONSTER_EGGS"), - INFESTED_STONE(0, "MONSTER_EGGS"), - INFESTED_STONE_BRICKS(2, "MONSTER_EGGS", "SMOOTH_BRICK"), - INK_SAC(0, "INK_SACK"), - IRON_AXE(0, ""), - IRON_BARS(0, "IRON_FENCE"), - IRON_BLOCK(0, ""), - IRON_BOOTS(0, ""), - IRON_CHESTPLATE(0, ""), - IRON_DOOR(0, "IRON_DOOR_BLOCK"), - IRON_HELMET(0, ""), - IRON_HOE(0, ""), - IRON_HORSE_ARMOR(0, "IRON_BARDING"), - IRON_INGOT(0, ""), - IRON_LEGGINGS(0, ""), - IRON_NUGGET(0, ""), - IRON_ORE(0, ""), - IRON_PICKAXE(0, ""), - IRON_SHOVEL(0, "IRON_SPADE"), - IRON_SWORD(0, ""), - IRON_TRAPDOOR(0, ""), - ITEM_FRAME(0, ""), - JACK_O_LANTERN(0, ""), - JIGSAW(0, "1.14", "COMMAND_BLOCK", "STRUCTURE_BLOCK"), - JUKEBOX(0, ""), - JUNGLE_BOAT(0, "BOAT_JUNGLE"), - JUNGLE_BUTTON(0, "WOOD_BUTTON"), - JUNGLE_DOOR(0, "JUNGLE_DOOR_ITEM"), - JUNGLE_FENCE(0, ""), - JUNGLE_FENCE_GATE(0, ""), - JUNGLE_LEAVES(3, "LEAVES"), - JUNGLE_LOG(3, "LOG"), - JUNGLE_PLANKS(3, "WOOD"), - JUNGLE_PRESSURE_PLATE(0, "WOOD_PLATE"), - JUNGLE_SAPLING(3, "SAPLING"), - JUNGLE_SIGN(0, "SIGN"), - JUNGLE_SLAB(3, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - JUNGLE_STAIRS(0, "JUNGLE_WOOD_STAIRS"), - JUNGLE_TRAPDOOR(0, "TRAP_DOOR"), - JUNGLE_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), - JUNGLE_WOOD(3, "LOG"), - KELP(0, "1.13"), - KELP_PLANT(0, "1.13"), - KNOWLEDGE_BOOK(0, ""), - LADDER(0, ""), - LANTERN(0, "1.14", "SEA_LANTERN"), - LAPIS_BLOCK(0, ""), - LAPIS_LAZULI(4, "INK_SACK"), - LAPIS_ORE(0, ""), - LARGE_FERN(3, "DOUBLE_PLANT"), - LAVA(0, "STATIONARY_LAVA"), - LAVA_BUCKET(0, ""), - LEAD(0, "LEASH"), - LEATHER(0, ""), - LEATHER_BOOTS(0, ""), - LEATHER_CHESTPLATE(0, ""), - LEATHER_HELMET(0, ""), - LEATHER_HORSE_ARMOR(0, "1.14", "IRON_HORSE_ARMOR"), - LEATHER_LEGGINGS(0, ""), - LECTERN(0, "1.14", "BOOKSHELF"), - LEVER(0, ""), - LIGHT_BLUE_BANNER(11, "BANNER", "STANDING_BANNER"), - LIGHT_BLUE_BED(3, "BED", "BED_BLOCK"), - LIGHT_BLUE_CARPET(3, "CARPET"), - LIGHT_BLUE_CONCRETE(3, "CONCRETE"), - LIGHT_BLUE_CONCRETE_POWDER(3, "CONCRETE_POWDER"), - LIGHT_BLUE_DYE(12, "INK_SACK"), - LIGHT_BLUE_GLAZED_TERRACOTTA(3, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_BLUE_TERRACOTTA"), - LIGHT_BLUE_SHULKER_BOX(0, ""), - LIGHT_BLUE_STAINED_GLASS(11, "STAINED_GLASS"), - LIGHT_BLUE_STAINED_GLASS_PANE(3, "THIN_GLASS", "STAINED_GLASS_PANE"), - LIGHT_BLUE_TERRACOTTA(3, "STAINED_CLAY"), - LIGHT_BLUE_WALL_BANNER(12, "WALL_BANNER", "BANNER", "STANDING_BANNER"), - LIGHT_BLUE_WOOL(11, "WOOL"), - LIGHT_GRAY_BANNER(7, "BANNER", "STANDING_BANNER"), - LIGHT_GRAY_BED(7, "BED", "BED_BLOCK"), - LIGHT_GRAY_CARPET(8, "CARPET"), - LIGHT_GRAY_CONCRETE(8, "CONCRETE"), - LIGHT_GRAY_CONCRETE_POWDER(8, "CONCRETE_POWDER"), - LIGHT_GRAY_DYE(7, "INK_SACK"), - LIGHT_GRAY_GLAZED_TERRACOTTA(8, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_GRAY_TERRACOTTA", "SILVER_GLAZED_TERRACOTTA/1.13"), - LIGHT_GRAY_SHULKER_BOX(0, "SILVER_SHULKER_BOX"), - LIGHT_GRAY_STAINED_GLASS(8, "STAINED_GLASS"), - LIGHT_GRAY_STAINED_GLASS_PANE(8, "THIN_GLASS", "STAINED_GLASS_PANE"), - LIGHT_GRAY_TERRACOTTA(8, "HARD_CLAY", "STAINED_CLAY"), - LIGHT_GRAY_WALL_BANNER(7, "WALL_BANNER"), - LIGHT_GRAY_WOOL(8, "WOOL"), - LIGHT_WEIGHTED_PRESSURE_PLATE(0, "GOLD_PLATE"), - LILAC(1, "DOUBLE_PLANT"), - LILY_OF_THE_VALLEY(15, "1.14", "WHITE_DYE"), - LILY_PAD(0, "WATER_LILY"), - LIME_BANNER(10, "BANNER", "STANDING_BANNER"), - LIME_BED(5, "BED", "BED_BLOCK"), - LIME_CARPET(5, "CARPET"), - LIME_CONCRETE(5, "CONCRETE"), - LIME_CONCRETE_POWDER(5, "CONCRETE_POWDER"), - LIME_DYE(10, "INK_SACK"), - LIME_GLAZED_TERRACOTTA(5, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIME_TERRACOTTA"), - LIME_SHULKER_BOX(0, ""), - LIME_STAINED_GLASS(5, "STAINED_GLASS"), - LIME_STAINED_GLASS_PANE(5, "STAINED_GLASS_PANE"), - LIME_TERRACOTTA(5, "HARD_CLAY", "STAINED_CLAY"), - LIME_WALL_BANNER(10, "WALL_BANNER"), - LIME_WOOL(5, "WOOL"), - LINGERING_POTION(0, ""), - LLAMA_SPAWN_EGG(103, "MONSTER_EGG"), - LOOM(0, "1.14"), - MAGENTA_BANNER(13, "BANNER", "STANDING_BANNER"), - MAGENTA_BED(2, "BED", "BED_BLOCK"), - MAGENTA_CARPET(2, "CARPET"), - MAGENTA_CONCRETE(2, "CONCRETE"), - MAGENTA_CONCRETE_POWDER(2, "CONCRETE_POWDER"), - MAGENTA_DYE(13, "INK_SACK"), - MAGENTA_GLAZED_TERRACOTTA(2, "1.12", "HARD_CLAY", "STAINED_CLAY", "MAGENTA_TERRACOTTA"), - MAGENTA_SHULKER_BOX(0, ""), - MAGENTA_STAINED_GLASS(2, "STAINED_GLASS"), - MAGENTA_STAINED_GLASS_PANE(2, "THIN_GLASS", "STAINED_GLASS_PANE"), - MAGENTA_TERRACOTTA(2, "HARD_CLAY", "STAINED_CLAY"), - MAGENTA_WALL_BANNER(13, "WALL_BANNER"), - MAGENTA_WOOL(2, "WOOL"), - MAGMA_BLOCK(0, "MAGMA"), - MAGMA_CREAM(0, ""), - MAGMA_CUBE_SPAWN_EGG(62, "MONSTER_EGG"), - MAP(0, "EMPTY_MAP"), - MELON(0, "MELON_BLOCK"), - MELON_SEEDS(0, ""), - MELON_SLICE(0, "MELON"), - MELON_STEM(0, ""), - MILK_BUCKET(0, ""), - MINECART(0, ""), - MOJANG_BANNER_PATTERN(0, ""), - MOOSHROOM_SPAWN_EGG(96, "MONSTER_EGG"), - MOSSY_COBBLESTONE(0, ""), - MOSSY_COBBLESTONE_SLAB(3, "STEP"), - MOSSY_COBBLESTONE_STAIRS(0, ""), - MOSSY_COBBLESTONE_WALL(1, "COBBLE_WALL", "COBBLESTONE_WALL"), - MOSSY_STONE_BRICKS(1, "SMOOTH_BRICK"), - MOSSY_STONE_BRICK_SLAB(4, "STEP"), - MOSSY_STONE_BRICK_STAIRS(0, "SMOOTH_STAIRS"), - MOSSY_STONE_BRICK_WALL(0, ""), - MOVING_PISTON(0, "PISTON_BASE", "PISTON_MOVING_PIECE"), - MULE_SPAWN_EGG(32, "MONSTER_EGG"), - MUSHROOM_STEM(0, "BROWN_MUSHROOM"), - MUSHROOM_STEW(0, "MUSHROOM_SOUP"), - MUSIC_DISC_11(0, "GOLD_RECORD"), - MUSIC_DISC_13(0, "GREEN_RECORD"), - MUSIC_DISC_BLOCKS(0, "RECORD_3"), - MUSIC_DISC_CAT(0, "RECORD_4"), - MUSIC_DISC_CHIRP(0, "RECORD_5"), - MUSIC_DISC_FAR(0, "RECORD_6"), - MUSIC_DISC_MALL(0, "RECORD_7"), - MUSIC_DISC_MELLOHI(0, "RECORD_8"), - MUSIC_DISC_STAL(0, "RECORD_9"), - MUSIC_DISC_STRAD(0, "RECORD_10"), - MUSIC_DISC_WAIT(0, "RECORD_11"), - MUSIC_DISC_WARD(0, "RECORD_12"), - MUTTON(0, ""), - MYCELIUM(0, "MYCEL"), - NAME_TAG(0, ""), - NAUTILUS_SHELL(0, "1.13"), - NETHERRACK(0, ""), - NETHER_BRICK(0, "NETHER_BRICK_ITEM"), - NETHER_BRICKS(0, "NETHER_BRICK"), - NETHER_BRICK_FENCE(0, "NETHER_FENCE"), - NETHER_BRICK_SLAB(4, "STEP"), - NETHER_BRICK_STAIRS(0, ""), - NETHER_BRICK_WALL(0, ""), - NETHER_PORTAL(0, "PORTAL"), - NETHER_QUARTZ_ORE(0, "QUARTZ_ORE"), - NETHER_STAR(0, ""), - NETHER_WART(0, "NETHER_STALK"), - NETHER_WART_BLOCK(0, "NETHER_WARTS"), - NOTE_BLOCK(0, ""), - OAK_BOAT(0, "BOAT"), - OAK_BUTTON(0, "WOOD_BUTTON"), - OAK_DOOR(0, "WOOD_DOOR", "WOODEN_DOOR"), - OAK_FENCE(0, "FENCE"), - OAK_FENCE_GATE(0, "FENCE_GATE"), - OAK_LEAVES(0, "LEAVES"), - OAK_LOG(0, "LOG"), - OAK_PLANKS(0, "WOOD"), - OAK_PRESSURE_PLATE(0, "WOOD_PLATE"), - OAK_SAPLING(0, "SAPLING"), - OAK_SIGN(0, "SIGN"), - OAK_SLAB(0, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - OAK_STAIRS(0, "WOOD_STAIRS"), - OAK_TRAPDOOR(0, "TRAP_DOOR"), - OAK_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), - OAK_WOOD(0, "LOG"), - OBSERVER(0, ""), - OBSIDIAN(0, ""), - OCELOT_SPAWN_EGG(98, "MONSTER_EGG"), - ORANGE_BANNER(14, "BANNER", "STANDING_BANNER"), - ORANGE_BED(1, "BED", "BED_BLOCK"), - ORANGE_CARPET(1, "CARPET"), - ORANGE_CONCRETE(1, "CONCRETE"), - ORANGE_CONCRETE_POWDER(1, "CONCRETE_POWDER"), - ORANGE_DYE(14, "INK_SACK"), - ORANGE_GLAZED_TERRACOTTA(1, "1.12", "HARD_CLAY", "STAINED_CLAY", "ORANGE_TERRACOTTA"), - ORANGE_SHULKER_BOX(0, ""), - ORANGE_STAINED_GLASS(1, "STAINED_GLASS"), - ORANGE_STAINED_GLASS_PANE(1, "STAINED_GLASS_PANE"), - ORANGE_TERRACOTTA(1, "HARD_CLAY", "STAINED_CLAY"), - ORANGE_TULIP(5, "RED_ROSE"), - ORANGE_WALL_BANNER(14, "WALL_BANNER"), - ORANGE_WOOL(1, "WOOL"), - OXEYE_DAISY(8, "RED_ROSE"), - PACKED_ICE(0, ""), - PAINTING(0, ""), - PANDA_SPAWN_EGG(0, "1.14"), - PAPER(0, ""), - PARROT_SPAWN_EGG(105, "MONSTER_EGG"), - PEONY(5, "DOUBLE_PLANT"), - PETRIFIED_OAK_SLAB(0, "WOOD_STEP"), - PHANTOM_MEMBRANE(0, "1.13"), - PHANTOM_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), - PIG_SPAWN_EGG(90, "MONSTER_EGG"), - PILLAGER_SPAWN_EGG(0, "1.14"), - PINK_BANNER(9, "BANNER", "STANDING_BANNER"), - PINK_BED(6, "BED", "BED_BLOCK"), - PINK_CARPET(6, "CARPET"), - PINK_CONCRETE(6, "CONCRETE"), - PINK_CONCRETE_POWDER(6, "CONCRETE_POWDER"), - PINK_DYE(9, "INK_SACK"), - PINK_GLAZED_TERRACOTTA(6, "1.12", "HARD_CLAY", "STAINED_CLAY", "PINK_TERRACOTTA"), - PINK_SHULKER_BOX(0, ""), - PINK_STAINED_GLASS(6, "STAINED_GLASS"), - PINK_STAINED_GLASS_PANE(6, "THIN_GLASS", "STAINED_GLASS_PANE"), - PINK_TERRACOTTA(6, "HARD_CLAY", "STAINED_CLAY"), - PINK_TULIP(7, "RED_ROSE"), - PINK_WALL_BANNER(14, "WALL_BANNER"), - PINK_WOOL(6, "WOOL"), - PISTON(0, "PISTON_BASE"), - PISTON_HEAD(0, "PISTON_EXTENSION"), - PLAYER_HEAD(3, "SKULL", "SKULL_ITEM"), - PLAYER_WALL_HEAD(3, "SKULL", "SKULL_ITEM"), - PODZOL(2, "DIRT"), - POISONOUS_POTATO(0, ""), - POLAR_BEAR_SPAWN_EGG(102, "MONSTER_EGG"), - POLISHED_ANDESITE(6, "1.13"), - POLISHED_ANDESITE_SLAB(0, ""), - POLISHED_ANDESITE_STAIRS(0, ""), - POLISHED_DIORITE(4, "1.13"), - POLISHED_DIORITE_SLAB(0, ""), - POLISHED_DIORITE_STAIRS(0, ""), - POLISHED_GRANITE(2, "1.13"), - POLISHED_GRANITE_SLAB(0, ""), - POLISHED_GRANITE_STAIRS(0, ""), - POPPED_CHORUS_FRUIT(0, "CHORUS_FRUIT_POPPED"), - POPPY(0, "RED_ROSE"), - PORKCHOP(0, "PORK"), - POTATO(0, "POTATO_ITEM"), - POTATOES(0, "POTATO"), - POTION(0, ""), - POTTED_ACACIA_SAPLING(4, "SAPLING", "FLOWER_POT"), - POTTED_ALLIUM(2, "RED_ROSE", "FLOWER_POT"), - POTTED_AZURE_BLUET(3, "RED_ROSE", "FLOWER_POT"), - POTTED_BAMBOO(0, ""), - POTTED_BIRCH_SAPLING(2, "SAPLING", "FLOWER_POT"), - POTTED_BLUE_ORCHID(1, "RED_ROSE", "FLOWER_POT"), - POTTED_BROWN_MUSHROOM(0, "FLOWER_POT"), - POTTED_CACTUS(0, "FLOWER_POT"), - POTTED_CORNFLOWER(0, ""), - POTTED_DANDELION(0, "YELLOW_FLOWER", "FLOWER_POT"), - POTTED_DARK_OAK_SAPLING(5, "SAPLING", "FLOWER_POT"), - POTTED_DEAD_BUSH(0, "FLOWER_POT"), - POTTED_FERN(2, "LONG_GRASS", "FLOWER_POT"), - POTTED_JUNGLE_SAPLING(3, "SAPLING", "FLOWER_POT"), - POTTED_LILY_OF_THE_VALLEY(0, ""), - POTTED_OAK_SAPLING(0, "SAPLING", "FLOWER_POT"), - POTTED_ORANGE_TULIP(5, "RED_ROSE", "FLOWER_POT"), - POTTED_OXEYE_DAISY(8, "RED_ROSE", "FLOWER_POT"), - POTTED_PINK_TULIP(7, "RED_ROSE", "FLOWER_POT"), - POTTED_POPPY(0, "RED_ROSE", "FLOWER_POT"), - POTTED_RED_MUSHROOM(0, "FLOWER_POT"), - POTTED_RED_TULIP(4, "RED_ROSE", "FLOWER_POT"), - POTTED_SPRUCE_SAPLING(1, "SAPLING", "FLOWER_POT"), - POTTED_WHITE_TULIP(6, "RED_ROSE", "FLOWER_POT"), - POTTED_WITHER_ROSE(0, ""), - POWERED_RAIL(0, ""), - PRISMARINE(0, ""), - PRISMARINE_BRICKS(2, "PRISMARINE"), - PRISMARINE_BRICK_SLAB(4, "STEP"), - PRISMARINE_BRICK_STAIRS(0, "1.13"), - PRISMARINE_CRYSTALS(0, ""), - PRISMARINE_SHARD(0, ""), - PRISMARINE_SLAB(0, "1.13"), - PRISMARINE_STAIRS(0, "1.13"), - PRISMARINE_WALL(0, ""), - PUFFERFISH(3, "RAW_FISH"), - PUFFERFISH_BUCKET(0, "1.13", "BUCKET", "WATER_BUCKET"), - PUFFERFISH_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), - PUMPKIN(0, ""), - PUMPKIN_PIE(0, ""), - PUMPKIN_SEEDS(0, ""), - PUMPKIN_STEM(0, ""), - PURPLE_BANNER(5, "BANNER", "STANDING_BANNER"), - PURPLE_BED(10, "BED", "BED_BLOCK"), - PURPLE_CARPET(10, "CARPET"), - PURPLE_CONCRETE(10, "CONCRETE"), - PURPLE_CONCRETE_POWDER(10, "CONCRETE_POWDER"), - PURPLE_DYE(5, "INK_SACK"), - PURPLE_GLAZED_TERRACOTTA(10, "1.12", "HARD_CLAY", "STAINED_CLAY", "PURPLE_TERRACOTTA"), - PURPLE_SHULKER_BOX(0, ""), - PURPLE_STAINED_GLASS(10, "STAINED_GLASS"), - PURPLE_STAINED_GLASS_PANE(10, "THIN_GLASS", "STAINED_GLASS_PANE"), - PURPLE_TERRACOTTA(10, "HARD_CLAY", "STAINED_CLAY"), - PURPLE_WALL_BANNER(5, "WALL_BANNER"), - PURPLE_WOOL(10, "WOOL"), - PURPUR_BLOCK(0, ""), - PURPUR_PILLAR(0, ""), - PURPUR_SLAB(0, "PURPUR_DOUBLE_SLAB"), - PURPUR_STAIRS(0, ""), - QUARTZ(0, ""), - QUARTZ_BLOCK(0, ""), - QUARTZ_PILLAR(2, "QUARTZ_BLOCK"), - QUARTZ_SLAB(7, "STEP"), - QUARTZ_STAIRS(0, ""), - RABBIT(0, ""), - RABBIT_FOOT(0, ""), - RABBIT_HIDE(0, ""), - RABBIT_SPAWN_EGG(101, "MONSTER_EGG"), - RABBIT_STEW(0, ""), - RAIL(0, "RAILS"), - RAVAGER_SPAWN_EGG(0, "1.14"), - REDSTONE(0, ""), - REDSTONE_BLOCK(0, ""), - REDSTONE_LAMP(0, "REDSTONE_LAMP_OFF", "REDSTONE_LAMP_ON"), - REDSTONE_ORE(0, "GLOWING_REDSTONE_ORE"), - REDSTONE_TORCH(0, "REDSTONE_TORCH_ON", "REDSTONE_TORCH_OFF"), - REDSTONE_WALL_TORCH(1, "REDSTONE_TORCH_ON", "REDSTONE_TORCH_OFF"), - REDSTONE_WIRE(0, ""), - RED_BANNER(1, "BANNER", "STANDING_BANNER"), - RED_BED(14, "BED", "BED_BLOCK"), - RED_CARPET(14, "CARPET"), - RED_CONCRETE(14, "CONCRETE"), - RED_CONCRETE_POWDER(14, "CONCRETE_POWDER"), - RED_DYE(1, "ROSE_RED"), - RED_GLAZED_TERRACOTTA(14, "1.12", "HARD_CLAY", "STAINED_CLAY", "RED_TERRACOTTA"), - RED_MUSHROOM(0, ""), - RED_MUSHROOM_BLOCK(0, "RED_MUSHROOM", "HUGE_MUSHROOM_2"), - RED_NETHER_BRICKS(0, "RED_NETHER_BRICK"), - RED_NETHER_BRICK_SLAB(4, "STEP"), - RED_NETHER_BRICK_STAIRS(0, ""), - RED_NETHER_BRICK_WALL(0, ""), - RED_SAND(1, "SAND"), - RED_SANDSTONE(0, ""), - RED_SANDSTONE_SLAB(0, "STONE_SLAB2", "DOUBLE_STONE_SLAB2"), - RED_SANDSTONE_STAIRS(0, ""), - RED_SANDSTONE_WALL(0, ""), - RED_SHULKER_BOX(0, ""), - RED_STAINED_GLASS(14, "STAINED_GLASS"), - RED_STAINED_GLASS_PANE(14, "THIN_GLASS", "STAINED_GLASS_PANE"), - RED_TERRACOTTA(14, "HARD_CLAY", "STAINED_CLAY"), - RED_TULIP(4, "RED_ROSE"), - RED_WALL_BANNER(1, "WALL_BANNER"), - RED_WOOL(14, "WOOL"), - REPEATER(0, "DIODE", "DIODE_BLOCK_ON", "DIODE_BLOCK_OFF"), - REPEATING_COMMAND_BLOCK(0, "COMMAND", "COMMAND_REPEATING"), - ROSE_BUSH(4, "DOUBLE_PLANT"), - ROTTEN_FLESH(0, ""), - SADDLE(0, ""), - SALMON(1, "RAW_FISH"), - SALMON_BUCKET(0, "1.13", "BUCKET", "WATER_BUCKET"), - SALMON_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), - SAND(0, ""), - SANDSTONE(0, ""), - SANDSTONE_SLAB(1, "STEP", "STONE_SLAB", "DOUBLE_STEP"), - SANDSTONE_STAIRS(0, ""), - SANDSTONE_WALL(0, ""), - SCAFFOLDING(0, "1.14", "SLIME_BLOCK"), - SCUTE(0, "1.13"), - SEAGRASS(0, "1.13"), - SEA_LANTERN(0, ""), - SEA_PICKLE(0, "1.13"), - SHEARS(0, ""), - SHEEP_SPAWN_EGG(91, "MONSTER_EGG"), - SHIELD(0, ""), - SHULKER_BOX(0, "PURPLE_SHULKER_BOX"), - SHULKER_SHELL(0, ""), - SHULKER_SPAWN_EGG(69, "MONSTER_EGG"), - SILVERFISH_SPAWN_EGG(60, "MONSTER_EGG"), - SKELETON_HORSE_SPAWN_EGG(28, "MONSTER_EGG"), - SKELETON_SKULL(0, "SKULL", "SKULL_ITEM"), - SKELETON_SPAWN_EGG(51, "MONSTER_EGG"), - SKELETON_WALL_SKULL(0, "SKULL", "SKULL_ITEM"), - SKULL_BANNER_PATTERN(0, ""), - SLIME_BALL(0, ""), - SLIME_BLOCK(0, ""), - SLIME_SPAWN_EGG(55, "MONSTER_EGG"), - SMITHING_TABLE(0, ""), - SMOKER(0, "1.14", "FURNACE"), - SMOOTH_QUARTZ(0, "1.13"), - SMOOTH_QUARTZ_SLAB(7, "STEP"), - SMOOTH_QUARTZ_STAIRS(0, ""), - SMOOTH_RED_SANDSTONE(2, "RED_SANDSTONE"), - SMOOTH_RED_SANDSTONE_SLAB(0, "STONE_SLAB2"), - SMOOTH_RED_SANDSTONE_STAIRS(0, ""), - SMOOTH_SANDSTONE(2, "SANDSTONE"), - SMOOTH_SANDSTONE_SLAB(0, "STEP"), - SMOOTH_SANDSTONE_STAIRS(0, ""), - SMOOTH_STONE(0, "STEP"), - SMOOTH_STONE_SLAB(0, "STEP"), - SNOW(0, ""), - SNOWBALL(0, "SNOW_BALL"), - SNOW_BLOCK(0, ""), - SOUL_SAND(0, ""), - SPAWNER(0, "MOB_SPAWNER"), - SPECTRAL_ARROW(0, ""), - SPIDER_EYE(0, ""), - SPIDER_SPAWN_EGG(52, "MONSTER_EGG"), - SPLASH_POTION(0, ""), - SPONGE(0, ""), - SPRUCE_BOAT(0, "BOAT_SPRUCE"), - SPRUCE_BUTTON(0, "WOOD_BUTTON"), - SPRUCE_DOOR(0, "SPRUCE_DOOR_ITEM"), - SPRUCE_FENCE(0, ""), - SPRUCE_FENCE_GATE(0, ""), - SPRUCE_LEAVES(1, "LEAVES"), - SPRUCE_LOG(1, "LOG"), - SPRUCE_PLANKS(1, "WOOD"), - SPRUCE_PRESSURE_PLATE(0, "WOOD_PLATE"), - SPRUCE_SAPLING(1, "SAPLING"), - SPRUCE_SIGN(0, "SIGN"), - SPRUCE_SLAB(1, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - SPRUCE_STAIRS(0, "SPRUCE_WOOD_STAIRS"), - SPRUCE_TRAPDOOR(0, "TRAP_DOOR"), - SPRUCE_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), - SPRUCE_WOOD(1, "LOG"), - SQUID_SPAWN_EGG(94, "MONSTER_EGG"), - STICK(0, ""), - STICKY_PISTON(0, "PISTON_BASE", "PISTON_STICKY_BASE"), - STONE(0, ""), - STONECUTTER(0, "1.14"), - STONE_AXE(0, ""), - STONE_BRICKS(0, "SMOOTH_BRICK"), - STONE_BRICK_SLAB(4, "STEP", "STONE_SLAB", "DOUBLE_STEP"), - STONE_BRICK_STAIRS(0, "SMOOTH_STAIRS"), - STONE_BRICK_WALL(0, ""), - STONE_BUTTON(0, ""), - STONE_HOE(0, ""), - STONE_PICKAXE(0, ""), - STONE_PRESSURE_PLATE(0, "STONE_PLATE"), - STONE_SHOVEL(0, "STONE_SPADE"), - STONE_SLAB(0, "STEP", "DOUBLE_STEP"), - STONE_STAIRS(0, ""), - STONE_SWORD(0, ""), - STRAY_SPAWN_EGG(6, "MONSTER_EGG"), - STRING(0, ""), - STRIPPED_ACACIA_LOG(0, "LOG_2"), - STRIPPED_ACACIA_WOOD(0, "LOG_2"), - STRIPPED_BIRCH_LOG(2, "LOG"), - STRIPPED_BIRCH_WOOD(2, "LOG"), - STRIPPED_DARK_OAK_LOG(0, "LOG"), - STRIPPED_DARK_OAK_WOOD(0, "LOG"), - STRIPPED_JUNGLE_LOG(3, "LOG"), - STRIPPED_JUNGLE_WOOD(3, "LOG"), - STRIPPED_OAK_LOG(0, "LOG"), - STRIPPED_OAK_WOOD(0, "LOG"), - STRIPPED_SPRUCE_LOG(1, "LOG"), - STRIPPED_SPRUCE_WOOD(1, "LOG"), - STRUCTURE_BLOCK(0, ""), - STRUCTURE_VOID(0, "1.10", "BARRIER/1.9"), // Originally developers used barrier blocks for its purpose. - SUGAR(0, ""), - SUGAR_CANE(0, "SUGAR_CANE_BLOCK"), - SUNFLOWER(0, "DOUBLE_PLANT"), - SUSPICIOUS_STEW(0, "1.14", "MUSHROOM_STEW"), - SWEET_BERRIES(0, "1.14"), - SWEET_BERRY_BUSH(0, "1.14", "GRASS"), - TALL_GRASS(2, "DOUBLE_PLANT"), - TALL_SEAGRASS(0, "1.13"), - TERRACOTTA(0, "HARD_CLAY"), - TIPPED_ARROW(0, ""), - TNT(0, ""), - TNT_MINECART(0, "EXPLOSIVE_MINECART"), - TORCH(0, ""), - TOTEM_OF_UNDYING(0, "TOTEM"), - TRADER_LLAMA_SPAWN_EGG(103, "1.14", "MONSTER_EGG"), - TRAPPED_CHEST(0, ""), - TRIDENT(0, "1.13"), - TRIPWIRE(0, ""), - TRIPWIRE_HOOK(0, ""), - TROPICAL_FISH(2, "RAW_FISH"), - TROPICAL_FISH_BUCKET(0, "1.13", "BUCKET", "WATER_BUCKET"), - TROPICAL_FISH_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), - TUBE_CORAL(0, "1.13"), - TUBE_CORAL_BLOCK(0, "1.13"), - TUBE_CORAL_FAN(0, "1.13"), - TUBE_CORAL_WALL_FAN(0, ""), - TURTLE_EGG(0, "1.13", "EGG"), - TURTLE_HELMET(0, "1.13"), - TURTLE_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), - VEX_SPAWN_EGG(35, "MONSTER_EGG"), - VILLAGER_SPAWN_EGG(120, "MONSTER_EGG"), - VINDICATOR_SPAWN_EGG(36, "MONSTER_EGG"), - VINE(0, ""), - VOID_AIR(0, "AIR"), - WALL_TORCH(0, "TORCH"), - WANDERING_TRADER_SPAWN_EGG(0, "1.14", "VILLAGER_SPAWN_EGG"), - WATER(0, "STATIONARY_WATER"), - WATER_BUCKET(0, ""), - WET_SPONGE(1, "SPONGE"), - WHEAT(0, "CROPS"), - WHEAT_SEEDS(0, "SEEDS"), - WHITE_BANNER(15, "BANNER", "STANDING_BANNER"), - WHITE_BED(0, "BED", "BED_BLOCK"), - WHITE_CARPET(0, "CARPET"), - WHITE_CONCRETE(0, "CONCRETE"), - WHITE_CONCRETE_POWDER(0, "CONCRETE_POWDER"), - WHITE_DYE(15, "1.14", "INK_SACK", "BONE_MEAL"), - WHITE_GLAZED_TERRACOTTA(0, "1.12", "HARD_CLAY", "STAINED_CLAY", "WHITE_TERRACOTTA"), - WHITE_SHULKER_BOX(0, ""), - WHITE_STAINED_GLASS(0, "STAINED_GLASS"), - WHITE_STAINED_GLASS_PANE(0, "THIN_GLASS", "STAINED_GLASS_PANE"), - WHITE_TERRACOTTA(0, "HARD_CLAY", "TERRACOTTA"), - WHITE_TULIP(6, "RED_ROSE"), - WHITE_WALL_BANNER(15, "WALL_BANNER"), - WHITE_WOOL(0, "WOOL"), - WITCH_SPAWN_EGG(66, "MONSTER_EGG"), - WITHER_ROSE(0, "1.14", "BLACK_DYE"), - WITHER_SKELETON_SKULL(1, "SKULL", "SKULL_ITEM"), - WITHER_SKELETON_SPAWN_EGG(5, "MONSTER_EGG"), - WITHER_SKELETON_WALL_SKULL(1, "SKULL", "SKULL_ITEM"), - WOLF_SPAWN_EGG(95, "MONSTER_EGG"), - WOODEN_AXE(0, "WOOD_AXE"), - WOODEN_HOE(0, "WOOD_HOE"), - WOODEN_PICKAXE(0, "WOOD_PICKAXE"), - WOODEN_SHOVEL(0, "WOOD_SPADE"), - WOODEN_SWORD(0, "WOOD_SWORD"), - WRITABLE_BOOK(0, "BOOK_AND_QUILL"), - WRITTEN_BOOK(0, ""), - YELLOW_BANNER(11, "BANNER", "STANDING_BANNER"), - YELLOW_BED(4, "BED", "BED_BLOCK"), - YELLOW_CARPET(4, "CARPET"), - YELLOW_CONCRETE(4, "CONCRETE"), - YELLOW_CONCRETE_POWDER(4, "CONCRETE_POWDER"), - YELLOW_DYE(11, "INK_SACK", "DANDELION_YELLOW"), - YELLOW_GLAZED_TERRACOTTA(4, "1.12", "HARD_CLAY", "STAINED_CLAY", "YELLOW_TERRACOTTA"), - YELLOW_SHULKER_BOX(0, ""), - YELLOW_STAINED_GLASS(4, "STAINED_GLASS"), - YELLOW_STAINED_GLASS_PANE(4, "THIN_GLASS", "STAINED_GLASS_PANE"), - YELLOW_TERRACOTTA(4, "HARD_CLAY", "STAINED_CLAY"), - YELLOW_WALL_BANNER(11, "WALL_BANNER"), - YELLOW_WOOL(4, "WOOL"), - ZOMBIE_HEAD(2, "SKULL", "SKULL_ITEM"), - ZOMBIE_HORSE_SPAWN_EGG(29, "MONSTER_EGG"), - ZOMBIE_PIGMAN_SPAWN_EGG(57, "MONSTER_EGG"), - ZOMBIE_SPAWN_EGG(54, "MONSTER_EGG"), - ZOMBIE_VILLAGER_SPAWN_EGG(27, "MONSTER_EGG"), - ZOMBIE_WALL_HEAD(2, "SKULL", "SKULL_ITEM"); + ACACIA_BOAT(0, "BOAT_ACACIA"), + ACACIA_BUTTON(0, "WOOD_BUTTON"), + ACACIA_DOOR(0, "ACACIA_DOOR_ITEM"), + ACACIA_FENCE(0, ""), + ACACIA_FENCE_GATE(0, ""), + ACACIA_LEAVES(0, "LEAVES_2"), + ACACIA_LOG(0, "LOG_2"), + ACACIA_PLANKS(4, "WOOD"), + ACACIA_PRESSURE_PLATE(0, "WOOD_PLATE"), + ACACIA_SAPLING(4, "SAPLING"), + ACACIA_SIGN(0, "SIGN"), + ACACIA_SLAB(4, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + ACACIA_STAIRS(0, ""), + ACACIA_TRAPDOOR(0, "TRAP_DOOR"), + ACACIA_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), + ACACIA_WOOD(0, "LOG_2"), + ACTIVATOR_RAIL(0, ""), + AIR(0, ""), + ALLIUM(2, "RED_ROSE"), + ANDESITE(5, "STONEZ"), + ANDESITE_SLAB(0, ""), + ANDESITE_STAIRS(0, ""), + ANDESITE_WALL(0, ""), + ANVIL(0, ""), + APPLE(0, ""), + ARMOR_STAND(0, ""), + ARROW(0, ""), + ATTACHED_MELON_STEM(7, "MELON_STEM"), + ATTACHED_PUMPKIN_STEM(7, "PUMPKIN_STEM"), + AZURE_BLUET(3, "RED_ROSE"), + BAKED_POTATO(0, ""), + BAMBOO(0, "1.14", "SUGAR_CANE"), + BAMBOO_SAPLING(0, "1.14"), + BARREL(0, "1.14", "CHEST"), + BARRIER(0, ""), + BAT_SPAWN_EGG(65, "MONSTER_EGG"), + BEACON(0, ""), + BEDROCK(0, ""), + BEEF(0, "RAW_BEEF"), + BEETROOT(0, "BEETROOT_BLOCK"), + BEETROOTS(0, "BEETROOT"), + BEETROOT_SEEDS(0, ""), + BEETROOT_SOUP(0, ""), + BELL(0, "1.14"), + BIRCH_BOAT(0, "BOAT_BIRCH"), + BIRCH_BUTTON(0, "WOOD_BUTTON"), + BIRCH_DOOR(0, "BIRCH_DOOR_ITEM"), + BIRCH_FENCE(0, ""), + BIRCH_FENCE_GATE(0, ""), + BIRCH_LEAVES(2, "LEAVES"), + BIRCH_LOG(2, "LOG"), + BIRCH_PLANKS(2, "WOOD"), + BIRCH_PRESSURE_PLATE(0, "WOOD_PLATE"), + BIRCH_SAPLING(2, "SAPLING"), + BIRCH_SIGN(0, "SIGN"), + BIRCH_SLAB(2, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + BIRCH_STAIRS(0, "BIRCH_WOOD_STAIRS"), + BIRCH_TRAPDOOR(0, "TRAP_DOOR"), + BIRCH_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), + BIRCH_WOOD(2, "LOG"), + BLACK_BANNER(0, "BANNER", "STANDING_BANNER"), + BLACK_BED(15, "BED", "BED_BLOCK"), + BLACK_CARPET(15, "CARPET"), + BLACK_CONCRETE(15, "CONCRETE"), + BLACK_CONCRETE_POWDER(15, "CONCRETE_POWDER"), + BLACK_DYE(0, "1.14", "INK_SACK"), + BLACK_GLAZED_TERRACOTTA(15, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLACK_TERRACOTTA"), + BLACK_SHULKER_BOX(0, ""), + BLACK_STAINED_GLASS(15, "STAINED_GLASS"), + BLACK_STAINED_GLASS_PANE(15, "STAINED_GLASS_PANE"), + BLACK_TERRACOTTA(15, "HARD_CLAY", "STAINED_CLAY"), + BLACK_WALL_BANNER(0, "WALL_BANNER"), + BLACK_WOOL(15, "WOOL"), + BLAST_FURNACE(0, "1.14", "FURNACE"), + BLAZE_POWDER(0, ""), + BLAZE_ROD(0, ""), + BLAZE_SPAWN_EGG(61, "MONSTER_EGG"), + BLUE_BANNER(11, "BANNER", "STANDING_BANNER"), + BLUE_BED(4, "BED", "BED_BLOCK"), + BLUE_CARPET(11, "CARPET"), + BLUE_CONCRETE(11, "CONCRETE"), + BLUE_CONCRETE_POWDER(11, "CONCRETE_POWDER"), + BLUE_DYE(4, "INK_SACK", "LAPIS_LAZULI"), + BLUE_GLAZED_TERRACOTTA(11, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLUE_TERRACOTTA"), + BLUE_ICE(0, "1.13", "PACKED_ICE"), + BLUE_ORCHID(1, "RED_ROSE"), + BLUE_SHULKER_BOX(0, ""), + BLUE_STAINED_GLASS(11, "STAINED_GLASS"), + BLUE_STAINED_GLASS_PANE(11, "THIN_GLASS", "STAINED_GLASS_PANE"), + BLUE_TERRACOTTA(11, "STAINED_CLAY"), + BLUE_WALL_BANNER(11, "WALL_BANNER"), + BLUE_WOOL(11, "WOOL"), + BONE(0, ""), + BONE_BLOCK(0, ""), + BONE_MEAL(15, "INK_SACK"), + BOOK(0, ""), + BOOKSHELF(0, ""), + BOW(0, ""), + BOWL(0, ""), + BRAIN_CORAL(0, "1.13"), + BRAIN_CORAL_BLOCK(0, "1.13"), + BRAIN_CORAL_FAN(0, "1.13"), + BRAIN_CORAL_WALL_FAN(0, ""), + BREAD(0, ""), + BREWING_STAND(0, "BREWING_STAND_ITEM"), + BRICK(0, "CLAY_BRICK"), + BRICKS(0, "BRICK"), + BRICK_SLAB(4, "STEP"), + BRICK_STAIRS(0, ""), + BRICK_WALL(0, ""), + BROWN_BANNER(3, "BANNER", "STANDING_BANNER"), + BROWN_BED(12, "BED", "BED_BLOCK"), + BROWN_DYE(3, "INK_SACK", "COCOA", "COCOA_BEANS"), + BROWN_CARPET(12, "CARPET"), + BROWN_CONCRETE(12, "CONCRETE"), + BROWN_CONCRETE_POWDER(12, "CONCRETE_POWDER"), + BROWN_GLAZED_TERRACOTTA(12, "1.12", "HARD_CLAY", "STAINED_CLAY", "BROWN_TERRACOTTA"), + BROWN_MUSHROOM(0, ""), + BROWN_MUSHROOM_BLOCK(0, "BROWN_MUSHROOM", "HUGE_MUSHROOM_1"), + BROWN_SHULKER_BOX(0, ""), + BROWN_STAINED_GLASS(12, "STAINED_GLASS"), + BROWN_STAINED_GLASS_PANE(12, "THIN_GLASS", "STAINED_GLASS_PANE"), + BROWN_TERRACOTTA(12, "STAINED_CLAY"), + BROWN_WALL_BANNER(3, "WALL_BANNER"), + BROWN_WOOL(12, "WOOL"), + BUBBLE_COLUMN(0, "1.13"), + BUBBLE_CORAL(0, "1.13"), + BUBBLE_CORAL_BLOCK(0, "1.13"), + BUBBLE_CORAL_FAN(0, "1.13"), + BUBBLE_CORAL_WALL_FAN(0, ""), + BUCKET(0, ""), + CACTUS(0, ""), + CAKE(0, "CAKE_BLOCK"), + CAMPFIRE(0, "1.14"), + CARROT(0, "CARROT_ITEM"), + CARROTS(0, "CARROT"), + CARROT_ON_A_STICK(0, "CARROT_STICK"), + CARTOGRAPHY_TABLE(0, "1.14", "CRAFTING_TABLE"), + CARVED_PUMPKIN(1, "PUMPKIN"), + CAT_SPAWN_EGG(0, ""), + CAULDRON(0, "CAULDRON_ITEM"), + CAVE_AIR(0, "AIR"), + CAVE_SPIDER_SPAWN_EGG(59, "MONSTER_EGG"), + CHAINMAIL_BOOTS(0, ""), + CHAINMAIL_CHESTPLATE(0, ""), + CHAINMAIL_HELMET(0, ""), + CHAINMAIL_LEGGINGS(0, ""), + CHAIN_COMMAND_BLOCK(0, "COMMAND", "COMMAND_CHAIN"), + CHARCOAL(1, "COAL"), + CHEST(0, "LOCKED_CHEST"), + CHEST_MINECART(0, "STORAGE_MINECART"), + CHICKEN(0, "RAW_CHICKEN"), + CHICKEN_SPAWN_EGG(93, "MONSTER_EGG"), + CHIPPED_ANVIL(1, "ANVIL"), + CHISELED_QUARTZ_BLOCK(1, "QUARTZ_BLOCK"), + CHISELED_RED_SANDSTONE(1, "RED_SANDSTONE"), + CHISELED_SANDSTONE(1, "SANDSTONE"), + CHISELED_STONE_BRICKS(3, "SMOOTH_BRICK"), + CHORUS_FLOWER(0, ""), + CHORUS_FRUIT(0, ""), + CHORUS_PLANT(0, ""), + CLAY(0, ""), + CLAY_BALL(0, ""), + CLOCK(0, "WATCH"), + COAL(0, ""), + COAL_BLOCK(0, ""), + COAL_ORE(0, ""), + COARSE_DIRT(1, "DIRT"), + COBBLESTONE(0, ""), + COBBLESTONE_SLAB(3, "STEP"), + COBBLESTONE_STAIRS(0, ""), + COBBLESTONE_WALL(0, "COBBLE_WALL"), + COBWEB(0, "WEB"), + COCOA_BEANS(3, "INK_SACK", "COCOA"), + COD(0, "RAW_FISH"), + COD_BUCKET(0, "1.13", "BUCKET", "WATER_BUCKET"), + COD_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), + COMMAND_BLOCK(0, "COMMAND"), + COMMAND_BLOCK_MINECART(0, "COMMAND_MINECART"), + COMPARATOR(0, "REDSTONE_COMPARATOR", "REDSTONE_COMPARATOR_ON", "REDSTONE_COMPARATOR_OFF"), + COMPASS(0, ""), + COMPOSTER(0, "1.14", "CAULDRON"), + CONDUIT(0, "1.13"), + COOKED_BEEF(0, ""), + COOKED_CHICKEN(0, ""), + COOKED_COD(0, "COOKED_FISH"), + COOKED_MUTTON(0, ""), + COOKED_PORKCHOP(0, "PORK", "GRILLED_PORK"), + COOKED_RABBIT(0, ""), + COOKED_SALMON(1, "COOKED_FISH"), + COOKIE(0, ""), + CORNFLOWER(4, "1.14", "BLUE_DYE"), + COW_SPAWN_EGG(92, "MONSTER_EGG"), + CRACKED_STONE_BRICKS(2, "SMOOTH_BRICK"), + CRAFTING_TABLE(0, "WORKBENCH"), + CREEPER_BANNER_PATTERN(0, ""), + CREEPER_HEAD(4, "SKULL", "SKULL_ITEM"), + CREEPER_SPAWN_EGG(50, "MONSTER_EGG"), + CREEPER_WALL_HEAD(4, "SKULL", "SKULL_ITEM"), + CROSSBOW(0, ""), + CUT_RED_SANDSTONE(0, "1.13"), + CUT_RED_SANDSTONE_SLAB(0, "STONE_SLAB2"), + CUT_SANDSTONE(0, "1.13"), + CUT_SANDSTONE_SLAB(0, "STEP"), + CYAN_BANNER(6, "BANNER", "STANDING_BANNER"), + CYAN_BED(9, "BED", "BED_BLOCK"), + CYAN_CARPET(9, "CARPET"), + CYAN_CONCRETE(9, "CONCRETE"), + CYAN_CONCRETE_POWDER(9, "CONCRETE_POWDER"), + CYAN_DYE(6, "INK_SACK"), + CYAN_GLAZED_TERRACOTTA(9, "1.12", "HARD_CLAY", "STAINED_CLAY", "CYAN_TERRACOTTA"), + CYAN_SHULKER_BOX(0, ""), + CYAN_STAINED_GLASS(9, "STAINED_GLASS"), + CYAN_STAINED_GLASS_PANE(9, "STAINED_GLASS_PANE"), + CYAN_TERRACOTTA(9, "HARD_CLAY", "STAINED_CLAY"), + CYAN_WALL_BANNER(6, "WALL_BANNER"), + CYAN_WOOL(9, "WOOL"), + DAMAGED_ANVIL(2, "ANVIL"), + DANDELION(0, "YELLOW_FLOWER"), + DARK_OAK_BOAT(0, "BOAT_DARK_OAK"), + DARK_OAK_BUTTON(0, "WOOD_BUTTON"), + DARK_OAK_DOOR(0, "DARK_OAK_DOOR_ITEM"), + DARK_OAK_FENCE(0, ""), + DARK_OAK_FENCE_GATE(0, ""), + DARK_OAK_LEAVES(1, "LEAVES", "LEAVES_2"), + DARK_OAK_LOG(1, "LOG", "LOG_2"), + DARK_OAK_PLANKS(5, "WOOD"), + DARK_OAK_PRESSURE_PLATE(0, "WOOD_PLATE"), + DARK_OAK_SAPLING(5, "SAPLING"), + DARK_OAK_SIGN(0, "SIGN"), + DARK_OAK_SLAB(0, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + DARK_OAK_STAIRS(0, ""), + DARK_OAK_TRAPDOOR(0, "TRAP_DOOR"), + DARK_OAK_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), + DARK_OAK_WOOD(1, "LOG", "LOG_2"), + DARK_PRISMARINE(1, "PRISMARINE"), + DARK_PRISMARINE_SLAB(0, "1.13"), + DARK_PRISMARINE_STAIRS(0, "1.13"), + DAYLIGHT_DETECTOR(0, "DAYLIGHT_DETECTOR_INVERTED"), + DEAD_BRAIN_CORAL(0, ""), + DEAD_BRAIN_CORAL_BLOCK(0, "1.13"), + DEAD_BRAIN_CORAL_FAN(0, ""), + DEAD_BRAIN_CORAL_WALL_FAN(0, ""), + DEAD_BUBBLE_CORAL(0, ""), + DEAD_BUBBLE_CORAL_BLOCK(0, "1.13"), + DEAD_BUBBLE_CORAL_FAN(0, ""), + DEAD_BUBBLE_CORAL_WALL_FAN(0, ""), + DEAD_BUSH(0, ""), + DEAD_FIRE_CORAL(0, ""), + DEAD_FIRE_CORAL_BLOCK(0, "1.13"), + DEAD_FIRE_CORAL_FAN(0, ""), + DEAD_FIRE_CORAL_WALL_FAN(0, ""), + DEAD_HORN_CORAL(0, ""), + DEAD_HORN_CORAL_BLOCK(0, "1.13"), + DEAD_HORN_CORAL_FAN(0, ""), + DEAD_HORN_CORAL_WALL_FAN(0, ""), + DEAD_TUBE_CORAL(0, ""), + DEAD_TUBE_CORAL_BLOCK(0, "1.13"), + DEAD_TUBE_CORAL_FAN(0, ""), + DEAD_TUBE_CORAL_WALL_FAN(0, ""), + DEBUG_STICK(0, "1.13", "STICK"), + DETECTOR_RAIL(0, ""), + DIAMOND(0, ""), + DIAMOND_AXE(0, ""), + DIAMOND_BLOCK(0, ""), + DIAMOND_BOOTS(0, ""), + DIAMOND_CHESTPLATE(0, ""), + DIAMOND_HELMET(0, ""), + DIAMOND_HOE(0, ""), + DIAMOND_HORSE_ARMOR(0, "DIAMOND_BARDING"), + DIAMOND_LEGGINGS(0, ""), + DIAMOND_ORE(0, ""), + DIAMOND_PICKAXE(0, ""), + DIAMOND_SHOVEL(0, "DIAMOND_SPADE"), + DIAMOND_SWORD(0, ""), + DIORITE(3, "1.13"), + DIORITE_SLAB(0, ""), + DIORITE_STAIRS(0, ""), + DIORITE_WALL(0, ""), + DIRT(0, ""), + DISPENSER(0, ""), + DOLPHIN_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), + DONKEY_SPAWN_EGG(32, "MONSTER_EGG"), + DRAGON_BREATH(0, "DRAGONS_BREATH"), + DRAGON_EGG(0, ""), + DRAGON_HEAD(5, "SKULL", "SKULL_ITEM"), + DRAGON_WALL_HEAD(5, "SKULL", "SKULL_ITEM"), + DRIED_KELP(0, "1.13"), + DRIED_KELP_BLOCK(0, "1.13"), + DROPPER(0, ""), + DROWNED_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), + EGG(0, ""), + ELDER_GUARDIAN_SPAWN_EGG(4, "MONSTER_EGG"), + ELYTRA(0, ""), + EMERALD(0, ""), + EMERALD_BLOCK(0, ""), + EMERALD_ORE(0, ""), + ENCHANTED_BOOK(0, ""), + ENCHANTED_GOLDEN_APPLE(1, "GOLDEN_APPLE"), + ENCHANTING_TABLE(0, "ENCHANTMENT_TABLE"), + ENDERMAN_SPAWN_EGG(58, "MONSTER_EGG"), + ENDERMITE_SPAWN_EGG(67, "MONSTER_EGG"), + ENDER_CHEST(0, ""), + ENDER_EYE(0, "EYE_OF_ENDER"), + ENDER_PEARL(0, ""), + END_CRYSTAL(0, ""), + END_GATEWAY(0, ""), + END_PORTAL(0, "ENDER_PORTAL"), + END_PORTAL_FRAME(0, "ENDER_PORTAL_FRAME"), + END_ROD(0, ""), + END_STONE(0, "ENDER_STONE"), + END_STONE_BRICKS(0, "END_BRICKS"), + END_STONE_BRICK_SLAB(4, "STEP"), + END_STONE_BRICK_STAIRS(0, "SMOOTH_STAIRS"), + END_STONE_BRICK_WALL(0, ""), + EVOKER_SPAWN_EGG(34, "MONSTER_EGG"), + EXPERIENCE_BOTTLE(0, "EXP_BOTTLE"), + FARMLAND(0, "SOIL"), + FEATHER(0, ""), + FERMENTED_SPIDER_EYE(0, ""), + FERN(2, "LONG_GRASS"), + FILLED_MAP(0, "MAP"), + FIRE(0, ""), + FIREWORK_ROCKET(0, "FIREWORK"), + FIREWORK_STAR(0, "FIREWORK_CHARGE"), + FIRE_CHARGE(0, "FIREBALL"), + FIRE_CORAL(0, "1.13"), + FIRE_CORAL_BLOCK(0, "1.13"), + FIRE_CORAL_FAN(0, "1.13"), + FIRE_CORAL_WALL_FAN(0, ""), + FISHING_ROD(0, ""), + FLETCHING_TABLE(0, "1.14", "CRAFTING_TABLE"), + FLINT(0, ""), + FLINT_AND_STEEL(0, ""), + FLOWER_BANNER_PATTERN(0, ""), + FLOWER_POT(0, "FLOWER_POT_ITEM"), + FOX_SPAWN_EGG(0, "1.14"), + FROSTED_ICE(0, ""), + FURNACE(0, "BURNING_FURNACE"), + FURNACE_MINECART(0, "POWERED_MINECART"), + GHAST_SPAWN_EGG(56, "MONSTER_EGG"), + GHAST_TEAR(0, ""), + GLASS(0, ""), + GLASS_BOTTLE(0, ""), + GLASS_PANE(0, "THIN_GLASS"), + GLISTERING_MELON_SLICE(0, "SPECKLED_MELON"), + GLOBE_BANNER_PATTERN(0, ""), + GLOWSTONE(0, ""), + GLOWSTONE_DUST(0, ""), + GOLDEN_APPLE(0, ""), + GOLDEN_AXE(0, "GOLD_AXE"), + GOLDEN_BOOTS(0, "GOLD_BOOTS"), + GOLDEN_CARROT(0, ""), + GOLDEN_CHESTPLATE(0, "GOLD_CHESTPLATE"), + GOLDEN_HELMET(0, "GOLD_HELMET"), + GOLDEN_HOE(0, "GOLD_HOE"), + GOLDEN_HORSE_ARMOR(0, "GOLD_BARDING"), + GOLDEN_LEGGINGS(0, "GOLD_LEGGINGS"), + GOLDEN_PICKAXE(0, "GOLD_PICKAXE"), + GOLDEN_SHOVEL(0, "GOLD_SPADE"), + GOLDEN_SWORD(0, "GOLD_SWORD"), + GOLD_BLOCK(0, ""), + GOLD_INGOT(0, ""), + GOLD_NUGGET(0, ""), + GOLD_ORE(0, ""), + GRANITE(1, "1.13"), + GRANITE_SLAB(0, ""), + GRANITE_STAIRS(0, ""), + GRANITE_WALL(0, ""), + GRASS(0, ""), + GRASS_BLOCK(0, "GRASS"), + GRASS_PATH(0, ""), + GRAVEL(0, ""), + GRAY_BANNER(8, "BANNER", "STANDING_BANNER"), + GRAY_BED(7, "BED", "BED_BLOCK"), + GRAY_CARPET(7, "CARPET"), + GRAY_CONCRETE(7, "CONCRETE"), + GRAY_CONCRETE_POWDER(7, "CONCRETE_POWDER"), + GRAY_DYE(8, "INK_SACK"), + GRAY_GLAZED_TERRACOTTA(7, "1.12", "HARD_CLAY", "STAINED_CLAY", "GRAY_TERRACOTTA"), + GRAY_SHULKER_BOX(0, ""), + GRAY_STAINED_GLASS(8, "STAINED_GLASS"), + GRAY_STAINED_GLASS_PANE(7, "THIN_GLASS", "STAINED_GLASS_PANE"), + GRAY_TERRACOTTA(7, "HARD_CLAY", "STAINED_CLAY"), + GRAY_WALL_BANNER(8, "WALL_BANNER"), + GRAY_WOOL(8, "WOOL"), + GREEN_BANNER(2, "BANNER", "STANDING_BANNER"), + GREEN_BED(13, "BED", "BED_BLOCK"), + GREEN_CARPET(13, "CARPET"), + GREEN_CONCRETE(13, "CONCRETE"), + GREEN_CONCRETE_POWDER(13, "CONCRETE_POWDER"), + GREEN_DYE(2, "INK_SACK", "CACTUS_GREEN"), + GREEN_GLAZED_TERRACOTTA(13, "1.12", "HARD_CLAY", "STAINED_CLAY", "GREEN_TERRACOTTA"), + GREEN_SHULKER_BOX(0, ""), + GREEN_STAINED_GLASS(13, "STAINED_GLASS"), + GREEN_STAINED_GLASS_PANE(13, "THIN_GLASS", "STAINED_GLASS_PANE"), + GREEN_TERRACOTTA(13, "HARD_CLAY", "STAINED_CLAY"), + GREEN_WALL_BANNER(2, "WALL_BANNER"), + GREEN_WOOL(13, "WOOL"), + GRINDSTONE(0, "1.14", "ANVIL"), + GUARDIAN_SPAWN_EGG(68, "MONSTER_EGG"), + GUNPOWDER(0, "SULPHUR"), + HAY_BLOCK(0, ""), + HEART_OF_THE_SEA(0, "1.13"), + HEAVY_WEIGHTED_PRESSURE_PLATE(0, "IRON_PLATE"), + HOPPER(0, ""), + HOPPER_MINECART(0, ""), + HORN_CORAL(0, "1.13"), + HORN_CORAL_BLOCK(0, "1.13"), + HORN_CORAL_FAN(0, "1.13"), + HORN_CORAL_WALL_FAN(0, ""), + HORSE_SPAWN_EGG(100, "MONSTER_EGG"), + HUSK_SPAWN_EGG(23, "MONSTER_EGG"), + ICE(0, ""), + INFESTED_CHISELED_STONE_BRICKS(5, "MONSTER_EGGS", "SMOOTH_BRICK"), + INFESTED_COBBLESTONE(1, "MONSTER_EGGS"), + INFESTED_CRACKED_STONE_BRICKS(4, "MONSTER_EGGS", "SMOOTH_BRICK"), + INFESTED_MOSSY_STONE_BRICKS(3, "MONSTER_EGGS"), + INFESTED_STONE(0, "MONSTER_EGGS"), + INFESTED_STONE_BRICKS(2, "MONSTER_EGGS", "SMOOTH_BRICK"), + INK_SAC(0, "INK_SACK"), + IRON_AXE(0, ""), + IRON_BARS(0, "IRON_FENCE"), + IRON_BLOCK(0, ""), + IRON_BOOTS(0, ""), + IRON_CHESTPLATE(0, ""), + IRON_DOOR(0, "IRON_DOOR_BLOCK"), + IRON_HELMET(0, ""), + IRON_HOE(0, ""), + IRON_HORSE_ARMOR(0, "IRON_BARDING"), + IRON_INGOT(0, ""), + IRON_LEGGINGS(0, ""), + IRON_NUGGET(0, ""), + IRON_ORE(0, ""), + IRON_PICKAXE(0, ""), + IRON_SHOVEL(0, "IRON_SPADE"), + IRON_SWORD(0, ""), + IRON_TRAPDOOR(0, ""), + ITEM_FRAME(0, ""), + JACK_O_LANTERN(0, ""), + JIGSAW(0, "1.14", "COMMAND_BLOCK", "STRUCTURE_BLOCK"), + JUKEBOX(0, ""), + JUNGLE_BOAT(0, "BOAT_JUNGLE"), + JUNGLE_BUTTON(0, "WOOD_BUTTON"), + JUNGLE_DOOR(0, "JUNGLE_DOOR_ITEM"), + JUNGLE_FENCE(0, ""), + JUNGLE_FENCE_GATE(0, ""), + JUNGLE_LEAVES(3, "LEAVES"), + JUNGLE_LOG(3, "LOG"), + JUNGLE_PLANKS(3, "WOOD"), + JUNGLE_PRESSURE_PLATE(0, "WOOD_PLATE"), + JUNGLE_SAPLING(3, "SAPLING"), + JUNGLE_SIGN(0, "SIGN"), + JUNGLE_SLAB(3, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + JUNGLE_STAIRS(0, "JUNGLE_WOOD_STAIRS"), + JUNGLE_TRAPDOOR(0, "TRAP_DOOR"), + JUNGLE_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), + JUNGLE_WOOD(3, "LOG"), + KELP(0, "1.13"), + KELP_PLANT(0, "1.13"), + KNOWLEDGE_BOOK(0, ""), + LADDER(0, ""), + LANTERN(0, "1.14", "SEA_LANTERN"), + LAPIS_BLOCK(0, ""), + LAPIS_LAZULI(4, "INK_SACK"), + LAPIS_ORE(0, ""), + LARGE_FERN(3, "DOUBLE_PLANT"), + LAVA(0, "STATIONARY_LAVA"), + LAVA_BUCKET(0, ""), + LEAD(0, "LEASH"), + LEATHER(0, ""), + LEATHER_BOOTS(0, ""), + LEATHER_CHESTPLATE(0, ""), + LEATHER_HELMET(0, ""), + LEATHER_HORSE_ARMOR(0, "1.14", "IRON_HORSE_ARMOR"), + LEATHER_LEGGINGS(0, ""), + LECTERN(0, "1.14", "BOOKSHELF"), + LEVER(0, ""), + LIGHT_BLUE_BANNER(11, "BANNER", "STANDING_BANNER"), + LIGHT_BLUE_BED(3, "BED", "BED_BLOCK"), + LIGHT_BLUE_CARPET(3, "CARPET"), + LIGHT_BLUE_CONCRETE(3, "CONCRETE"), + LIGHT_BLUE_CONCRETE_POWDER(3, "CONCRETE_POWDER"), + LIGHT_BLUE_DYE(12, "INK_SACK"), + LIGHT_BLUE_GLAZED_TERRACOTTA(3, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_BLUE_TERRACOTTA"), + LIGHT_BLUE_SHULKER_BOX(0, ""), + LIGHT_BLUE_STAINED_GLASS(11, "STAINED_GLASS"), + LIGHT_BLUE_STAINED_GLASS_PANE(3, "THIN_GLASS", "STAINED_GLASS_PANE"), + LIGHT_BLUE_TERRACOTTA(3, "STAINED_CLAY"), + LIGHT_BLUE_WALL_BANNER(12, "WALL_BANNER", "BANNER", "STANDING_BANNER"), + LIGHT_BLUE_WOOL(11, "WOOL"), + LIGHT_GRAY_BANNER(7, "BANNER", "STANDING_BANNER"), + LIGHT_GRAY_BED(7, "BED", "BED_BLOCK"), + LIGHT_GRAY_CARPET(8, "CARPET"), + LIGHT_GRAY_CONCRETE(8, "CONCRETE"), + LIGHT_GRAY_CONCRETE_POWDER(8, "CONCRETE_POWDER"), + LIGHT_GRAY_DYE(7, "INK_SACK"), + LIGHT_GRAY_GLAZED_TERRACOTTA(8, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_GRAY_TERRACOTTA", "SILVER_GLAZED_TERRACOTTA/1.13"), + LIGHT_GRAY_SHULKER_BOX(0, "SILVER_SHULKER_BOX"), + LIGHT_GRAY_STAINED_GLASS(8, "STAINED_GLASS"), + LIGHT_GRAY_STAINED_GLASS_PANE(8, "THIN_GLASS", "STAINED_GLASS_PANE"), + LIGHT_GRAY_TERRACOTTA(8, "HARD_CLAY", "STAINED_CLAY"), + LIGHT_GRAY_WALL_BANNER(7, "WALL_BANNER"), + LIGHT_GRAY_WOOL(8, "WOOL"), + LIGHT_WEIGHTED_PRESSURE_PLATE(0, "GOLD_PLATE"), + LILAC(1, "DOUBLE_PLANT"), + LILY_OF_THE_VALLEY(15, "1.14", "WHITE_DYE"), + LILY_PAD(0, "WATER_LILY"), + LIME_BANNER(10, "BANNER", "STANDING_BANNER"), + LIME_BED(5, "BED", "BED_BLOCK"), + LIME_CARPET(5, "CARPET"), + LIME_CONCRETE(5, "CONCRETE"), + LIME_CONCRETE_POWDER(5, "CONCRETE_POWDER"), + LIME_DYE(10, "INK_SACK"), + LIME_GLAZED_TERRACOTTA(5, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIME_TERRACOTTA"), + LIME_SHULKER_BOX(0, ""), + LIME_STAINED_GLASS(5, "STAINED_GLASS"), + LIME_STAINED_GLASS_PANE(5, "STAINED_GLASS_PANE"), + LIME_TERRACOTTA(5, "HARD_CLAY", "STAINED_CLAY"), + LIME_WALL_BANNER(10, "WALL_BANNER"), + LIME_WOOL(5, "WOOL"), + LINGERING_POTION(0, ""), + LLAMA_SPAWN_EGG(103, "MONSTER_EGG"), + LOOM(0, "1.14"), + MAGENTA_BANNER(13, "BANNER", "STANDING_BANNER"), + MAGENTA_BED(2, "BED", "BED_BLOCK"), + MAGENTA_CARPET(2, "CARPET"), + MAGENTA_CONCRETE(2, "CONCRETE"), + MAGENTA_CONCRETE_POWDER(2, "CONCRETE_POWDER"), + MAGENTA_DYE(13, "INK_SACK"), + MAGENTA_GLAZED_TERRACOTTA(2, "1.12", "HARD_CLAY", "STAINED_CLAY", "MAGENTA_TERRACOTTA"), + MAGENTA_SHULKER_BOX(0, ""), + MAGENTA_STAINED_GLASS(2, "STAINED_GLASS"), + MAGENTA_STAINED_GLASS_PANE(2, "THIN_GLASS", "STAINED_GLASS_PANE"), + MAGENTA_TERRACOTTA(2, "HARD_CLAY", "STAINED_CLAY"), + MAGENTA_WALL_BANNER(13, "WALL_BANNER"), + MAGENTA_WOOL(2, "WOOL"), + MAGMA_BLOCK(0, "MAGMA"), + MAGMA_CREAM(0, ""), + MAGMA_CUBE_SPAWN_EGG(62, "MONSTER_EGG"), + MAP(0, "EMPTY_MAP"), + MELON(0, "MELON_BLOCK"), + MELON_SEEDS(0, ""), + MELON_SLICE(0, "MELON"), + MELON_STEM(0, ""), + MILK_BUCKET(0, ""), + MINECART(0, ""), + MOJANG_BANNER_PATTERN(0, ""), + MOOSHROOM_SPAWN_EGG(96, "MONSTER_EGG"), + MOSSY_COBBLESTONE(0, ""), + MOSSY_COBBLESTONE_SLAB(3, "STEP"), + MOSSY_COBBLESTONE_STAIRS(0, ""), + MOSSY_COBBLESTONE_WALL(1, "COBBLE_WALL", "COBBLESTONE_WALL"), + MOSSY_STONE_BRICKS(1, "SMOOTH_BRICK"), + MOSSY_STONE_BRICK_SLAB(4, "STEP"), + MOSSY_STONE_BRICK_STAIRS(0, "SMOOTH_STAIRS"), + MOSSY_STONE_BRICK_WALL(0, ""), + MOVING_PISTON(0, "PISTON_BASE", "PISTON_MOVING_PIECE"), + MULE_SPAWN_EGG(32, "MONSTER_EGG"), + MUSHROOM_STEM(0, "BROWN_MUSHROOM"), + MUSHROOM_STEW(0, "MUSHROOM_SOUP"), + MUSIC_DISC_11(0, "GOLD_RECORD"), + MUSIC_DISC_13(0, "GREEN_RECORD"), + MUSIC_DISC_BLOCKS(0, "RECORD_3"), + MUSIC_DISC_CAT(0, "RECORD_4"), + MUSIC_DISC_CHIRP(0, "RECORD_5"), + MUSIC_DISC_FAR(0, "RECORD_6"), + MUSIC_DISC_MALL(0, "RECORD_7"), + MUSIC_DISC_MELLOHI(0, "RECORD_8"), + MUSIC_DISC_STAL(0, "RECORD_9"), + MUSIC_DISC_STRAD(0, "RECORD_10"), + MUSIC_DISC_WAIT(0, "RECORD_11"), + MUSIC_DISC_WARD(0, "RECORD_12"), + MUTTON(0, ""), + MYCELIUM(0, "MYCEL"), + NAME_TAG(0, ""), + NAUTILUS_SHELL(0, "1.13"), + NETHERRACK(0, ""), + NETHER_BRICK(0, "NETHER_BRICK_ITEM"), + NETHER_BRICKS(0, "NETHER_BRICK"), + NETHER_BRICK_FENCE(0, "NETHER_FENCE"), + NETHER_BRICK_SLAB(4, "STEP"), + NETHER_BRICK_STAIRS(0, ""), + NETHER_BRICK_WALL(0, ""), + NETHER_PORTAL(0, "PORTAL"), + NETHER_QUARTZ_ORE(0, "QUARTZ_ORE"), + NETHER_STAR(0, ""), + NETHER_WART(0, "NETHER_STALK"), + NETHER_WART_BLOCK(0, "NETHER_WARTS"), + NOTE_BLOCK(0, ""), + OAK_BOAT(0, "BOAT"), + OAK_BUTTON(0, "WOOD_BUTTON"), + OAK_DOOR(0, "WOOD_DOOR", "WOODEN_DOOR"), + OAK_FENCE(0, "FENCE"), + OAK_FENCE_GATE(0, "FENCE_GATE"), + OAK_LEAVES(0, "LEAVES"), + OAK_LOG(0, "LOG"), + OAK_PLANKS(0, "WOOD"), + OAK_PRESSURE_PLATE(0, "WOOD_PLATE"), + OAK_SAPLING(0, "SAPLING"), + OAK_SIGN(0, "SIGN"), + OAK_SLAB(0, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + OAK_STAIRS(0, "WOOD_STAIRS"), + OAK_TRAPDOOR(0, "TRAP_DOOR"), + OAK_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), + OAK_WOOD(0, "LOG"), + OBSERVER(0, ""), + OBSIDIAN(0, ""), + OCELOT_SPAWN_EGG(98, "MONSTER_EGG"), + ORANGE_BANNER(14, "BANNER", "STANDING_BANNER"), + ORANGE_BED(1, "BED", "BED_BLOCK"), + ORANGE_CARPET(1, "CARPET"), + ORANGE_CONCRETE(1, "CONCRETE"), + ORANGE_CONCRETE_POWDER(1, "CONCRETE_POWDER"), + ORANGE_DYE(14, "INK_SACK"), + ORANGE_GLAZED_TERRACOTTA(1, "1.12", "HARD_CLAY", "STAINED_CLAY", "ORANGE_TERRACOTTA"), + ORANGE_SHULKER_BOX(0, ""), + ORANGE_STAINED_GLASS(1, "STAINED_GLASS"), + ORANGE_STAINED_GLASS_PANE(1, "STAINED_GLASS_PANE"), + ORANGE_TERRACOTTA(1, "HARD_CLAY", "STAINED_CLAY"), + ORANGE_TULIP(5, "RED_ROSE"), + ORANGE_WALL_BANNER(14, "WALL_BANNER"), + ORANGE_WOOL(1, "WOOL"), + OXEYE_DAISY(8, "RED_ROSE"), + PACKED_ICE(0, ""), + PAINTING(0, ""), + PANDA_SPAWN_EGG(0, "1.14"), + PAPER(0, ""), + PARROT_SPAWN_EGG(105, "MONSTER_EGG"), + PEONY(5, "DOUBLE_PLANT"), + PETRIFIED_OAK_SLAB(0, "WOOD_STEP"), + PHANTOM_MEMBRANE(0, "1.13"), + PHANTOM_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), + PIG_SPAWN_EGG(90, "MONSTER_EGG"), + PILLAGER_SPAWN_EGG(0, "1.14"), + PINK_BANNER(9, "BANNER", "STANDING_BANNER"), + PINK_BED(6, "BED", "BED_BLOCK"), + PINK_CARPET(6, "CARPET"), + PINK_CONCRETE(6, "CONCRETE"), + PINK_CONCRETE_POWDER(6, "CONCRETE_POWDER"), + PINK_DYE(9, "INK_SACK"), + PINK_GLAZED_TERRACOTTA(6, "1.12", "HARD_CLAY", "STAINED_CLAY", "PINK_TERRACOTTA"), + PINK_SHULKER_BOX(0, ""), + PINK_STAINED_GLASS(6, "STAINED_GLASS"), + PINK_STAINED_GLASS_PANE(6, "THIN_GLASS", "STAINED_GLASS_PANE"), + PINK_TERRACOTTA(6, "HARD_CLAY", "STAINED_CLAY"), + PINK_TULIP(7, "RED_ROSE"), + PINK_WALL_BANNER(14, "WALL_BANNER"), + PINK_WOOL(6, "WOOL"), + PISTON(0, "PISTON_BASE"), + PISTON_HEAD(0, "PISTON_EXTENSION"), + PLAYER_HEAD(3, "SKULL", "SKULL_ITEM"), + PLAYER_WALL_HEAD(3, "SKULL", "SKULL_ITEM"), + PODZOL(2, "DIRT"), + POISONOUS_POTATO(0, ""), + POLAR_BEAR_SPAWN_EGG(102, "MONSTER_EGG"), + POLISHED_ANDESITE(6, "1.13"), + POLISHED_ANDESITE_SLAB(0, ""), + POLISHED_ANDESITE_STAIRS(0, ""), + POLISHED_DIORITE(4, "1.13"), + POLISHED_DIORITE_SLAB(0, ""), + POLISHED_DIORITE_STAIRS(0, ""), + POLISHED_GRANITE(2, "1.13"), + POLISHED_GRANITE_SLAB(0, ""), + POLISHED_GRANITE_STAIRS(0, ""), + POPPED_CHORUS_FRUIT(0, "CHORUS_FRUIT_POPPED"), + POPPY(0, "RED_ROSE"), + PORKCHOP(0, "PORK"), + POTATO(0, "POTATO_ITEM"), + POTATOES(0, "POTATO"), + POTION(0, ""), + POTTED_ACACIA_SAPLING(4, "SAPLING", "FLOWER_POT"), + POTTED_ALLIUM(2, "RED_ROSE", "FLOWER_POT"), + POTTED_AZURE_BLUET(3, "RED_ROSE", "FLOWER_POT"), + POTTED_BAMBOO(0, ""), + POTTED_BIRCH_SAPLING(2, "SAPLING", "FLOWER_POT"), + POTTED_BLUE_ORCHID(1, "RED_ROSE", "FLOWER_POT"), + POTTED_BROWN_MUSHROOM(0, "FLOWER_POT"), + POTTED_CACTUS(0, "FLOWER_POT"), + POTTED_CORNFLOWER(0, ""), + POTTED_DANDELION(0, "YELLOW_FLOWER", "FLOWER_POT"), + POTTED_DARK_OAK_SAPLING(5, "SAPLING", "FLOWER_POT"), + POTTED_DEAD_BUSH(0, "FLOWER_POT"), + POTTED_FERN(2, "LONG_GRASS", "FLOWER_POT"), + POTTED_JUNGLE_SAPLING(3, "SAPLING", "FLOWER_POT"), + POTTED_LILY_OF_THE_VALLEY(0, ""), + POTTED_OAK_SAPLING(0, "SAPLING", "FLOWER_POT"), + POTTED_ORANGE_TULIP(5, "RED_ROSE", "FLOWER_POT"), + POTTED_OXEYE_DAISY(8, "RED_ROSE", "FLOWER_POT"), + POTTED_PINK_TULIP(7, "RED_ROSE", "FLOWER_POT"), + POTTED_POPPY(0, "RED_ROSE", "FLOWER_POT"), + POTTED_RED_MUSHROOM(0, "FLOWER_POT"), + POTTED_RED_TULIP(4, "RED_ROSE", "FLOWER_POT"), + POTTED_SPRUCE_SAPLING(1, "SAPLING", "FLOWER_POT"), + POTTED_WHITE_TULIP(6, "RED_ROSE", "FLOWER_POT"), + POTTED_WITHER_ROSE(0, ""), + POWERED_RAIL(0, ""), + PRISMARINE(0, ""), + PRISMARINE_BRICKS(2, "PRISMARINE"), + PRISMARINE_BRICK_SLAB(4, "STEP"), + PRISMARINE_BRICK_STAIRS(0, "1.13"), + PRISMARINE_CRYSTALS(0, ""), + PRISMARINE_SHARD(0, ""), + PRISMARINE_SLAB(0, "1.13"), + PRISMARINE_STAIRS(0, "1.13"), + PRISMARINE_WALL(0, ""), + PUFFERFISH(3, "RAW_FISH"), + PUFFERFISH_BUCKET(0, "1.13", "BUCKET", "WATER_BUCKET"), + PUFFERFISH_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), + PUMPKIN(0, ""), + PUMPKIN_PIE(0, ""), + PUMPKIN_SEEDS(0, ""), + PUMPKIN_STEM(0, ""), + PURPLE_BANNER(5, "BANNER", "STANDING_BANNER"), + PURPLE_BED(10, "BED", "BED_BLOCK"), + PURPLE_CARPET(10, "CARPET"), + PURPLE_CONCRETE(10, "CONCRETE"), + PURPLE_CONCRETE_POWDER(10, "CONCRETE_POWDER"), + PURPLE_DYE(5, "INK_SACK"), + PURPLE_GLAZED_TERRACOTTA(10, "1.12", "HARD_CLAY", "STAINED_CLAY", "PURPLE_TERRACOTTA"), + PURPLE_SHULKER_BOX(0, ""), + PURPLE_STAINED_GLASS(10, "STAINED_GLASS"), + PURPLE_STAINED_GLASS_PANE(10, "THIN_GLASS", "STAINED_GLASS_PANE"), + PURPLE_TERRACOTTA(10, "HARD_CLAY", "STAINED_CLAY"), + PURPLE_WALL_BANNER(5, "WALL_BANNER"), + PURPLE_WOOL(10, "WOOL"), + PURPUR_BLOCK(0, ""), + PURPUR_PILLAR(0, ""), + PURPUR_SLAB(0, "PURPUR_DOUBLE_SLAB"), + PURPUR_STAIRS(0, ""), + QUARTZ(0, ""), + QUARTZ_BLOCK(0, ""), + QUARTZ_PILLAR(2, "QUARTZ_BLOCK"), + QUARTZ_SLAB(7, "STEP"), + QUARTZ_STAIRS(0, ""), + RABBIT(0, ""), + RABBIT_FOOT(0, ""), + RABBIT_HIDE(0, ""), + RABBIT_SPAWN_EGG(101, "MONSTER_EGG"), + RABBIT_STEW(0, ""), + RAIL(0, "RAILS"), + RAVAGER_SPAWN_EGG(0, "1.14"), + REDSTONE(0, ""), + REDSTONE_BLOCK(0, ""), + REDSTONE_LAMP(0, "REDSTONE_LAMP_OFF", "REDSTONE_LAMP_ON"), + REDSTONE_ORE(0, "GLOWING_REDSTONE_ORE"), + REDSTONE_TORCH(0, "REDSTONE_TORCH_ON", "REDSTONE_TORCH_OFF"), + REDSTONE_WALL_TORCH(1, "REDSTONE_TORCH_ON", "REDSTONE_TORCH_OFF"), + REDSTONE_WIRE(0, ""), + RED_BANNER(1, "BANNER", "STANDING_BANNER"), + RED_BED(14, "BED", "BED_BLOCK"), + RED_CARPET(14, "CARPET"), + RED_CONCRETE(14, "CONCRETE"), + RED_CONCRETE_POWDER(14, "CONCRETE_POWDER"), + RED_DYE(1, "ROSE_RED"), + RED_GLAZED_TERRACOTTA(14, "1.12", "HARD_CLAY", "STAINED_CLAY", "RED_TERRACOTTA"), + RED_MUSHROOM(0, ""), + RED_MUSHROOM_BLOCK(0, "RED_MUSHROOM", "HUGE_MUSHROOM_2"), + RED_NETHER_BRICKS(0, "RED_NETHER_BRICK"), + RED_NETHER_BRICK_SLAB(4, "STEP"), + RED_NETHER_BRICK_STAIRS(0, ""), + RED_NETHER_BRICK_WALL(0, ""), + RED_SAND(1, "SAND"), + RED_SANDSTONE(0, ""), + RED_SANDSTONE_SLAB(0, "STONE_SLAB2", "DOUBLE_STONE_SLAB2"), + RED_SANDSTONE_STAIRS(0, ""), + RED_SANDSTONE_WALL(0, ""), + RED_SHULKER_BOX(0, ""), + RED_STAINED_GLASS(14, "STAINED_GLASS"), + RED_STAINED_GLASS_PANE(14, "THIN_GLASS", "STAINED_GLASS_PANE"), + RED_TERRACOTTA(14, "HARD_CLAY", "STAINED_CLAY"), + RED_TULIP(4, "RED_ROSE"), + RED_WALL_BANNER(1, "WALL_BANNER"), + RED_WOOL(14, "WOOL"), + REPEATER(0, "DIODE", "DIODE_BLOCK_ON", "DIODE_BLOCK_OFF"), + REPEATING_COMMAND_BLOCK(0, "COMMAND", "COMMAND_REPEATING"), + ROSE_BUSH(4, "DOUBLE_PLANT"), + ROTTEN_FLESH(0, ""), + SADDLE(0, ""), + SALMON(1, "RAW_FISH"), + SALMON_BUCKET(0, "1.13", "BUCKET", "WATER_BUCKET"), + SALMON_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), + SAND(0, ""), + SANDSTONE(0, ""), + SANDSTONE_SLAB(1, "STEP", "STONE_SLAB", "DOUBLE_STEP"), + SANDSTONE_STAIRS(0, ""), + SANDSTONE_WALL(0, ""), + SCAFFOLDING(0, "1.14", "SLIME_BLOCK"), + SCUTE(0, "1.13"), + SEAGRASS(0, "1.13"), + SEA_LANTERN(0, ""), + SEA_PICKLE(0, "1.13"), + SHEARS(0, ""), + SHEEP_SPAWN_EGG(91, "MONSTER_EGG"), + SHIELD(0, ""), + SHULKER_BOX(0, "PURPLE_SHULKER_BOX"), + SHULKER_SHELL(0, ""), + SHULKER_SPAWN_EGG(69, "MONSTER_EGG"), + SILVERFISH_SPAWN_EGG(60, "MONSTER_EGG"), + SKELETON_HORSE_SPAWN_EGG(28, "MONSTER_EGG"), + SKELETON_SKULL(0, "SKULL", "SKULL_ITEM"), + SKELETON_SPAWN_EGG(51, "MONSTER_EGG"), + SKELETON_WALL_SKULL(0, "SKULL", "SKULL_ITEM"), + SKULL_BANNER_PATTERN(0, ""), + SLIME_BALL(0, ""), + SLIME_BLOCK(0, ""), + SLIME_SPAWN_EGG(55, "MONSTER_EGG"), + SMITHING_TABLE(0, ""), + SMOKER(0, "1.14", "FURNACE"), + SMOOTH_QUARTZ(0, "1.13"), + SMOOTH_QUARTZ_SLAB(7, "STEP"), + SMOOTH_QUARTZ_STAIRS(0, ""), + SMOOTH_RED_SANDSTONE(2, "RED_SANDSTONE"), + SMOOTH_RED_SANDSTONE_SLAB(0, "STONE_SLAB2"), + SMOOTH_RED_SANDSTONE_STAIRS(0, ""), + SMOOTH_SANDSTONE(2, "SANDSTONE"), + SMOOTH_SANDSTONE_SLAB(0, "STEP"), + SMOOTH_SANDSTONE_STAIRS(0, ""), + SMOOTH_STONE(0, "STEP"), + SMOOTH_STONE_SLAB(0, "STEP"), + SNOW(0, ""), + SNOWBALL(0, "SNOW_BALL"), + SNOW_BLOCK(0, ""), + SOUL_SAND(0, ""), + SPAWNER(0, "MOB_SPAWNER"), + SPECTRAL_ARROW(0, ""), + SPIDER_EYE(0, ""), + SPIDER_SPAWN_EGG(52, "MONSTER_EGG"), + SPLASH_POTION(0, ""), + SPONGE(0, ""), + SPRUCE_BOAT(0, "BOAT_SPRUCE"), + SPRUCE_BUTTON(0, "WOOD_BUTTON"), + SPRUCE_DOOR(0, "SPRUCE_DOOR_ITEM"), + SPRUCE_FENCE(0, ""), + SPRUCE_FENCE_GATE(0, ""), + SPRUCE_LEAVES(1, "LEAVES"), + SPRUCE_LOG(1, "LOG"), + SPRUCE_PLANKS(1, "WOOD"), + SPRUCE_PRESSURE_PLATE(0, "WOOD_PLATE"), + SPRUCE_SAPLING(1, "SAPLING"), + SPRUCE_SIGN(0, "SIGN"), + SPRUCE_SLAB(1, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), + SPRUCE_STAIRS(0, "SPRUCE_WOOD_STAIRS"), + SPRUCE_TRAPDOOR(0, "TRAP_DOOR"), + SPRUCE_WALL_SIGN(0, "SIGN_POST", "WALL_SIGN"), + SPRUCE_WOOD(1, "LOG"), + SQUID_SPAWN_EGG(94, "MONSTER_EGG"), + STICK(0, ""), + STICKY_PISTON(0, "PISTON_BASE", "PISTON_STICKY_BASE"), + STONE(0, ""), + STONECUTTER(0, "1.14"), + STONE_AXE(0, ""), + STONE_BRICKS(0, "SMOOTH_BRICK"), + STONE_BRICK_SLAB(4, "STEP", "STONE_SLAB", "DOUBLE_STEP"), + STONE_BRICK_STAIRS(0, "SMOOTH_STAIRS"), + STONE_BRICK_WALL(0, ""), + STONE_BUTTON(0, ""), + STONE_HOE(0, ""), + STONE_PICKAXE(0, ""), + STONE_PRESSURE_PLATE(0, "STONE_PLATE"), + STONE_SHOVEL(0, "STONE_SPADE"), + STONE_SLAB(0, "STEP", "DOUBLE_STEP"), + STONE_STAIRS(0, ""), + STONE_SWORD(0, ""), + STRAY_SPAWN_EGG(6, "MONSTER_EGG"), + STRING(0, ""), + STRIPPED_ACACIA_LOG(0, "LOG_2"), + STRIPPED_ACACIA_WOOD(0, "LOG_2"), + STRIPPED_BIRCH_LOG(2, "LOG"), + STRIPPED_BIRCH_WOOD(2, "LOG"), + STRIPPED_DARK_OAK_LOG(0, "LOG"), + STRIPPED_DARK_OAK_WOOD(0, "LOG"), + STRIPPED_JUNGLE_LOG(3, "LOG"), + STRIPPED_JUNGLE_WOOD(3, "LOG"), + STRIPPED_OAK_LOG(0, "LOG"), + STRIPPED_OAK_WOOD(0, "LOG"), + STRIPPED_SPRUCE_LOG(1, "LOG"), + STRIPPED_SPRUCE_WOOD(1, "LOG"), + STRUCTURE_BLOCK(0, ""), + STRUCTURE_VOID(0, "1.10", "BARRIER/1.9"), // Originally developers used barrier blocks for its purpose. + SUGAR(0, ""), + SUGAR_CANE(0, "SUGAR_CANE_BLOCK"), + SUNFLOWER(0, "DOUBLE_PLANT"), + SUSPICIOUS_STEW(0, "1.14", "MUSHROOM_STEW"), + SWEET_BERRIES(0, "1.14"), + SWEET_BERRY_BUSH(0, "1.14", "GRASS"), + TALL_GRASS(2, "DOUBLE_PLANT"), + TALL_SEAGRASS(0, "1.13"), + TERRACOTTA(0, "HARD_CLAY"), + TIPPED_ARROW(0, ""), + TNT(0, ""), + TNT_MINECART(0, "EXPLOSIVE_MINECART"), + TORCH(0, ""), + TOTEM_OF_UNDYING(0, "TOTEM"), + TRADER_LLAMA_SPAWN_EGG(103, "1.14", "MONSTER_EGG"), + TRAPPED_CHEST(0, ""), + TRIDENT(0, "1.13"), + TRIPWIRE(0, ""), + TRIPWIRE_HOOK(0, ""), + TROPICAL_FISH(2, "RAW_FISH"), + TROPICAL_FISH_BUCKET(0, "1.13", "BUCKET", "WATER_BUCKET"), + TROPICAL_FISH_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), + TUBE_CORAL(0, "1.13"), + TUBE_CORAL_BLOCK(0, "1.13"), + TUBE_CORAL_FAN(0, "1.13"), + TUBE_CORAL_WALL_FAN(0, ""), + TURTLE_EGG(0, "1.13", "EGG"), + TURTLE_HELMET(0, "1.13"), + TURTLE_SPAWN_EGG(0, "1.13", "MONSTER_EGG"), + VEX_SPAWN_EGG(35, "MONSTER_EGG"), + VILLAGER_SPAWN_EGG(120, "MONSTER_EGG"), + VINDICATOR_SPAWN_EGG(36, "MONSTER_EGG"), + VINE(0, ""), + VOID_AIR(0, "AIR"), + WALL_TORCH(0, "TORCH"), + WANDERING_TRADER_SPAWN_EGG(0, "1.14", "VILLAGER_SPAWN_EGG"), + WATER(0, "STATIONARY_WATER"), + WATER_BUCKET(0, ""), + WET_SPONGE(1, "SPONGE"), + WHEAT(0, "CROPS"), + WHEAT_SEEDS(0, "SEEDS"), + WHITE_BANNER(15, "BANNER", "STANDING_BANNER"), + WHITE_BED(0, "BED", "BED_BLOCK"), + WHITE_CARPET(0, "CARPET"), + WHITE_CONCRETE(0, "CONCRETE"), + WHITE_CONCRETE_POWDER(0, "CONCRETE_POWDER"), + WHITE_DYE(15, "1.14", "INK_SACK", "BONE_MEAL"), + WHITE_GLAZED_TERRACOTTA(0, "1.12", "HARD_CLAY", "STAINED_CLAY", "WHITE_TERRACOTTA"), + WHITE_SHULKER_BOX(0, ""), + WHITE_STAINED_GLASS(0, "STAINED_GLASS"), + WHITE_STAINED_GLASS_PANE(0, "THIN_GLASS", "STAINED_GLASS_PANE"), + WHITE_TERRACOTTA(0, "HARD_CLAY", "TERRACOTTA"), + WHITE_TULIP(6, "RED_ROSE"), + WHITE_WALL_BANNER(15, "WALL_BANNER"), + WHITE_WOOL(0, "WOOL"), + WITCH_SPAWN_EGG(66, "MONSTER_EGG"), + WITHER_ROSE(0, "1.14", "BLACK_DYE"), + WITHER_SKELETON_SKULL(1, "SKULL", "SKULL_ITEM"), + WITHER_SKELETON_SPAWN_EGG(5, "MONSTER_EGG"), + WITHER_SKELETON_WALL_SKULL(1, "SKULL", "SKULL_ITEM"), + WOLF_SPAWN_EGG(95, "MONSTER_EGG"), + WOODEN_AXE(0, "WOOD_AXE"), + WOODEN_HOE(0, "WOOD_HOE"), + WOODEN_PICKAXE(0, "WOOD_PICKAXE"), + WOODEN_SHOVEL(0, "WOOD_SPADE"), + WOODEN_SWORD(0, "WOOD_SWORD"), + WRITABLE_BOOK(0, "BOOK_AND_QUILL"), + WRITTEN_BOOK(0, ""), + YELLOW_BANNER(11, "BANNER", "STANDING_BANNER"), + YELLOW_BED(4, "BED", "BED_BLOCK"), + YELLOW_CARPET(4, "CARPET"), + YELLOW_CONCRETE(4, "CONCRETE"), + YELLOW_CONCRETE_POWDER(4, "CONCRETE_POWDER"), + YELLOW_DYE(11, "INK_SACK", "DANDELION_YELLOW"), + YELLOW_GLAZED_TERRACOTTA(4, "1.12", "HARD_CLAY", "STAINED_CLAY", "YELLOW_TERRACOTTA"), + YELLOW_SHULKER_BOX(0, ""), + YELLOW_STAINED_GLASS(4, "STAINED_GLASS"), + YELLOW_STAINED_GLASS_PANE(4, "THIN_GLASS", "STAINED_GLASS_PANE"), + YELLOW_TERRACOTTA(4, "HARD_CLAY", "STAINED_CLAY"), + YELLOW_WALL_BANNER(11, "WALL_BANNER"), + YELLOW_WOOL(4, "WOOL"), + ZOMBIE_HEAD(2, "SKULL", "SKULL_ITEM"), + ZOMBIE_HORSE_SPAWN_EGG(29, "MONSTER_EGG"), + ZOMBIE_PIGMAN_SPAWN_EGG(57, "MONSTER_EGG"), + ZOMBIE_SPAWN_EGG(54, "MONSTER_EGG"), + ZOMBIE_VILLAGER_SPAWN_EGG(27, "MONSTER_EGG"), + ZOMBIE_WALL_HEAD(2, "SKULL", "SKULL_ITEM"); - /** - * A list of material names that can be damaged. - * Some names are not complete as this list needs to be - * checked with {@link String#contains}. - */ - public static final String[] DAMAGEABLE = { - "HELMET", "CHESTPLATE", "LEGGINGS", "BOOTS", - "SWORD", "AXE", "PICKAXE", "SHOVEL", "HOE", - "ELYTRA", "TRIDENT", "HORSE_ARMOR", "BARDING", - "SHEARS", "FLINT_AND_STEEL", "BOW", "FISHING_ROD", - "CARROT_ON_A_STICK", "CARROT_STICK" - }; - /** - * A list of duplicated items in 1.13 and 1.12 with different purpose. - * Values are the new material names. - * Duplicates are only checked by keys not values. - * Checked with {@link String#equals} - */ - public static final HashMap DUPLICATED = new HashMap() {{ - put(XMaterial.MELON, XMaterial.MELON_SLICE); - put(XMaterial.CARROT, XMaterial.CARROTS); - put(XMaterial.POTATO, XMaterial.POTATOES); - put(XMaterial.BEETROOT, XMaterial.BEETROOTS); - put(XMaterial.BROWN_MUSHROOM, XMaterial.BROWN_MUSHROOM_BLOCK); - put(XMaterial.BRICK, XMaterial.BRICKS); - put(XMaterial.RED_MUSHROOM, XMaterial.RED_MUSHROOM_BLOCK); - put(XMaterial.MAP, XMaterial.FILLED_MAP); - put(XMaterial.NETHER_BRICK, XMaterial.NETHER_BRICKS); - }}; - public static final XMaterial[] VALUES = XMaterial.values(); - private static final HashMap CACHED_SEARCH = new HashMap<>(); - private static MinecraftVersion version; - private static Boolean isNewVersion; - private final byte data; - private final String[] legacy; + /** + * A list of material names that can be damaged. + * Some names are not complete as this list needs to be + * checked with {@link String#contains}. + */ + public static final String[] DAMAGEABLE = { + "HELMET", "CHESTPLATE", "LEGGINGS", "BOOTS", + "SWORD", "AXE", "PICKAXE", "SHOVEL", "HOE", + "ELYTRA", "TRIDENT", "HORSE_ARMOR", "BARDING", + "SHEARS", "FLINT_AND_STEEL", "BOW", "FISHING_ROD", + "CARROT_ON_A_STICK", "CARROT_STICK" + }; + /** + * A list of duplicated items in 1.13 and 1.12 with different purpose. + * Values are the new material names. + * Duplicates are only checked by keys not values. + * Checked with {@link String#equals} + */ + public static final HashMap DUPLICATED = new HashMap() {{ + put(XMaterial.MELON, XMaterial.MELON_SLICE); + put(XMaterial.CARROT, XMaterial.CARROTS); + put(XMaterial.POTATO, XMaterial.POTATOES); + put(XMaterial.BEETROOT, XMaterial.BEETROOTS); + put(XMaterial.BROWN_MUSHROOM, XMaterial.BROWN_MUSHROOM_BLOCK); + put(XMaterial.BRICK, XMaterial.BRICKS); + put(XMaterial.RED_MUSHROOM, XMaterial.RED_MUSHROOM_BLOCK); + put(XMaterial.MAP, XMaterial.FILLED_MAP); + put(XMaterial.NETHER_BRICK, XMaterial.NETHER_BRICKS); + }}; + public static final XMaterial[] VALUES = XMaterial.values(); + private static final HashMap CACHED_SEARCH = new HashMap<>(); + private static MinecraftVersion version; + private static Boolean isNewVersion; + private final byte data; + private final String[] legacy; - XMaterial(int data, String... legacy) { - this.data = (byte) data; - this.legacy = legacy; - } + XMaterial(int data, String... legacy) { + this.data = (byte) data; + this.legacy = legacy; + } - /** - * Checks if the version is 1.13 (Aquatic Update) or higher. - * - * @return true if 1.13 or higher. - */ - public static boolean isNewVersion() { - if (isNewVersion != null) return isNewVersion; - return isNewVersion = isVersionOrHigher(MinecraftVersion.VERSION_1_13); - } + /** + * Checks if the version is 1.13 (Aquatic Update) or higher. + * + * @return true if 1.13 or higher. + */ + public static boolean isNewVersion() { + if (isNewVersion != null) return isNewVersion; + return isNewVersion = isVersionOrHigher(MinecraftVersion.VERSION_1_13); + } - public static boolean isOneEight() { - return getVersion() == MinecraftVersion.VERSION_1_8; - } + public static boolean isOneEight() { + return getVersion() == MinecraftVersion.VERSION_1_8; + } - /** - * Uses newly added materials to minecraft to detect the server version. - * - * @return the current server version. - */ - public static MinecraftVersion getVersion() { - if (version != null) return version; - return version = valueOfVersion(Bukkit.getVersion()); - } + /** + * Uses newly added materials to minecraft to detect the server version. + * + * @return the current server version. + */ + public static MinecraftVersion getVersion() { + if (version != null) return version; + return version = valueOfVersion(Bukkit.getVersion()); + } - /** - * When using newer versions of Minecraft {@link #isNewVersion()} this helps - * to find the old material name with its data using a cached search for optimization. - * - * @see #matchXMaterial(String, byte) - */ - private static XMaterial requestOldXMaterial(String name, byte data) { - XMaterial cached = CACHED_SEARCH.get(name + "," + data); + /** + * When using newer versions of Minecraft {@link #isNewVersion()} this helps + * to find the old material name with its data using a cached search for optimization. + * + * @see #matchXMaterial(String, byte) + */ + private static XMaterial requestOldXMaterial(String name, byte data) { + XMaterial cached = CACHED_SEARCH.get(name + "," + data); - if (cached != null) return cached; - Optional search = data == -1 ? Arrays.stream(XMaterial.VALUES).filter(mat -> mat.matchAnyLegacy(name)).findFirst() - : Arrays.stream(XMaterial.VALUES).filter(mat -> mat.matchAnyLegacy(name) && mat.data == data).findFirst(); + if (cached != null) return cached; + Optional search = data == -1 ? Arrays.stream(XMaterial.VALUES).filter(mat -> mat.matchAnyLegacy(name)).findFirst() + : Arrays.stream(XMaterial.VALUES).filter(mat -> mat.matchAnyLegacy(name) && mat.data == data).findFirst(); - if (search.isPresent()) { - XMaterial found = search.get(); - CACHED_SEARCH.put(found.legacy[0] + "," + found.getData(), found); - return found; - } - return null; - } + if (search.isPresent()) { + XMaterial found = search.get(); + CACHED_SEARCH.put(found.legacy[0] + "," + found.getData(), found); + return found; + } + return null; + } - /** - * Checks if XMaterial enum contains a material with this name. - * - * @param name name of the material - * @return true if XMaterial enum has this material. - */ - public static boolean contains(String name) { - String formatted = format(name); - return Arrays.stream(XMaterial.VALUES).anyMatch(mat -> mat.name().equals(formatted)); - } + /** + * Checks if XMaterial enum contains a material with this name. + * + * @param name name of the material + * @return true if XMaterial enum has this material. + */ + public static boolean contains(String name) { + String formatted = format(name); + return Arrays.stream(XMaterial.VALUES).anyMatch(mat -> mat.name().equals(formatted)); + } - /** - * Checks if the given material matches any of the legacy names. - * - * @param name the material name. - * @return true if it's a legacy name. - */ - public static boolean containsLegacy(String name) { - String formatted = format(name); - return Arrays.stream(Arrays.stream(XMaterial.VALUES).map(m -> m.legacy).toArray(String[]::new)).anyMatch(mat - -> parseLegacyVersionMaterialName(mat).equals(formatted)); - } + /** + * Checks if the given material matches any of the legacy names. + * + * @param name the material name. + * @return true if it's a legacy name. + */ + public static boolean containsLegacy(String name) { + String formatted = format(name); + return Arrays.stream(Arrays.stream(XMaterial.VALUES).map(m -> m.legacy).toArray(String[]::new)).anyMatch(mat + -> parseLegacyVersionMaterialName(mat).equals(formatted)); + } - /** - * @see #matchXMaterial(String, byte) - */ - public static XMaterial matchXMaterial(Material material) { - return matchXMaterial(material.name()); - } + /** + * @see #matchXMaterial(String, byte) + */ + public static XMaterial matchXMaterial(Material material) { + return matchXMaterial(material.name()); + } - /** - * @see #matchXMaterial(String, byte) - */ - public static XMaterial matchXMaterial(String name) { - // -1 Determines whether the item's data is unknown and only the name is given. - // Checking if the item is damageable won't do anything as the data is not going to be checked in requestOldMaterial anyway. - return matchXMaterial(name, (byte) -1); - } + /** + * @see #matchXMaterial(String, byte) + */ + public static XMaterial matchXMaterial(String name) { + // -1 Determines whether the item's data is unknown and only the name is given. + // Checking if the item is damageable won't do anything as the data is not going to be checked in requestOldMaterial anyway. + return matchXMaterial(name, (byte) -1); + } - /** - * Parses the material name and data argument as a {@link Material}. - * - * @param name name of the material - * @param data data of the material - */ - public static Material parseMaterial(String name, byte data) { - return matchXMaterial(name, data).parseMaterial(); - } + /** + * Parses the material name and data argument as a {@link Material}. + * + * @param name name of the material + * @param data data of the material + */ + public static Material parseMaterial(String name, byte data) { + return matchXMaterial(name, data).parseMaterial(); + } - /** - * @param item the ItemStack to match its material and data. - * @see #matchXMaterial(String, byte) - */ - @SuppressWarnings("deprecation") - public static XMaterial matchXMaterial(ItemStack item) { - return isDamageable(item.getType().name()) ? matchXMaterial(item.getType().name(), (byte) 0) : - matchXMaterial(item.getType().name(), (byte) item.getDurability()); - } + /** + * @param item the ItemStack to match its material and data. + * @see #matchXMaterial(String, byte) + */ + @SuppressWarnings("deprecation") + public static XMaterial matchXMaterial(ItemStack item) { + return isDamageable(item.getType().name()) ? matchXMaterial(item.getType().name(), (byte) 0) : + matchXMaterial(item.getType().name(), (byte) item.getDurability()); + } - /** - * Matches the argument string and its data with a XMaterial. - * - * @param name the name of the material - * @param data the data byte of the material - * @return a XMaterial from the enum (with the same legacy name and data if in older versions.) - */ - public static XMaterial matchXMaterial(String name, byte data) { - Validate.notEmpty(name, "Material name cannot be null or empty"); - name = format(name); + /** + * Matches the argument string and its data with a XMaterial. + * + * @param name the name of the material + * @param data the data byte of the material + * @return a XMaterial from the enum (with the same legacy name and data if in older versions.) + */ + public static XMaterial matchXMaterial(String name, byte data) { + Validate.notEmpty(name, "Material name cannot be null or empty"); + name = format(name); - if ((contains(name) && data <= 0) && (isNewVersion() || !isDuplicated(name))) - return valueOf(name); + if ((contains(name) && data <= 0) && (isNewVersion() || !isDuplicated(name))) + return valueOf(name); - // TODO Temporary but works - Please find a more reasonable fix for duplicated materials. - if (isDuplicated(name) && !isNewVersion()) - return requestDuplicatedXMaterial(name, data); + // TODO Temporary but works - Please find a more reasonable fix for duplicated materials. + if (isDuplicated(name) && !isNewVersion()) + return requestDuplicatedXMaterial(name, data); - return requestOldXMaterial(name, data); - } + return requestOldXMaterial(name, data); + } - /** - * Gets the XMaterial based on the Material's ID and data. - * You should avoid using this for performance reasons. - * - * @param id the ID (Magic value) of the material. - * @param data the data of the material. - * @return some XMaterial, or null. - */ - public static XMaterial matchXMaterial(int id, byte data) { - // Looping through Material.values() will take longer. - return Arrays.stream(XMaterial.VALUES).filter(mat -> mat.getId() == id && mat.data == data).findFirst().orElse(null); - } + /** + * Gets the XMaterial based on the Material's ID and data. + * You should avoid using this for performance reasons. + * + * @param id the ID (Magic value) of the material. + * @param data the data of the material. + * @return some XMaterial, or null. + */ + public static XMaterial matchXMaterial(int id, byte data) { + // Looping through Material.values() will take longer. + return Arrays.stream(XMaterial.VALUES).filter(mat -> mat.getId() == id && mat.data == data).findFirst().orElse(null); + } - /** - * This method is temporary. Do not use this. - * Manually parses the duplicated materials to find the exact material based on the server version. - * - * @param name the name of the material. - * @return the duplicated XMaterial based on the version. - */ - private static XMaterial requestDuplicatedXMaterial(String name, byte data) { - XMaterial mat = requestOldXMaterial(name, data); - return mat == null ? null : mat.name().endsWith("S") ? valueOf(name) : mat; - } + /** + * This method is temporary. Do not use this. + * Manually parses the duplicated materials to find the exact material based on the server version. + * + * @param name the name of the material. + * @return the duplicated XMaterial based on the version. + */ + private static XMaterial requestDuplicatedXMaterial(String name, byte data) { + XMaterial mat = requestOldXMaterial(name, data); + return mat == null ? null : mat.name().endsWith("S") ? valueOf(name) : mat; + } - /** - * Always returns the value. - * - * @param name the name of the material. - * @return the new XMaterial of this duplicated material. - * @see #getXMaterialIfDuplicated(String) - */ - public static XMaterial getNewXMaterialIfDuplicated(String name) { - return DUPLICATED.entrySet().stream() - .filter(m -> m.getKey().name().equals(format(name))) - .findFirst() - .map(Map.Entry::getValue) - .orElse(null); - } + /** + * Always returns the value. + * + * @param name the name of the material. + * @return the new XMaterial of this duplicated material. + * @see #getXMaterialIfDuplicated(String) + */ + public static XMaterial getNewXMaterialIfDuplicated(String name) { + return DUPLICATED.entrySet().stream() + .filter(m -> m.getKey().name().equals(format(name))) + .findFirst() + .map(Map.Entry::getValue) + .orElse(null); + } - /** - * Checks if the item is duplicated for a different purpose in new versions from {@link #DUPLICATED}. - * - * @param name the name of the material. - * @return the other XMaterial (key or value) of the XMaterial (key or value) which the name was equals to. - * @see #matchXMaterial(String, byte) - */ - public static XMaterial getXMaterialIfDuplicated(String name) { - String formatted = format(name); - Optional> mat = DUPLICATED.entrySet().stream().filter(m - -> m.getKey().name().equals(formatted) || m.getValue().name().equals(formatted)).findFirst(); + /** + * Checks if the item is duplicated for a different purpose in new versions from {@link #DUPLICATED}. + * + * @param name the name of the material. + * @return the other XMaterial (key or value) of the XMaterial (key or value) which the name was equals to. + * @see #matchXMaterial(String, byte) + */ + public static XMaterial getXMaterialIfDuplicated(String name) { + String formatted = format(name); + Optional> mat = DUPLICATED.entrySet().stream().filter(m + -> m.getKey().name().equals(formatted) || m.getValue().name().equals(formatted)).findFirst(); - if (mat.isPresent()) { - Map.Entry found = mat.get(); - return formatted.equals(found.getKey().name()) ? found.getValue() : found.getKey(); - } - return null; - } + if (mat.isPresent()) { + Map.Entry found = mat.get(); + return formatted.equals(found.getKey().name()) ? found.getValue() : found.getKey(); + } + return null; + } - /** - * Attempts to build the string like an enum name. - * - * @param name the material name to modify. - * @return a Material enum name. - */ - private static String format(String name) { - return name.toUpperCase().replace("MINECRAFT:", "").replace('-', '_').replaceAll("\\s+", "_").replaceAll("\\W", ""); - } + /** + * Attempts to build the string like an enum name. + * + * @param name the material name to modify. + * @return a Material enum name. + */ + private static String format(String name) { + return name.toUpperCase().replace("MINECRAFT:", "").replace('-', '_').replaceAll("\\s+", "_").replaceAll("\\W", ""); + } - /** - * Parses the material name if the legacy name has a version attached to it. - * - * @param name the material name to parse. - * @return the material name with the version removed. - */ - private static String parseLegacyVersionMaterialName(String name) { - if (!name.contains("/")) return name; - return name.substring(0, name.indexOf('/')); - } + /** + * Parses the material name if the legacy name has a version attached to it. + * + * @param name the material name to parse. + * @return the material name with the version removed. + */ + private static String parseLegacyVersionMaterialName(String name) { + if (!name.contains("/")) return name; + return name.substring(0, name.indexOf('/')); + } - /** - * Checks if the version argument is the same or higher than the current server version. - * - * @param version the version to be checked. - * @return true of the version is equal or higher than the current version. - */ - public static boolean isVersionOrHigher(MinecraftVersion version) { - MinecraftVersion current = getVersion(); + /** + * Checks if the version argument is the same or higher than the current server version. + * + * @param version the version to be checked. + * @return true of the version is equal or higher than the current version. + */ + public static boolean isVersionOrHigher(MinecraftVersion version) { + MinecraftVersion current = getVersion(); - if (version == current) return true; - if (version == MinecraftVersion.UNKNOWN) return false; - if (current == MinecraftVersion.UNKNOWN) return true; + if (version == current) return true; + if (version == MinecraftVersion.UNKNOWN) return false; + if (current == MinecraftVersion.UNKNOWN) return true; - int ver = Integer.parseInt(version.name().replace("VERSION_", "").replace("_", "")); - int currentVer = Integer.parseInt(current.name().replace("VERSION_", "").replace("_", "")); + int ver = Integer.parseInt(version.name().replace("VERSION_", "").replace("_", "")); + int currentVer = Integer.parseInt(current.name().replace("VERSION_", "").replace("_", "")); - return currentVer >= ver; - } + return currentVer >= ver; + } - /** - * Converts the material's name to a string with the first letter uppercase. - * - * @return a converted string. - */ - public static String toWord(Material material) { - return material.name().charAt(0) + material.name().substring(1).toLowerCase(); - } + /** + * Converts the material's name to a string with the first letter uppercase. + * + * @return a converted string. + */ + public static String toWord(Material material) { + return material.name().charAt(0) + material.name().substring(1).toLowerCase(); + } - /** - * Compares two major versions. The current server version and the given version. - * - * @param version the version to check. - * @return true if is the same as the current version or higher. - */ - public static boolean isVersionOrHigher(String version) { - int currentVer = Integer.parseInt(getExactMajorVersion(Bukkit.getVersion()).replace(".", "")); - int versionNumber = Integer.parseInt(version.replace(".", "")); + /** + * Compares two major versions. The current server version and the given version. + * + * @param version the version to check. + * @return true if is the same as the current version or higher. + */ + public static boolean isVersionOrHigher(String version) { + int currentVer = Integer.parseInt(getExactMajorVersion(Bukkit.getVersion()).replace(".", "")); + int versionNumber = Integer.parseInt(version.replace(".", "")); - return currentVer >= versionNumber; - } + return currentVer >= versionNumber; + } - /** - * Gets the exact major version (..., 1.9, 1.10, ..., 1.14) - * - * @param version Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as "1.14" - * @return the exact major version. - */ - public static String getExactMajorVersion(String version) { - // getBukkitVersion() - if (version.contains("SNAPSHOT") || version.contains("-R")) - version = version.substring(0, version.indexOf("-")); - // getVersion() - if (version.contains("git")) version = version.substring(version.indexOf("MC:") + 4).replace(")", ""); - if (version.split(Pattern.quote(".")).length > 2) version = version.substring(0, version.lastIndexOf(".")); - return version; - } + /** + * Gets the exact major version (..., 1.9, 1.10, ..., 1.14) + * + * @param version Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as "1.14" + * @return the exact major version. + */ + public static String getExactMajorVersion(String version) { + // getBukkitVersion() + if (version.contains("SNAPSHOT") || version.contains("-R")) + version = version.substring(0, version.indexOf("-")); + // getVersion() + if (version.contains("git")) version = version.substring(version.indexOf("MC:") + 4).replace(")", ""); + if (version.split(Pattern.quote(".")).length > 2) version = version.substring(0, version.lastIndexOf(".")); + return version; + } - /** - * Parses the string arugment to a version. - * Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as "1.14" - * - * @param version the server version. - * @return the Minecraft version represented by the string. - */ - private static MinecraftVersion valueOfVersion(String version) { - version = getExactMajorVersion(version); - if (version.equals("1.10") || version.equals("1.11") || version.equals("1.12")) - return MinecraftVersion.VERSION_1_9; - version = version.replace(".", "_"); - if (!version.startsWith("VERSION_")) version = "VERSION_" + version; - String check = version; - return Arrays.stream(MinecraftVersion.VALUES).anyMatch(v -> v.name().equals(check)) ? MinecraftVersion.valueOf(version) : MinecraftVersion.UNKNOWN; - } + /** + * Parses the string arugment to a version. + * Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as "1.14" + * + * @param version the server version. + * @return the Minecraft version represented by the string. + */ + private static MinecraftVersion valueOfVersion(String version) { + version = getExactMajorVersion(version); + if (version.equals("1.10") || version.equals("1.11") || version.equals("1.12")) + return MinecraftVersion.VERSION_1_9; + version = version.replace(".", "_"); + if (!version.startsWith("VERSION_")) version = "VERSION_" + version; + String check = version; + return Arrays.stream(MinecraftVersion.VALUES).anyMatch(v -> v.name().equals(check)) ? MinecraftVersion.valueOf(version) : MinecraftVersion.UNKNOWN; + } - /** - * Checks if the material can be damaged from {@link #DAMAGEABLE}. - * - * @param name the name of the material. - * @return true of the material can be damaged. - */ - public static boolean isDamageable(String name) { - return Arrays.stream(DAMAGEABLE).anyMatch(name::contains); - } + /** + * Checks if the material can be damaged from {@link #DAMAGEABLE}. + * + * @param name the name of the material. + * @return true of the material can be damaged. + */ + public static boolean isDamageable(String name) { + return Arrays.stream(DAMAGEABLE).anyMatch(name::contains); + } - public static boolean isDuplicated(String name) { - String formatted = format(name); - return DUPLICATED.entrySet().stream().anyMatch(x -> x.getKey().name().equals(formatted)); - } + public static boolean isDuplicated(String name) { + String formatted = format(name); + return DUPLICATED.entrySet().stream().anyMatch(x -> x.getKey().name().equals(formatted)); + } - /** - * Gets the ID (Magic value) of the material. - * If an {@link IllegalArgumentException} was thrown from this method, - * you should definitely report it. - * - * @return the ID of the material. -1 if it's a new block. - */ - @SuppressWarnings("deprecation") - public int getId() { - return this.isNew() ? -1 : this.parseMaterial().getId(); - } + /** + * Gets the ID (Magic value) of the material. + * If an {@link IllegalArgumentException} was thrown from this method, + * you should definitely report it. + * + * @return the ID of the material. -1 if it's a new block. + */ + @SuppressWarnings("deprecation") + public int getId() { + return this.isNew() ? -1 : this.parseMaterial().getId(); + } - public boolean isDuplicated() { - return DUPLICATED.containsKey(this); - } + public boolean isDuplicated() { + return DUPLICATED.containsKey(this); + } - /** - * Checks if the given string matches any of this material's legacy material names. - * - * @param name the name to check - * @return true if it's one of the legacy names. - */ - public boolean matchAnyLegacy(String name) { - String formatted = format(name); - return Arrays.asList(this.legacy).contains(formatted); - } + /** + * Checks if the given string matches any of this material's legacy material names. + * + * @param name the name to check + * @return true if it's one of the legacy names. + */ + public boolean matchAnyLegacy(String name) { + String formatted = format(name); + return Arrays.asList(this.legacy).contains(formatted); + } - /** - * Converts the material's name to a string with the first letter uppercase. - * - * @return a converted string. - */ - public String toWord() { - return this.name().charAt(0) + this.name().substring(1).toLowerCase(); - } + /** + * Converts the material's name to a string with the first letter uppercase. + * + * @return a converted string. + */ + public String toWord() { + return this.name().charAt(0) + this.name().substring(1).toLowerCase(); + } - /** - * Checks if the item is duplicated for a different purpose in new versions from {@link #DUPLICATED}. - * - * @return true if the item's name is duplicated. - * @see #matchXMaterial(String, byte) - */ - public XMaterial getXMaterialIfDuplicated() { - Optional> mat = DUPLICATED.entrySet().stream().filter(m -> m.getKey() == this).findFirst(); - return mat.map(Map.Entry::getValue).orElse(null); - } + /** + * Checks if the item is duplicated for a different purpose in new versions from {@link #DUPLICATED}. + * + * @return true if the item's name is duplicated. + * @see #matchXMaterial(String, byte) + */ + public XMaterial getXMaterialIfDuplicated() { + Optional> mat = DUPLICATED.entrySet().stream().filter(m -> m.getKey() == this).findFirst(); + return mat.map(Map.Entry::getValue).orElse(null); + } - /** - * @return true if the item can be damaged. - * @see #isDamageable(String) - */ - public boolean isDamageable() { - return isDamageable(this.name()); - } + /** + * @return true if the item can be damaged. + * @see #isDamageable(String) + */ + public boolean isDamageable() { + return isDamageable(this.name()); + } - /** - * Get the {@link ItemStack} data of this material in older versions. - * Which can be accessed with {@link ItemStack#getData()} then MaterialData#getData() - * or {@link ItemStack#getDurability()} if not damageable. - * - * @return data of this material. - */ - public int getData() { - return this.data; - } + /** + * Get the {@link ItemStack} data of this material in older versions. + * Which can be accessed with {@link ItemStack#getData()} then MaterialData#getData() + * or {@link ItemStack#getDurability()} if not damageable. + * + * @return data of this material. + */ + public int getData() { + return this.data; + } - /** - * Get a list of materials names that was previously used by older versions. - * - * @return a list of string of legacy material names. - */ - public String[] getLegacy() { - return this.legacy; - } + /** + * Get a list of materials names that was previously used by older versions. + * + * @return a list of string of legacy material names. + */ + public String[] getLegacy() { + return this.legacy; + } - /** - * Parses the XMaterial as an {@link ItemStack}. - * - * @return an ItemStack with the same material (and data if in older versions.) - */ - public ItemStack parseItem() { - return parseItem(false); - } + /** + * Parses the XMaterial as an {@link ItemStack}. + * + * @return an ItemStack with the same material (and data if in older versions.) + */ + public ItemStack parseItem() { + return parseItem(false); + } - /** - * Parses the XMaterial as an {@link ItemStack}. - * - * @param suggest if true {@link #parseMaterial(boolean)} - * @return an ItemStack with the same material (and data if in older versions.) - */ - @SuppressWarnings("deprecation") - public ItemStack parseItem(boolean suggest) { - Material material = this.parseMaterial(suggest); - return isNewVersion() ? new ItemStack(material) : new ItemStack(material, 1, this.data); - } + /** + * Parses the XMaterial as an {@link ItemStack}. + * + * @param suggest if true {@link #parseMaterial(boolean)} + * @return an ItemStack with the same material (and data if in older versions.) + */ + @SuppressWarnings("deprecation") + public ItemStack parseItem(boolean suggest) { + Material material = this.parseMaterial(suggest); + return isNewVersion() ? new ItemStack(material) : new ItemStack(material, 1, this.data); + } - /** - * Parses the XMaterial as a {@link Material}. - * - * @return the Material related to this XMaterial based on the server version. - */ - public Material parseMaterial() { - return parseMaterial(false); - } + /** + * Parses the XMaterial as a {@link Material}. + * + * @return the Material related to this XMaterial based on the server version. + */ + public Material parseMaterial() { + return parseMaterial(false); + } - /** - * Parses the XMaterial as a {@link Material}. - * - * @param suggest Use a suggested material if the material is added in the new version. - * @return the Material related to this XMaterial based on the server version. - * @see #matchXMaterial(String, byte) - */ - public Material parseMaterial(boolean suggest) { - Material newMat = Material.getMaterial(this.name()); + /** + * Parses the XMaterial as a {@link Material}. + * + * @param suggest Use a suggested material if the material is added in the new version. + * @return the Material related to this XMaterial based on the server version. + * @see #matchXMaterial(String, byte) + */ + public Material parseMaterial(boolean suggest) { + Material newMat = Material.getMaterial(this.name()); - // If the name is not null it's probably the new version. - // So you can still use this name even if it's a duplicated name. - // Since duplicated names only apply to older versions. - if (newMat != null && (isNewVersion() || !this.isDuplicated())) return newMat; - return requestOldMaterial(suggest); - } + // If the name is not null it's probably the new version. + // So you can still use this name even if it's a duplicated name. + // Since duplicated names only apply to older versions. + if (newMat != null && (isNewVersion() || !this.isDuplicated())) return newMat; + return requestOldMaterial(suggest); + } - /** - * Parses from old material names and can accept suggestions. - * - * @param suggest Accept suggestions for newly added blocks - * @return A parsed Material suitable for this minecraft version. - */ - private Material requestOldMaterial(boolean suggest) { - Material oldMat; - boolean isNew = getVersionIfNew() != MinecraftVersion.UNKNOWN; - for (int i = this.legacy.length - 1; i >= 0; i--) { - String legacyName = this.legacy[i]; - // Slash means it's just another name for the material in another version. - if (legacyName.contains("/")) { - oldMat = Material.getMaterial(parseLegacyVersionMaterialName(legacyName)); + /** + * Parses from old material names and can accept suggestions. + * + * @param suggest Accept suggestions for newly added blocks + * @return A parsed Material suitable for this minecraft version. + */ + private Material requestOldMaterial(boolean suggest) { + Material oldMat; + boolean isNew = getVersionIfNew() != MinecraftVersion.UNKNOWN; + for (int i = this.legacy.length - 1; i >= 0; i--) { + String legacyName = this.legacy[i]; + // Slash means it's just another name for the material in another version. + if (legacyName.contains("/")) { + oldMat = Material.getMaterial(parseLegacyVersionMaterialName(legacyName)); - if (oldMat != null) return oldMat; - else continue; - } - if (isNew) { - if (suggest) { - oldMat = Material.getMaterial(legacyName); if (oldMat != null) return oldMat; - } else return null; - // According to the suggestion format list, all the other names continuing - // from here are considered as a "suggestion" if there's no slash anymore. - } - oldMat = Material.getMaterial(legacyName); - if (oldMat != null) return oldMat; - } - return null; - } + else continue; + } + if (isNew) { + if (suggest) { + oldMat = Material.getMaterial(legacyName); + if (oldMat != null) return oldMat; + } else return null; + // According to the suggestion format list, all the other names continuing + // from here are considered as a "suggestion" if there's no slash anymore. + } + oldMat = Material.getMaterial(legacyName); + if (oldMat != null) return oldMat; + } + return null; + } - /** - * Checks if an item is similar to the material and its data (if in older versions.) - * - * @param item item to check. - * @return true if the material is the same as the item's material (and data if in older versions.) - */ - @SuppressWarnings("deprecation") - public boolean isSimilar(ItemStack item) { - Objects.requireNonNull(item, "ItemStack cannot be null"); - Objects.requireNonNull(item.getType(), "ItemStack's material cannot be null"); - return (isNewVersion() || this.isDamageable()) ? item.getType() == this.parseMaterial() : item.getType() == this.parseMaterial() && item.getDurability() == this.data; - } + /** + * Checks if an item is similar to the material and its data (if in older versions.) + * + * @param item item to check. + * @return true if the material is the same as the item's material (and data if in older versions.) + */ + @SuppressWarnings("deprecation") + public boolean isSimilar(ItemStack item) { + Objects.requireNonNull(item, "ItemStack cannot be null"); + Objects.requireNonNull(item.getType(), "ItemStack's material cannot be null"); + return (isNewVersion() || this.isDamageable()) ? item.getType() == this.parseMaterial() : item.getType() == this.parseMaterial() && item.getDurability() == this.data; + } - /** - * Get the suggested material names that can be used instead of this material. - * - * @return a list of suggested material names. - */ - public String[] getSuggestions() { - if (!this.legacy[0].contains(".")) return new String[0]; - return Arrays.stream(this.legacy).filter(mat -> !mat.contains(".")).toArray(String[]::new); - } + /** + * Get the suggested material names that can be used instead of this material. + * + * @return a list of suggested material names. + */ + public String[] getSuggestions() { + if (!this.legacy[0].contains(".")) return new String[0]; + return Arrays.stream(this.legacy).filter(mat -> !mat.contains(".")).toArray(String[]::new); + } - /** - * Checks if this material is supported in the current version. - * It'll check both the newest matetrial name and for legacy names. - * - * @return true if the material exists in {@link Material} list. - */ - public boolean isSupported() { - return Arrays.stream(Material.values()).anyMatch(mat -> mat.name().equals(this.name()) || this.matchAnyLegacy(mat.name())); - } + /** + * Checks if this material is supported in the current version. + * It'll check both the newest matetrial name and for legacy names. + * + * @return true if the material exists in {@link Material} list. + */ + public boolean isSupported() { + return Arrays.stream(Material.values()).anyMatch(mat -> mat.name().equals(this.name()) || this.matchAnyLegacy(mat.name())); + } - /** - * Gets the added version if the material is newly added after the 1.13 Aquatic Update and higher. - * - * @return the version which the material was added in. {@link MinecraftVersion#UNKNOWN} if not new. - * @see #isNew() - */ - public MinecraftVersion getVersionIfNew() { - return this.isNew() ? valueOfVersion(this.legacy[0]) : MinecraftVersion.UNKNOWN; - } + /** + * Gets the added version if the material is newly added after the 1.13 Aquatic Update and higher. + * + * @return the version which the material was added in. {@link MinecraftVersion#UNKNOWN} if not new. + * @see #isNew() + */ + public MinecraftVersion getVersionIfNew() { + return this.isNew() ? valueOfVersion(this.legacy[0]) : MinecraftVersion.UNKNOWN; + } - /** - * Checks if the material is newly added after the 1.13 Aquatic Update. - * - * @return true if it was newly added. - */ - public boolean isNew() { - return this.legacy[0].contains("."); - } + /** + * Checks if the material is newly added after the 1.13 Aquatic Update. + * + * @return true if it was newly added. + */ + public boolean isNew() { + return this.legacy[0].contains("."); + } - /** - * Gets the suggested material instead of returning null for unsupported versions. - * This is somehow similar to what ProtcolSupport and ViaVersion are doing to new materials. - * Don't use this if you want to parse to a {@link Material} - * - * @return The suggested material that is similar. - * @see #parseMaterial() - */ - public XMaterial suggestOldMaterialIfNew() { - if (getVersionIfNew() == MinecraftVersion.UNKNOWN || this.legacy.length == 1) return null; + /** + * Gets the suggested material instead of returning null for unsupported versions. + * This is somehow similar to what ProtcolSupport and ViaVersion are doing to new materials. + * Don't use this if you want to parse to a {@link Material} + * + * @return The suggested material that is similar. + * @see #parseMaterial() + */ + public XMaterial suggestOldMaterialIfNew() { + if (getVersionIfNew() == MinecraftVersion.UNKNOWN || this.legacy.length == 1) return null; - // We need a loop because: Newest -> Oldest - for (int i = this.legacy.length - 1; i >= 0; i--) { - String legacyName = this.legacy[i]; + // We need a loop because: Newest -> Oldest + for (int i = this.legacy.length - 1; i >= 0; i--) { + String legacyName = this.legacy[i]; - if (legacyName.contains("/")) continue; - XMaterial mat = matchXMaterial(parseLegacyVersionMaterialName(legacyName), this.data); - if (mat != null && this != mat) return mat; - } - return null; - } + if (legacyName.contains("/")) continue; + XMaterial mat = matchXMaterial(parseLegacyVersionMaterialName(legacyName), this.data); + if (mat != null && this != mat) return mat; + } + return null; + } - /** - * Only major versions related to material changes. - */ - public enum MinecraftVersion { - /** - * Bountiful Update - */ - VERSION_1_8, - /** - * Combat Update (Pitiful Update?) - */ - VERSION_1_9, - /** - * Aquatic Update - */ - VERSION_1_13, - /** - * Village Pillage Update - */ - VERSION_1_14, - /** - * 1.7 or below. - * Using {@link #getVersionIfNew()} it means 1.12 or below. - */ - UNKNOWN; + /** + * Only major versions related to material changes. + */ + public enum MinecraftVersion { + /** + * Bountiful Update + */ + VERSION_1_8, + /** + * Combat Update (Pitiful Update?) + */ + VERSION_1_9, + /** + * Aquatic Update + */ + VERSION_1_13, + /** + * Village Pillage Update + */ + VERSION_1_14, + /** + * 1.7 or below. + * Using {@link #getVersionIfNew()} it means 1.12 or below. + */ + UNKNOWN; - public static final MinecraftVersion[] VALUES = MinecraftVersion.values(); - } + public static final MinecraftVersion[] VALUES = MinecraftVersion.values(); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java b/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java index 66ea11eb..1cc0da09 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. + 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 7dfeba74..47bf78bb 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 = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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 2e688f0e..68ac6c62 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java @@ -27,308 +27,308 @@ 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); + while ((read = defLangStream.read(bytes)) != -1) { + out.write(bytes, 0, read); + } + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new BufferedReader(new InputStreamReader(defLangStream))); + TL.setFile(defConfig); } - 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(); + } 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(); + 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()); + } + } + + // 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 Driftay."); + 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"); + } + + // -------------------------------------------- // + // 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); + } + + // -------------------------------------------- // + // LANG AND TAGS + // -------------------------------------------- // + + 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 initTXT() { + this.addRawTags(); + + 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"); + + for (Entry rawTag : this.rawTags.entrySet()) { + this.txt.tags.put(rawTag.getKey(), TextUtil.parseColor(rawTag.getValue())); + } + } + + // -------------------------------------------- // + // COMMAND HANDLING + // -------------------------------------------- // + + // can be overridden by FactionsPlugin 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(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 (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); - YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); - for (TL item : TL.values()) { - if (conf.getString(item.getPath()) == null) { - conf.set(item.getPath(), item.getDefault()); - } - } + if (testOnly) { + return true; + } - // 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."); - } + if (async) { + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, () -> command.execute(sender, args)); + } else { + command.execute(sender, args); + } - 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 Driftay."); - 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"); - } - - // -------------------------------------------- // - // 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); - } - - // -------------------------------------------- // - // LANG AND TAGS - // -------------------------------------------- // - - 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 initTXT() { - this.addRawTags(); - - 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"); - - for (Entry rawTag : this.rawTags.entrySet()) { - this.txt.tags.put(rawTag.getKey(), TextUtil.parseColor(rawTag.getValue())); - } - } - - // -------------------------------------------- // - // COMMAND HANDLING - // -------------------------------------------- // - - // can be overridden by FactionsPlugin 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(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 (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 (testOnly) { - return true; + return true; } + } + } + return false; + } - if (async) { - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, () -> command.execute(sender, args)); - } else { - command.execute(sender, args); - } + public boolean handleCommand(CommandSender sender, String commandString) { + return this.handleCommand(sender, commandString, false); + } - return true; - } - } - } - return false; - } + // -------------------------------------------- // + // HOOKS + // -------------------------------------------- // + public void preAutoSave() { - public boolean handleCommand(CommandSender sender, String commandString) { - return this.handleCommand(sender, commandString, false); - } + } - // -------------------------------------------- // - // HOOKS - // -------------------------------------------- // - public void preAutoSave() { + public void postAutoSave() { - } + } - public void postAutoSave() { + public Map getStuckMap() { + return this.stuckMap; + } - } + public Map getTimers() { + return this.timers; + } - public Map getStuckMap() { - return this.stuckMap; - } + // -------------------------------------------- // + // LOGGING + // -------------------------------------------- // + public void log(Object msg) { + log(Level.INFO, msg); + } - public Map getTimers() { - return this.timers; - } + public void log(String str, Object... args) { + log(Level.INFO, this.txt.parse(str, args)); + } - // -------------------------------------------- // - // LOGGING - // -------------------------------------------- // - public void log(Object msg) { - log(Level.INFO, msg); - } + public void log(Level level, String str, Object... args) { + log(level, 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, 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 e1d9f132..43af116b 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, FactionsPlugin.getInstance().getPlayerFactionTag(speaker)).replace("[FACTION_TITLE]", FactionsPlugin.getInstance().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 c4c778d1..5413ef03 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java @@ -3,44 +3,44 @@ package com.massivecraft.factions.zcore.fperms; import com.massivecraft.factions.FactionsPlugin; public enum Access { - ALLOW("Allow"), - DENY("Deny"), - UNDEFINED("Undefined"); + ALLOW("Allow"), + DENY("Deny"), + UNDEFINED("Undefined"); - private final String name; + private final String name; - Access(String name) { - this.name = name; - } + Access(String name) { + this.name = name; + } - /** - * 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 static Access booleanToAccess(boolean access) { - if (access) return Access.ALLOW; - else return Access.DENY; - } + public static Access booleanToAccess(boolean access) { + if (access) return Access.ALLOW; + else return Access.DENY; + } - public String getName() { - return this.name.toLowerCase(); - } + public String getName() { + return this.name.toLowerCase(); + } - @Override - public String toString() { - return name(); - } + @Override + public String toString() { + return name(); + } - public String getColor() { - return FactionsPlugin.getInstance().getConfig().getString("fperm-gui.action.Access-Colors." + this.name); - } + public String getColor() { + return FactionsPlugin.getInstance().getConfig().getString("fperm-gui.action.Access-Colors." + this.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 5cd98f87..c4bdae60 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java @@ -1,157 +1,157 @@ package com.massivecraft.factions.zcore.fperms; public class DefaultPermissions { - 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 check; - public boolean spawner; + 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 check; + public boolean spawner; - public 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.check = def; - this.spawner = def; - } + 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.check = 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 canCheck, - 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.check = canCheck; - this.spawner = canSpawners; - } + 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 canCheck, + 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.check = canCheck; + this.spawner = canSpawners; + } - @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 == "home") return this.home; - 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 == "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 == "check") return this.check; - else if (name == "spawner") return this.spawner; - else return false; - } + @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 == "home") return this.home; + 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 == "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 == "check") return this.check; + 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..1c607fa8 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 3c721c27..61cd2843 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java @@ -13,105 +13,105 @@ import java.util.List; import java.util.Map; 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"), - CHECK("check"), - 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"), + CHECK("check"), + 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; + } - 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; + } - public static PermissableAction fromSlot(int slot) { - for (PermissableAction action : PermissableAction.values()) { - if (action.getSlot() == slot) return action; - } - return null; - } + public static PermissableAction fromSlot(int slot) { + for (PermissableAction action : PermissableAction.values()) { + if (action.getSlot() == slot) return action; + } + return null; + } - public int getSlot() { - return FactionsPlugin.getInstance().getConfig().getInt("fperm-gui.action.slots." + this.name.toLowerCase()); - } + public int getSlot() { + return FactionsPlugin.getInstance().getConfig().getInt("fperm-gui.action.slots." + this.name.toLowerCase()); + } - /** - * 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; + } - public ItemStack buildAsset(FPlayer fme, Permissable perm) { - ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.action"); - ItemStack item = XMaterial.matchXMaterial(section.getString("Materials." + this.name)).parseItem(); - ItemMeta meta = item.getItemMeta(); + public ItemStack buildAsset(FPlayer fme, Permissable perm) { + ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.action"); + ItemStack item = XMaterial.matchXMaterial(section.getString("Materials." + this.name)).parseItem(); + ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(FactionsPlugin.getInstance().color(section.getString("placeholder-item.name").replace("{action}", this.name))); - List lore = section.getStringList("placeholder-item.lore"); + meta.setDisplayName(FactionsPlugin.getInstance().color(section.getString("placeholder-item.name").replace("{action}", this.name))); + List lore = section.getStringList("placeholder-item.lore"); - lore = FactionsPlugin.getInstance().replacePlaceholders(lore, - new Placeholder("{action-access-color}", fme.getFaction().getPermissions().get(perm).get(this).getColor()), - new Placeholder("{action-access}", fme.getFaction().getPermissions().get(perm).get(this).getName())); + lore = FactionsPlugin.getInstance().replacePlaceholders(lore, + new Placeholder("{action-access-color}", fme.getFaction().getPermissions().get(perm).get(this).getColor()), + new Placeholder("{action-access}", fme.getFaction().getPermissions().get(perm).get(this).getName())); - meta.setLore(FactionsPlugin.getInstance().colorList(lore)); - item.setItemMeta(meta); - return item; - } + meta.setLore(FactionsPlugin.getInstance().colorList(lore)); + item.setItemMeta(meta); + return item; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionFrame.java b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionFrame.java index fe31f632..96215fa6 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionFrame.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionFrame.java @@ -20,83 +20,84 @@ import java.util.List; public class PermissableActionFrame { - private Gui gui; + private Gui gui; - public PermissableActionFrame(Faction f) { - ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.action"); - gui = new Gui(FactionsPlugin.getInstance(), - section.getInt("rows", 3), - FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.action.name").replace("{faction}", f.getTag()))); - } + public PermissableActionFrame(Faction f) { + ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.action"); + gui = new Gui(FactionsPlugin.getInstance(), + section.getInt("rows", 3), + FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.action.name").replace("{faction}", f.getTag()))); + } - public void buildGUI(FPlayer fplayer, Permissable perm) { - PaginatedPane pane = new PaginatedPane(0, 0, 9, gui.getRows()); - List GUIItems = new ArrayList<>(); - ItemStack dumby = buildDummyItem(); - // Fill background of GUI with dumbyitem & replace GUI assets after - for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) GUIItems.add(new GuiItem(dumby, e -> e.setCancelled(true))); - for (PermissableAction action : PermissableAction.values()) { - if (action.getSlot() == -1) continue; - GUIItems.set(action.getSlot(), new GuiItem(action.buildAsset(fplayer, perm), e -> { - e.setCancelled(true); - if (PermissableAction.fromSlot(e.getSlot()) == action) { - Access access; - boolean success; - switch (e.getClick()) { - case LEFT: - access = Access.ALLOW; - success = fplayer.getFaction().setPermission(perm, action, access); - break; - case RIGHT: - access = Access.DENY; - success = fplayer.getFaction().setPermission(perm, action, access); - break; - case MIDDLE: - access = Access.UNDEFINED; - success = fplayer.getFaction().setPermission(perm, action, access); - break; - default: - return; + public void buildGUI(FPlayer fplayer, Permissable perm) { + PaginatedPane pane = new PaginatedPane(0, 0, 9, gui.getRows()); + List GUIItems = new ArrayList<>(); + ItemStack dumby = buildDummyItem(); + // Fill background of GUI with dumbyitem & replace GUI assets after + for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) + GUIItems.add(new GuiItem(dumby, e -> e.setCancelled(true))); + for (PermissableAction action : PermissableAction.values()) { + if (action.getSlot() == -1) continue; + GUIItems.set(action.getSlot(), new GuiItem(action.buildAsset(fplayer, perm), e -> { + e.setCancelled(true); + if (PermissableAction.fromSlot(e.getSlot()) == action) { + Access access; + boolean success; + switch (e.getClick()) { + case LEFT: + access = Access.ALLOW; + success = fplayer.getFaction().setPermission(perm, action, access); + break; + case RIGHT: + access = Access.DENY; + success = fplayer.getFaction().setPermission(perm, action, access); + break; + case MIDDLE: + access = Access.UNDEFINED; + success = fplayer.getFaction().setPermission(perm, action, access); + break; + default: + return; + } + if (success) fplayer.msg(TL.COMMAND_PERM_SET, action.name(), access.name(), perm.name()); + else fplayer.msg(TL.COMMAND_PERM_LOCKED); + FactionsPlugin.getInstance().log(String.format(TL.COMMAND_PERM_SET.toString(), action.name(), access.name(), perm.name()) + " for faction " + fplayer.getTag()); + // Closing and opening resets the cursor. + // fplayer.getPlayer().closeInventory(); + buildGUI(fplayer, perm); } - if (success) fplayer.msg(TL.COMMAND_PERM_SET, action.name(), access.name(), perm.name()); - else fplayer.msg(TL.COMMAND_PERM_LOCKED); - FactionsPlugin.getInstance().log(String.format(TL.COMMAND_PERM_SET.toString(), action.name(), access.name(), perm.name()) + " for faction " + fplayer.getTag()); - // Closing and opening resets the cursor. - // fplayer.getPlayer().closeInventory(); - buildGUI(fplayer, perm); - } - })); - } - GUIItems.set(FactionsPlugin.getInstance().getConfig().getInt("fperm-gui.action.slots.back"), new GuiItem(buildBackItem(), event -> { - event.setCancelled(true); - // Closing and opening resets the cursor. - // fplayer.getPlayer().closeInventory(); - new PermissableRelationFrame(fplayer.getFaction()).buildGUI(fplayer); - })); - pane.populateWithGuiItems(GUIItems); - gui.addPane(pane); - gui.update(); - gui.show(fplayer.getPlayer()); - } + })); + } + GUIItems.set(FactionsPlugin.getInstance().getConfig().getInt("fperm-gui.action.slots.back"), new GuiItem(buildBackItem(), event -> { + event.setCancelled(true); + // Closing and opening resets the cursor. + // fplayer.getPlayer().closeInventory(); + new PermissableRelationFrame(fplayer.getFaction()).buildGUI(fplayer); + })); + pane.populateWithGuiItems(GUIItems); + gui.addPane(pane); + gui.update(); + gui.show(fplayer.getPlayer()); + } - private ItemStack buildDummyItem() { - ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.dummy-item"); - ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); - ItemMeta meta = item.getItemMeta(); - meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); - meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); - item.setItemMeta(meta); - return item; - } + private ItemStack buildDummyItem() { + ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.dummy-item"); + ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); + ItemMeta meta = item.getItemMeta(); + meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); + meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); + item.setItemMeta(meta); + return item; + } - private ItemStack buildBackItem() { - ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.back-item"); - ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); - ItemMeta meta = item.getItemMeta(); - meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); - meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); - item.setItemMeta(meta); - return item; - } + private ItemStack buildBackItem() { + ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.back-item"); + ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); + ItemMeta meta = item.getItemMeta(); + meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); + meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); + item.setItemMeta(meta); + return item; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableRelationFrame.java b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableRelationFrame.java index db7dc7e3..6ffc9c18 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableRelationFrame.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableRelationFrame.java @@ -19,61 +19,62 @@ import java.util.List; public class PermissableRelationFrame { - private Gui gui; + private Gui gui; - public PermissableRelationFrame(Faction f) { - ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation"); - gui = new Gui(FactionsPlugin.getInstance(), - section.getInt("rows", 3), - FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.relation.name").replace("{faction}", f.getTag()))); - } + public PermissableRelationFrame(Faction f) { + ConfigurationSection section = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation"); + gui = new Gui(FactionsPlugin.getInstance(), + section.getInt("rows", 3), + FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.relation.name").replace("{faction}", f.getTag()))); + } - public void buildGUI(FPlayer fplayer) { - PaginatedPane pane = new PaginatedPane(0, 0, 9, gui.getRows()); - List GUIItems = new ArrayList<>(); - ItemStack dumby = buildDummyItem(); - // Fill background of GUI with dumbyitem & replace GUI assets after - for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) GUIItems.add(new GuiItem(dumby, e -> e.setCancelled(true))); - ConfigurationSection sec = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation"); - for (String key : sec.getConfigurationSection("slots").getKeys(false)) { - GUIItems.set(sec.getInt("slots." + key), new GuiItem(buildAsset("fperm-gui.relation.materials." + key, key), e -> { - e.setCancelled(true); - // Closing and opening resets the cursor. - // e.getWhoClicked().closeInventory(); - new PermissableActionFrame(fplayer.getFaction()).buildGUI(fplayer, getPermissable(key)); - })); - } - pane.populateWithGuiItems(GUIItems); - gui.addPane(pane); - gui.update(); - gui.show(fplayer.getPlayer()); - } + public void buildGUI(FPlayer fplayer) { + PaginatedPane pane = new PaginatedPane(0, 0, 9, gui.getRows()); + List GUIItems = new ArrayList<>(); + ItemStack dumby = buildDummyItem(); + // Fill background of GUI with dumbyitem & replace GUI assets after + for (int x = 0; x <= (gui.getRows() * 9) - 1; x++) + GUIItems.add(new GuiItem(dumby, e -> e.setCancelled(true))); + ConfigurationSection sec = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.relation"); + for (String key : sec.getConfigurationSection("slots").getKeys(false)) { + GUIItems.set(sec.getInt("slots." + key), new GuiItem(buildAsset("fperm-gui.relation.materials." + key, key), e -> { + e.setCancelled(true); + // Closing and opening resets the cursor. + // e.getWhoClicked().closeInventory(); + new PermissableActionFrame(fplayer.getFaction()).buildGUI(fplayer, getPermissable(key)); + })); + } + pane.populateWithGuiItems(GUIItems); + gui.addPane(pane); + gui.update(); + gui.show(fplayer.getPlayer()); + } - private ItemStack buildAsset(String loc, String relation) { - ItemStack item = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString(loc)).parseItem(); - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.relation.Placeholder-Item.Name").replace("{relation}", relation))); - item.setItemMeta(meta); - return item; - } + private ItemStack buildAsset(String loc, String relation) { + ItemStack item = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString(loc)).parseItem(); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fperm-gui.relation.Placeholder-Item.Name").replace("{relation}", relation))); + item.setItemMeta(meta); + return item; + } - private ItemStack buildDummyItem() { - ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.dummy-item"); - ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); - ItemMeta meta = item.getItemMeta(); - meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); - meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); - item.setItemMeta(meta); - return item; - } + private ItemStack buildDummyItem() { + ConfigurationSection config = FactionsPlugin.getInstance().getConfig().getConfigurationSection("fperm-gui.dummy-item"); + ItemStack item = XMaterial.matchXMaterial(config.getString("Type")).parseItem(); + ItemMeta meta = item.getItemMeta(); + meta.setLore(FactionsPlugin.getInstance().colorList(config.getStringList("Lore"))); + meta.setDisplayName(FactionsPlugin.getInstance().color(config.getString("Name"))); + item.setItemMeta(meta); + return item; + } - 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; + } + } } 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 0385caf7..d22d05f3 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java @@ -18,62 +18,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(UpgradeType.CROP); - if (level != 0) { - int chance = -1; + if (!factionAtLoc.isWilderness()) { + int level = factionAtLoc.getUpgrade(UpgradeType.CROP); + if (level != 0) { + int chance = -1; - switch (level) { - case 1: - chance = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-1"); - break; - case 2: - chance = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-2"); - break; - case 3: - chance = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-3"); - break; - } + switch (level) { + case 1: + chance = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-1"); + break; + case 2: + chance = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-2"); + break; + case 3: + chance = FactionsPlugin.getInstance().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(XMaterial.WHEAT.parseMaterial())) { - e.setCancelled(true); - Crops c = new Crops(CropState.RIPE); - BlockState bs = e.getBlock().getState(); - bs.setData(c); - bs.update(); - } + if (e.getBlock().getType().equals(XMaterial.WHEAT.parseMaterial())) { + 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() == XMaterial.SUGAR_CANE.parseMaterial()) { - Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); + if (below.getType() == XMaterial.SUGAR_CANE.parseMaterial()) { + 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(XMaterial.SUGAR_CANE.parseMaterial()); - } + if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { + above.setType(XMaterial.SUGAR_CANE.parseMaterial()); + } - } 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 87bf37ff..2fedf1dc 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java @@ -11,42 +11,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) - return; + if (killer == null) + 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(UpgradeType.EXP); - if (level != 0) { + if (!faction.isWilderness()) { + int level = faction.getUpgrade(UpgradeType.EXP); + if (level != 0) { - double multiplier = -1; + double multiplier = -1; - switch (level) { - case 1: - multiplier = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-1"); - break; - case 2: - multiplier = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-2"); - break; - case 3: - multiplier = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-3"); - break; - } + switch (level) { + case 1: + multiplier = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-1"); + break; + case 2: + multiplier = FactionsPlugin.getInstance().getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-2"); + break; + case 3: + multiplier = FactionsPlugin.getInstance().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 fbc4d4c1..fed528bc 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java @@ -21,414 +21,414 @@ import java.util.List; public class FUpgradesGUI implements Listener { - public void openMainMenu(FPlayer fme) { - Inventory inventory = Bukkit.createInventory(null, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.DummyItem.rows") * 9, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Title").replace("{faction}", fme.getFaction().getTag()))); - ItemStack dummyItem = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.DummyItem.Type")).parseItem(); - ItemMeta meta = dummyItem.getItemMeta(); - meta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.DummyItem.Lore"))); - meta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.DummyItem.Name"))); - dummyItem.setItemMeta(meta); + public void openMainMenu(FPlayer fme) { + Inventory inventory = Bukkit.createInventory(null, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.DummyItem.rows") * 9, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Title").replace("{faction}", fme.getFaction().getTag()))); + ItemStack dummyItem = XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.DummyItem.Type")).parseItem(); + ItemMeta meta = dummyItem.getItemMeta(); + meta.setLore(FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.DummyItem.Lore"))); + meta.setDisplayName(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.DummyItem.Name"))); + dummyItem.setItemMeta(meta); - for (int fill = 0; fill < FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.DummyItem.rows") * 9; ++fill) { - inventory.setItem(fill, dummyItem); - } + for (int fill = 0; fill < FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.DummyItem.rows") * 9; ++fill) { + inventory.setItem(fill, dummyItem); + } - ItemStack[] items = buildItems(fme); - List cropSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Crops.CropItem.slots"); - List spawnerSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Spawners.SpawnerItem.slots"); - List expSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.EXP.EXPItem.slots"); - List chestSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Chest.ChestItem.slots"); - List powerSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Power.PowerItem.slots"); - List redSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Redstone.RedstoneItem.slots"); - List memberSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Members.MembersItem.slots"); + ItemStack[] items = buildItems(fme); + List cropSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Crops.CropItem.slots"); + List spawnerSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Spawners.SpawnerItem.slots"); + List expSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.EXP.EXPItem.slots"); + List chestSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Chest.ChestItem.slots"); + List powerSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Power.PowerItem.slots"); + List redSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Redstone.RedstoneItem.slots"); + List memberSlots = FactionsPlugin.getInstance().getConfig().getIntegerList("fupgrades.MainMenu.Members.MembersItem.slots"); - for (Integer cropSlot : cropSlots) if (cropSlot != -1) inventory.setItem(cropSlot, items[2]); + for (Integer cropSlot : cropSlots) if (cropSlot != -1) inventory.setItem(cropSlot, items[2]); - for (Integer spawnerSlot : spawnerSlots) if (spawnerSlot != -1) inventory.setItem(spawnerSlot, items[1]); + for (Integer spawnerSlot : spawnerSlots) if (spawnerSlot != -1) inventory.setItem(spawnerSlot, items[1]); - for (Integer expSlot : expSlots) if (expSlot != -1) inventory.setItem(expSlot, items[0]); + for (Integer expSlot : expSlots) if (expSlot != -1) inventory.setItem(expSlot, items[0]); - for (Integer chestSlot : chestSlots) if (chestSlot != -1) inventory.setItem(chestSlot, items[3]); + for (Integer chestSlot : chestSlots) if (chestSlot != -1) inventory.setItem(chestSlot, items[3]); - for (Integer powerSlot : powerSlots) if (powerSlot != -1) inventory.setItem(powerSlot, items[4]); + for (Integer powerSlot : powerSlots) if (powerSlot != -1) inventory.setItem(powerSlot, items[4]); - for (Integer redSlot : redSlots) if (redSlot != -1) inventory.setItem(redSlot, items[5]); + for (Integer redSlot : redSlots) if (redSlot != -1) inventory.setItem(redSlot, items[5]); - for (Integer memberSlot : memberSlots) if (memberSlot != -1) inventory.setItem(memberSlot, items[6]); + for (Integer memberSlot : memberSlots) if (memberSlot != -1) inventory.setItem(memberSlot, items[6]); - 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.getView().getTitle().equalsIgnoreCase(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().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]; - ItemStack powerItem = items[4]; - ItemStack redItem = items[5]; - ItemStack memberItem = items[6]; + FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getWhoClicked()); + if (e.getView().getTitle().equalsIgnoreCase(FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().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]; + ItemStack powerItem = items[4]; + ItemStack redItem = items[5]; + ItemStack memberItem = items[6]; - if (e.getCurrentItem().equals(cropItem)) { - int cropLevel = fme.getFaction().getUpgrade(UpgradeType.CROP); - switch (cropLevel) { - case 3: - return; - case 2: - upgradeItem(fme, UpgradeType.CROP, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-3")); - break; - case 1: - upgradeItem(fme, UpgradeType.CROP, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-2")); - break; - case 0: - upgradeItem(fme, UpgradeType.CROP, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-1")); - break; - } - } else if (e.getCurrentItem().equals(powerItem)) { - int powerLevel = fme.getFaction().getUpgrade(UpgradeType.POWER); - switch (powerLevel) { - case 3: - return; - case 2: - upgradeItem(fme, UpgradeType.POWER, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Cost.level-3")); - updatePower(fme.getFaction()); - break; - case 1: - upgradeItem(fme, UpgradeType.POWER, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Cost.level-2")); - updatePower(fme.getFaction()); - break; - case 0: - upgradeItem(fme, UpgradeType.POWER, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Cost.level-1")); - updatePower(fme.getFaction()); - break; - } - } else if (e.getCurrentItem().equals(spawnerItem)) { - int spawnerLevel = fme.getFaction().getUpgrade(UpgradeType.SPAWNER); - switch (spawnerLevel) { - case 3: - return; - case 2: - upgradeItem(fme, UpgradeType.SPAWNER, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-3")); - break; - case 1: - upgradeItem(fme, UpgradeType.SPAWNER, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-2")); - break; - case 0: - upgradeItem(fme, UpgradeType.SPAWNER, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-1")); - break; - } - } else if (e.getCurrentItem().equals(expItem)) { - int expLevel = fme.getFaction().getUpgrade(UpgradeType.EXP); - - switch (expLevel) { - case 3: - return; - case 2: - upgradeItem(fme, UpgradeType.EXP, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-3")); - break; - case 1: - upgradeItem(fme, UpgradeType.EXP, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-2")); - break; - case 0: - upgradeItem(fme, UpgradeType.EXP, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-1")); - break; - } - } else if (e.getCurrentItem().equals(redItem)) { - int redLevel = fme.getFaction().getUpgrade(UpgradeType.REDSTONE); - switch (redLevel) { - case 1: - return; - case 0: - upgradeItem(fme, UpgradeType.REDSTONE, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.Cost")); - break; - } - } else if (e.getCurrentItem().equals(chestitem)) { - int chestLevel = fme.getFaction().getUpgrade(UpgradeType.CHEST); - switch (chestLevel) { - case 3: - return; - case 2: { - if (upgradeItem(fme, UpgradeType.CHEST, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-3"))) - updateChests(fme.getFaction()); - break; + if (e.getCurrentItem().equals(cropItem)) { + int cropLevel = fme.getFaction().getUpgrade(UpgradeType.CROP); + switch (cropLevel) { + case 3: + return; + case 2: + upgradeItem(fme, UpgradeType.CROP, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-3")); + break; + case 1: + upgradeItem(fme, UpgradeType.CROP, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-2")); + break; + case 0: + upgradeItem(fme, UpgradeType.CROP, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-1")); + break; } - case 1: { - if (upgradeItem(fme, UpgradeType.CHEST, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-2"))) - updateChests(fme.getFaction()); - break; + } else if (e.getCurrentItem().equals(powerItem)) { + int powerLevel = fme.getFaction().getUpgrade(UpgradeType.POWER); + switch (powerLevel) { + case 3: + return; + case 2: + upgradeItem(fme, UpgradeType.POWER, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Cost.level-3")); + updatePower(fme.getFaction()); + break; + case 1: + upgradeItem(fme, UpgradeType.POWER, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Cost.level-2")); + updatePower(fme.getFaction()); + break; + case 0: + upgradeItem(fme, UpgradeType.POWER, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Cost.level-1")); + updatePower(fme.getFaction()); + break; } - case 0: { - if (upgradeItem(fme, UpgradeType.CHEST, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-1"))) - updateChests(fme.getFaction()); - break; + } else if (e.getCurrentItem().equals(spawnerItem)) { + int spawnerLevel = fme.getFaction().getUpgrade(UpgradeType.SPAWNER); + switch (spawnerLevel) { + case 3: + return; + case 2: + upgradeItem(fme, UpgradeType.SPAWNER, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-3")); + break; + case 1: + upgradeItem(fme, UpgradeType.SPAWNER, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-2")); + break; + case 0: + upgradeItem(fme, UpgradeType.SPAWNER, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-1")); + break; } - } - } else if (e.getCurrentItem().equals(memberItem)) { - int memberLevel = fme.getFaction().getUpgrade(UpgradeType.MEMBERS) + 1; - if (!FactionsPlugin.getInstance().getConfig().isSet("fupgrades.MainMenu.Members.Cost.level-" + memberLevel)) { - return; - } - int cost = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Members.Cost.level-" + memberLevel); - if (hasMoney(fme, cost)) { - fme.getFaction().setUpgrade(UpgradeType.MEMBERS, memberLevel); - fme.getPlayer().closeInventory(); - takeMoney(fme, cost); - } - } - } - } + } else if (e.getCurrentItem().equals(expItem)) { + int expLevel = fme.getFaction().getUpgrade(UpgradeType.EXP); - private void updateChests(Faction faction) { - String invName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fchest.Inventory-Title")); + switch (expLevel) { + case 3: + return; + case 2: + upgradeItem(fme, UpgradeType.EXP, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-3")); + break; + case 1: + upgradeItem(fme, UpgradeType.EXP, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-2")); + break; + case 0: + upgradeItem(fme, UpgradeType.EXP, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-1")); + break; + } + } else if (e.getCurrentItem().equals(redItem)) { + int redLevel = fme.getFaction().getUpgrade(UpgradeType.REDSTONE); + switch (redLevel) { + case 1: + return; + case 0: + upgradeItem(fme, UpgradeType.REDSTONE, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.Cost")); + break; + } + } else if (e.getCurrentItem().equals(chestitem)) { + int chestLevel = fme.getFaction().getUpgrade(UpgradeType.CHEST); + switch (chestLevel) { + case 3: + return; + case 2: { + if (upgradeItem(fme, UpgradeType.CHEST, 3, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-3"))) + updateChests(fme.getFaction()); + break; + } + case 1: { + if (upgradeItem(fme, UpgradeType.CHEST, 2, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-2"))) + updateChests(fme.getFaction()); + break; + } + case 0: { + if (upgradeItem(fme, UpgradeType.CHEST, 1, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-1"))) + updateChests(fme.getFaction()); + break; + } + } + } else if (e.getCurrentItem().equals(memberItem)) { + int memberLevel = fme.getFaction().getUpgrade(UpgradeType.MEMBERS) + 1; + if (!FactionsPlugin.getInstance().getConfig().isSet("fupgrades.MainMenu.Members.Cost.level-" + memberLevel)) { + return; + } + int cost = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Members.Cost.level-" + memberLevel); + if (hasMoney(fme, cost)) { + fme.getFaction().setUpgrade(UpgradeType.MEMBERS, memberLevel); + fme.getPlayer().closeInventory(); + takeMoney(fme, cost); + } + } + } + } - for (Player player : faction.getOnlinePlayers()) { - if (player.getInventory().getTitle() != null && player.getInventory().getTitle().equalsIgnoreCase(invName)) - player.closeInventory(); - } + private void updateChests(Faction faction) { + String invName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fchest.Inventory-Title")); - int level = faction.getUpgrade(UpgradeType.CHEST); - int size = 1; + for (Player player : faction.getOnlinePlayers()) { + if (player.getInventory().getTitle() != null && player.getInventory().getTitle().equalsIgnoreCase(invName)) + player.closeInventory(); + } - switch (level) { - case 1: - size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-1"); - break; - case 2: - size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-2"); - break; - case 3: - size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-3"); - break; - } - faction.setChestSize(size * 9); - } + int level = faction.getUpgrade(UpgradeType.CHEST); + int size = 1; - private void updatePower(Faction faction) { - int level = faction.getUpgrade(UpgradeType.POWER); - double power = 0.0; + switch (level) { + case 1: + size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-1"); + break; + case 2: + size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-2"); + break; + case 3: + size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-3"); + break; + } + faction.setChestSize(size * 9); + } - switch (level) { - case 1: - power = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Power-Boost.level-1"); - break; - case 2: - power = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Power-Boost.level-2"); - break; - case 3: - power = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Power-Boost.level-3"); - break; - } - faction.setPowerBoost(power); - } + private void updatePower(Faction faction) { + int level = faction.getUpgrade(UpgradeType.POWER); + double power = 0.0; - @SuppressWarnings("Duplicates") - private ItemStack[] buildItems(FPlayer fme) { - Material expMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.EXP.EXPItem.Type")); - int expAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.EXPItem.Amount"); - short expData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.EXPItem.Damage") + ""); - String expName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.EXP.EXPItem.Name")); - List expLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.EXP.EXPItem.Lore")); - int expLevel = fme.getFaction().getUpgrade(UpgradeType.EXP); + switch (level) { + case 1: + power = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Power-Boost.level-1"); + break; + case 2: + power = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Power-Boost.level-2"); + break; + case 3: + power = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.Power-Boost.level-3"); + break; + } + faction.setPowerBoost(power); + } - for (int i = 0; i <= expLore.size() - 1; i++) - expLore.set(i, expLore.get(i).replace("{level}", expLevel + "")); + @SuppressWarnings("Duplicates") + private ItemStack[] buildItems(FPlayer fme) { + Material expMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.EXP.EXPItem.Type")); + int expAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.EXPItem.Amount"); + short expData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.EXP.EXPItem.Damage") + ""); + String expName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.EXP.EXPItem.Name")); + List expLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.EXP.EXPItem.Lore")); + int expLevel = fme.getFaction().getUpgrade(UpgradeType.EXP); - ItemStack expItem = FactionsPlugin.getInstance().createItem(expMaterial, expAmt, expData, expName, expLore); + for (int i = 0; i <= expLore.size() - 1; i++) + expLore.set(i, expLore.get(i).replace("{level}", expLevel + "")); - if (expLevel >= 1) { - ItemMeta itemMeta = expItem.getItemMeta(); - if (!FactionsPlugin.getInstance().mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + ItemStack expItem = FactionsPlugin.getInstance().createItem(expMaterial, expAmt, expData, expName, expLore); - expItem.setItemMeta(itemMeta); - expItem.setAmount(expLevel); - } + if (expLevel >= 1) { + ItemMeta itemMeta = expItem.getItemMeta(); + if (!FactionsPlugin.getInstance().mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - Material spawnerMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Spawners.SpawnerItem.Type")); - int spawnerAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.SpawnerItem.Amount"); - short spawnerData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.SpawnerItem.Damage") + ""); - String spawnerName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Spawners.SpawnerItem.Name")); - List spawnerLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Spawners.SpawnerItem.Lore")); - int spawnerLevel = fme.getFaction().getUpgrade(UpgradeType.SPAWNER); + expItem.setItemMeta(itemMeta); + expItem.setAmount(expLevel); + } - for (int i = 0; i <= spawnerLore.size() - 1; i++) { - spawnerLore.set(i, spawnerLore.get(i).replace("{level}", spawnerLevel + "")); - } + Material spawnerMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Spawners.SpawnerItem.Type")); + int spawnerAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.SpawnerItem.Amount"); + short spawnerData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.SpawnerItem.Damage") + ""); + String spawnerName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Spawners.SpawnerItem.Name")); + List spawnerLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Spawners.SpawnerItem.Lore")); + int spawnerLevel = fme.getFaction().getUpgrade(UpgradeType.SPAWNER); + + for (int i = 0; i <= spawnerLore.size() - 1; i++) { + spawnerLore.set(i, spawnerLore.get(i).replace("{level}", spawnerLevel + "")); + } - Material cropMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Type")); - int cropAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Amount"); - short cropData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Damage") + ""); - String cropName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Name")); - List cropLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Crops.CropItem.Lore")); - int cropLevel = fme.getFaction().getUpgrade(UpgradeType.CROP); + Material cropMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Type")); + int cropAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Amount"); + short cropData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Damage") + ""); + String cropName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Name")); + List cropLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Crops.CropItem.Lore")); + int cropLevel = fme.getFaction().getUpgrade(UpgradeType.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 = FactionsPlugin.getInstance().createItem(cropMaterial, cropAmt, cropData, cropName, cropLore); - cropItem.getItemMeta().setLore(cropLore); + ItemStack cropItem = FactionsPlugin.getInstance().createItem(cropMaterial, cropAmt, cropData, cropName, cropLore); + cropItem.getItemMeta().setLore(cropLore); - if (cropLevel >= 1) { - ItemMeta itemMeta = cropItem.getItemMeta(); - if (!FactionsPlugin.getInstance().mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - cropItem.setItemMeta(itemMeta); + if (cropLevel >= 1) { + ItemMeta itemMeta = cropItem.getItemMeta(); + if (!FactionsPlugin.getInstance().mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + cropItem.setItemMeta(itemMeta); - cropItem.setAmount(cropLevel); - } + cropItem.setAmount(cropLevel); + } - ItemStack spawnerItem = FactionsPlugin.getInstance().createItem(spawnerMaterial, spawnerAmt, spawnerData, spawnerName, spawnerLore); - spawnerItem.getItemMeta().setLore(spawnerLore); - if (spawnerLevel >= 1) { - ItemMeta itemMeta = spawnerItem.getItemMeta(); - if (!FactionsPlugin.getInstance().mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + ItemStack spawnerItem = FactionsPlugin.getInstance().createItem(spawnerMaterial, spawnerAmt, spawnerData, spawnerName, spawnerLore); + spawnerItem.getItemMeta().setLore(spawnerLore); + if (spawnerLevel >= 1) { + ItemMeta itemMeta = spawnerItem.getItemMeta(); + if (!FactionsPlugin.getInstance().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(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Chest.ChestItem.Type")); - int chesttAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.ChestItem.Amount"); - short chestData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.ChestItem.Damage") + ""); - String chestName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Chest.ChestItem.Name", "&e&lUpgrade Chest Size")); - List chestLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Chest.ChestItem.Lore")); - int chestlevel = fme.getFaction().getUpgrade(UpgradeType.CHEST); + Material chestMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Chest.ChestItem.Type")); + int chesttAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.ChestItem.Amount"); + short chestData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.ChestItem.Damage") + ""); + String chestName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Chest.ChestItem.Name", "&e&lUpgrade Chest Size")); + List chestLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Chest.ChestItem.Lore")); + int chestlevel = fme.getFaction().getUpgrade(UpgradeType.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 = FactionsPlugin.getInstance().createItem(chestMaterial, chesttAmt, chestData, chestName, chestLore); + ItemStack chestItem = FactionsPlugin.getInstance().createItem(chestMaterial, chesttAmt, chestData, chestName, chestLore); - if (chestlevel >= 1) { - ItemMeta itemMeta = chestItem.getItemMeta(); - if (!FactionsPlugin.getInstance().mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + if (chestlevel >= 1) { + ItemMeta itemMeta = chestItem.getItemMeta(); + if (!FactionsPlugin.getInstance().mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - chestItem.setItemMeta(itemMeta); - chestItem.setAmount(chestlevel); - } + chestItem.setItemMeta(itemMeta); + chestItem.setAmount(chestlevel); + } - Material memberMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Members.MembersItem.Type")); - int memberAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Members.MembersItem.Amount"); - short memberData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Members.MembersItem.Damage") + ""); - String memberName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Members.MembersItem.Name", "&e&lUpgrade Member Size")); - List memberLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Members.MembersItem.Lore")); - int memberlevel = fme.getFaction().getUpgrade(UpgradeType.MEMBERS); + Material memberMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Members.MembersItem.Type")); + int memberAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Members.MembersItem.Amount"); + short memberData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Members.MembersItem.Damage") + ""); + String memberName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Members.MembersItem.Name", "&e&lUpgrade Member Size")); + List memberLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Members.MembersItem.Lore")); + int memberlevel = fme.getFaction().getUpgrade(UpgradeType.MEMBERS); - for (int i = 0; i <= memberLore.size() - 1; i++) { - String line = memberLore.get(i); - line = line.replace("{level}", memberlevel + ""); - memberLore.set(i, line); - } + for (int i = 0; i <= memberLore.size() - 1; i++) { + String line = memberLore.get(i); + line = line.replace("{level}", memberlevel + ""); + memberLore.set(i, line); + } - ItemStack memberItem = FactionsPlugin.getInstance().createItem(memberMaterial, memberAmt, memberData, memberName, memberLore); + ItemStack memberItem = FactionsPlugin.getInstance().createItem(memberMaterial, memberAmt, memberData, memberName, memberLore); - if (memberlevel >= 1) { - ItemMeta itemMeta = memberItem.getItemMeta(); - if (!FactionsPlugin.getInstance().mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + if (memberlevel >= 1) { + ItemMeta itemMeta = memberItem.getItemMeta(); + if (!FactionsPlugin.getInstance().mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - memberItem.setItemMeta(itemMeta); - memberItem.setAmount(memberlevel); - } + memberItem.setItemMeta(itemMeta); + memberItem.setAmount(memberlevel); + } - Material powerMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Power.PowerItem.Type")); - int powerAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.PowerItem.Amount"); - short powerData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.PowerItem.Damage") + ""); - String powerName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Power.PowerItem.Name")); - List powerLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Power.PowerItem.Lore")); - int powerLevel = fme.getFaction().getUpgrade(UpgradeType.POWER); + Material powerMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Power.PowerItem.Type")); + int powerAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.PowerItem.Amount"); + short powerData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Power.PowerItem.Damage") + ""); + String powerName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Power.PowerItem.Name")); + List powerLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Power.PowerItem.Lore")); + int powerLevel = fme.getFaction().getUpgrade(UpgradeType.POWER); - for (int i = 0; i <= powerLore.size() - 1; i++) { - String line = powerLore.get(i); - line = line.replace("{level}", powerLevel + ""); - powerLore.set(i, line); - } + for (int i = 0; i <= powerLore.size() - 1; i++) { + String line = powerLore.get(i); + line = line.replace("{level}", powerLevel + ""); + powerLore.set(i, line); + } - ItemStack powerItem = FactionsPlugin.getInstance().createItem(powerMaterial, powerAmt, powerData, powerName, powerLore); - powerItem.getItemMeta().setLore(powerLore); + ItemStack powerItem = FactionsPlugin.getInstance().createItem(powerMaterial, powerAmt, powerData, powerName, powerLore); + powerItem.getItemMeta().setLore(powerLore); - if (powerLevel >= 1) { - ItemMeta itemMeta = powerItem.getItemMeta(); - if (!FactionsPlugin.getInstance().mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - powerItem.setItemMeta(itemMeta); + if (powerLevel >= 1) { + ItemMeta itemMeta = powerItem.getItemMeta(); + if (!FactionsPlugin.getInstance().mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + powerItem.setItemMeta(itemMeta); - powerItem.setAmount(powerLevel); - } + powerItem.setAmount(powerLevel); + } - Material redMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Redstone.RedstoneItem.Type")); - int redAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.RedstoneItem.Amount"); - short redData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.RedstoneItem.Damage") + ""); - String redName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Redstone.RedstoneItem.Name")); - List redLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Redstone.RedstoneItem.Lore")); - int redLevel = fme.getFaction().getUpgrade(UpgradeType.REDSTONE); + Material redMaterial = Material.getMaterial(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Redstone.RedstoneItem.Type")); + int redAmt = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.RedstoneItem.Amount"); + short redData = Short.parseShort(FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.RedstoneItem.Damage") + ""); + String redName = FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fupgrades.MainMenu.Redstone.RedstoneItem.Name")); + List redLore = FactionsPlugin.getInstance().colorList(FactionsPlugin.getInstance().getConfig().getStringList("fupgrades.MainMenu.Redstone.RedstoneItem.Lore")); + int redLevel = fme.getFaction().getUpgrade(UpgradeType.REDSTONE); - for (int i = 0; i <= redLore.size() - 1; i++) { - String line = redLore.get(i); - line = line.replace("{level}", redLevel + ""); - redLore.set(i, line); - } + for (int i = 0; i <= redLore.size() - 1; i++) { + String line = redLore.get(i); + line = line.replace("{level}", redLevel + ""); + redLore.set(i, line); + } - ItemStack redItem = FactionsPlugin.getInstance().createItem(redMaterial, redAmt, redData, redName, redLore); - redItem.getItemMeta().setLore(redLore); + ItemStack redItem = FactionsPlugin.getInstance().createItem(redMaterial, redAmt, redData, redName, redLore); + redItem.getItemMeta().setLore(redLore); - if (redLevel >= 1) { - ItemMeta itemMeta = redItem.getItemMeta(); - if (!FactionsPlugin.getInstance().mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - redItem.setItemMeta(itemMeta); + if (redLevel >= 1) { + ItemMeta itemMeta = redItem.getItemMeta(); + if (!FactionsPlugin.getInstance().mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + redItem.setItemMeta(itemMeta); - redItem.setAmount(redLevel); - } + redItem.setAmount(redLevel); + } - return new ItemStack[]{expItem, spawnerItem, cropItem, chestItem, powerItem, redItem, memberItem}; - } + return new ItemStack[]{expItem, spawnerItem, cropItem, chestItem, powerItem, redItem, memberItem}; + } - 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, UpgradeType 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, UpgradeType 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/RedstoneUpgrade.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/RedstoneUpgrade.java index 7727345b..39b3def1 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/RedstoneUpgrade.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/RedstoneUpgrade.java @@ -12,23 +12,23 @@ import java.util.List; public class RedstoneUpgrade implements Listener { - @EventHandler - public void onWaterRedstone(BlockFromToEvent e) { - List unbreakable = FactionsPlugin.getInstance().getConfig().getStringList("no-water-destroy.Item-List"); - String block = e.getToBlock().getType().toString(); - FLocation floc = new FLocation(e.getToBlock().getLocation()); - Faction factionAtLoc = Board.getInstance().getFactionAt(floc); + @EventHandler + public void onWaterRedstone(BlockFromToEvent e) { + List unbreakable = FactionsPlugin.getInstance().getConfig().getStringList("no-water-destroy.Item-List"); + String block = e.getToBlock().getType().toString(); + FLocation floc = new FLocation(e.getToBlock().getLocation()); + Faction factionAtLoc = Board.getInstance().getFactionAt(floc); - if (!factionAtLoc.isWilderness()) { - int level = factionAtLoc.getUpgrade(UpgradeType.REDSTONE); - if (level != 0) { - if (level == 1) { - FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.Cost"); - } - if (unbreakable.contains(block)) { - e.setCancelled(true); - } - } - } - } + if (!factionAtLoc.isWilderness()) { + int level = factionAtLoc.getUpgrade(UpgradeType.REDSTONE); + if (level != 0) { + if (level == 1) { + FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Redstone.Cost"); + } + if (unbreakable.contains(block)) { + e.setCancelled(true); + } + } + } + } } 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 f3a8735a..d9c842f3 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(UpgradeType.SPAWNER); - if (level != 0) { - switch (level) { - case 1: - lowerSpawnerDelay(e, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-1")); - break; - case 2: - lowerSpawnerDelay(e, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-2")); - break; - case 3: - lowerSpawnerDelay(e, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-3")); - break; - } - } - } - } + if (!factionAtLoc.isWilderness()) { + int level = factionAtLoc.getUpgrade(UpgradeType.SPAWNER); + if (level != 0) { + switch (level) { + case 1: + lowerSpawnerDelay(e, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-1")); + break; + case 2: + lowerSpawnerDelay(e, FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-2")); + break; + case 3: + lowerSpawnerDelay(e, FactionsPlugin.getInstance().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/UpgradeType.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/UpgradeType.java index fbecc44e..9b041c90 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/UpgradeType.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/UpgradeType.java @@ -2,16 +2,16 @@ package com.massivecraft.factions.zcore.fupgrades; public enum UpgradeType { - CHEST("Chest"), SPAWNER("Spawner"), EXP("Exp"), CROP("Crop"), POWER("Power"), REDSTONE("Redstone"), MEMBERS("Members"); + CHEST("Chest"), SPAWNER("Spawner"), EXP("Exp"), CROP("Crop"), POWER("Power"), REDSTONE("Redstone"), MEMBERS("Members"); - private String id; + private String id; - UpgradeType(String id) { - this.id = id; - } + UpgradeType(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..2ef2abee 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..d70d50ab 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..fbfd3ad2 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..59c6ea70 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..533ccc67 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..00879793 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..5e652462 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..fdda9aea 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..196ccde3 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..9503d5e6 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..180ec543 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..f5697e1d 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..2a845a90 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 04bad776..599e6679 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java @@ -19,372 +19,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); - faction.getWarps().values().removeIf(lazyLocation -> flocation.isInChunk(lazyLocation.getLocation())); - clearOwnershipAt(flocation); - flocationIds.remove(flocation); - } + public void removeAt(FLocation flocation) { + Faction faction = getFactionAt(flocation); + faction.getWarps().values().removeIf(lazyLocation -> flocation.isInChunk(lazyLocation.getLocation())); + 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())) { - FactionsPlugin.getInstance().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())) { + FactionsPlugin.getInstance().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 + FactionsPlugin.getInstance().txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(fplayer)))); - int buffer = FactionsPlugin.getInstance().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 + FactionsPlugin.getInstance().txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(fplayer)))); + int buffer = FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0); - // Get the compass - ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, FactionsPlugin.getInstance().txt.parse("")); + // Get the compass + ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, FactionsPlugin.getInstance().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()); - - //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)); + 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 { - row.then("-").color(ChatColor.GRAY); + 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); - } + } + 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 = FactionsPlugin.getInstance().getConfig().getStringList("map"); + @SuppressWarnings("unused") + private List getToolTip(Faction faction, FPlayer to) { + List ret = new ArrayList<>(); + List show = FactionsPlugin.getInstance().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(FactionsPlugin.getInstance().txt.titleize(tag)); - } else { - ret.add(FactionsPlugin.getInstance().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(FactionsPlugin.getInstance().txt.titleize(tag)); + } else { + ret.add(FactionsPlugin.getInstance().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((FactionsPlugin.getInstance().txt.parse(msg.toOldMessageFormat()))); + if (TagUtil.hasFancy(parsed)) { + List fancy = TagUtil.parseFancy(faction, to, parsed); + if (fancy != null) { + for (FancyMessage msg : fancy) { + ret.add((FactionsPlugin.getInstance().txt.parse(msg.toOldMessageFormat()))); + } } - } - continue; - } + 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(FactionsPlugin.getInstance().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(FactionsPlugin.getInstance().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 (FPlayer fPlayer : FPlayers.getInstance().getOnlinePlayers()) { - if (fLocations.contains(fPlayer.getLastStoodAt()) && !fPlayer.isAdminBypassing() && fPlayer.isFlying()) { - fPlayer.setFlying(false); - } - } - for (FLocation floc : fLocations) { - super.remove(floc); - } - } - } + public void removeFaction(String factionId) { + Collection fLocations = factionToLandMap.removeAll(factionId); + for (FPlayer fPlayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fLocations.contains(fPlayer.getLastStoodAt()) && !fPlayer.isAdminBypassing() && fPlayer.isFlying()) { + fPlayer.setFlying(false); + } + } + 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 a78e2b6d..099970df 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java @@ -41,1267 +41,1267 @@ import java.util.*; */ public abstract class MemoryFPlayer implements FPlayer { - public boolean inVault = false; - protected HashMap commandCooldown = new HashMap<>(); - 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; - protected boolean notificationsEnabled = true; - protected boolean isAlt = false; - boolean inspectMode = false; - - public MemoryFPlayer() { - } - - public MemoryFPlayer(String id) { - this.id = id; - this.isAlt = false; - this.resetFactionData(false); - this.power = Conf.powerPlayerStarting; - this.lastPowerUpdateTime = System.currentTimeMillis(); - this.lastLoginTime = System.currentTimeMillis(); - this.mapAutoUpdating = false; - this.autoClaimFor = null; - this.notificationsEnabled = true; - this.autoSafeZoneEnabled = false; - this.autoWarZoneEnabled = false; - this.loginPvpDisabled = Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0; - this.powerBoost = 0.0; - this.getKills(); - this.getDeaths(); - this.showScoreboard = FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-enabled", false); - 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.isAlt = other.isAlt; - 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.getKills(); - this.getDeaths(); - this.isAdminBypassing = other.isAdminBypassing; - this.notificationsEnabled = other.notificationsEnabled; - this.showScoreboard = FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-enabled", true); - this.mapHeight = Conf.mapHeight; - } - - public boolean isAlt() { - return isAlt; - } - - public void setAlt(boolean alt) { - this.isAlt = alt; - } - - 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 int getCooldown(String cmd) { - int seconds = 0; - if (this.getPlayer().isOp()) - return 0; - if (commandCooldown.containsKey(cmd)) - seconds = (int) ((this.commandCooldown.get(cmd) - System.currentTimeMillis()) / 1000); - return seconds; - } - - public void setCooldown(String cmd, long cooldown) { - if (this.getPlayer().isOp()) - return; - - this.commandCooldown.put(cmd, cooldown); - } - - public boolean isCooldownEnded(String cmd) { - if (this.getPlayer().isOp()) - return true; - if (!commandCooldown.containsKey(cmd)) - return true; - else return commandCooldown.containsKey(cmd) && commandCooldown.get(cmd) <= System.currentTimeMillis(); - } - - - public Faction getFaction() { - if (this.factionId == null) { - this.factionId = "0"; - } - return Factions.getInstance().getFactionById(this.factionId); - } - - public void setFaction(Faction faction, boolean alt) { - Faction oldFaction = this.getFaction(); - if (oldFaction != null) { - if (this.isAlt()) { - oldFaction.removeAltPlayer(this); - } - - oldFaction.removeFPlayer(this); - } - if (alt) { - faction.addAltPlayer(this); - } else { - faction.addFPlayer(this); - } - this.factionId = faction.getId(); - } - - @Override - public void setNotificationsEnabled(boolean enabled) { - this.notificationsEnabled = enabled; - } - - @Override - public boolean hasNotificationsEnabled() { - return this.notificationsEnabled; - } - - 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) { - if (this.role == role) { - return; - } - - FPlayerRoleChangeEvent event = new FPlayerRoleChangeEvent(getFaction(), this, role); - Bukkit.getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - this.role = event.getTo(); - } - } - - 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; - FactionsPlugin.getInstance().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; - this.isAlt = false; - } - - 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.getScheduler().runTask(FactionsPlugin.getInstance(), () -> 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 = FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.also-send-chat", true); - } - if (showChat) { - this.sendMessage(FactionsPlugin.getInstance().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() && FactionsPlugin.getInstance().getConfig().contains("scoreboard.finfo") && FactionsPlugin.getInstance().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) { - FactionsPlugin.getInstance().log(TL.LEAVE_LEFT.format(this.getName(), myFaction.getTag())); - } - } - - myFaction.removeAnnouncements(this); - - if (this.isAlt()) { - myFaction.removeAltPlayer(this); - this.msg(TL.LEAVE_LEFT, this.describeTo(this, true), myFaction.describeTo(this)); - } - - this.resetFactionData(); - setFlying(false); - - 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(getPlayer(), myFaction.getId(), PlayerDisbandReason.LEAVE); - Bukkit.getPluginManager().callEvent(disbandEvent); - - Factions.getInstance().removeFaction(myFaction.getId()); - if (Conf.logFactionDisband) { - FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().getConfig().getInt("hcf.buffer-zone", 0); - int worldBuffer = FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0); - - if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(flocation)) { - // Checks for WorldGuard regions in the chunk attempting to be claimed - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PROTECTED.toString()); - } else if (flocation.isOutsideWorldBorder(FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0))) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); - } else if (Conf.useWorldConfigurationsAsWhitelist != Conf.worldsNoClaiming.contains(flocation.getWorldName())) { - error = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); - } else if (forFaction == currentFaction) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true)); - } else if (this.getRole().value < Role.MODERATOR.value) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_MUSTBE.toString(), Role.MODERATOR.getTranslation()); - } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_MEMBERS.toString(), Conf.claimsRequireMinFactionMembers); - } else if (currentFaction.isSafeZone()) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_SAFEZONE.toString()); - } else if (currentFaction.isWarZone()) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_WARZONE.toString()); - } else if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.allow-overclaim", true) && ownedLand >= forFaction.getPowerRounded()) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_POWER.toString()); - } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_LIMIT.toString()); - } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { - error = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_CONTIGIOUS.toString()); - } else { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_FACTIONCONTIGUOUS.toString()); - } - } else if (factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer)); - } else if (flocation.isOutsideWorldBorder(worldBuffer)) { - if (worldBuffer > 0) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer)); - } else { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); - } - } else if (currentFaction.isNormal()) { - if (myFaction.isPeaceful()) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this)); - } else if (currentFaction.isPeaceful()) { - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this)); - } else if (!currentFaction.hasLandInflation()) { - // TODO more messages WARN current faction most importantly - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this)); - } else if (currentFaction.hasLandInflation() && !FactionsPlugin.getInstance().getConfig().getBoolean("hcf.allow-overclaim", true)) { - // deny over claim when it normally would be allowed. - error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OVERCLAIM_DISABLED.toString()); - } else if (!Board.getInstance().isBorderLocation(flocation)) { - error = FactionsPlugin.getInstance().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(FactionsPlugin.getInstance().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) return; - - 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}", FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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(FactionsPlugin.getInstance(), () -> 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(); - - if (me == null) { - return false; - } - - 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) { + public boolean inVault = false; + protected HashMap commandCooldown = new HashMap<>(); + 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; + protected boolean notificationsEnabled = true; + protected boolean isAlt = false; + boolean inspectMode = false; + + public MemoryFPlayer() { + } + + public MemoryFPlayer(String id) { + this.id = id; + this.isAlt = false; + this.resetFactionData(false); + this.power = Conf.powerPlayerStarting; + this.lastPowerUpdateTime = System.currentTimeMillis(); + this.lastLoginTime = System.currentTimeMillis(); + this.mapAutoUpdating = false; + this.autoClaimFor = null; + this.notificationsEnabled = true; + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + this.loginPvpDisabled = Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0; + this.powerBoost = 0.0; + this.getKills(); + this.getDeaths(); + this.showScoreboard = FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-enabled", false); + 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.isAlt = other.isAlt; + 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.getKills(); + this.getDeaths(); + this.isAdminBypassing = other.isAdminBypassing; + this.notificationsEnabled = other.notificationsEnabled; + this.showScoreboard = FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.default-enabled", true); + this.mapHeight = Conf.mapHeight; + } + + public boolean isAlt() { + return isAlt; + } + + public void setAlt(boolean alt) { + this.isAlt = alt; + } + + 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 int getCooldown(String cmd) { + int seconds = 0; + if (this.getPlayer().isOp()) + return 0; + if (commandCooldown.containsKey(cmd)) + seconds = (int) ((this.commandCooldown.get(cmd) - System.currentTimeMillis()) / 1000); + return seconds; + } + + public void setCooldown(String cmd, long cooldown) { + if (this.getPlayer().isOp()) + return; + + this.commandCooldown.put(cmd, cooldown); + } + + public boolean isCooldownEnded(String cmd) { + if (this.getPlayer().isOp()) + return true; + if (!commandCooldown.containsKey(cmd)) + return true; + else return commandCooldown.containsKey(cmd) && commandCooldown.get(cmd) <= System.currentTimeMillis(); + } + + + public Faction getFaction() { + if (this.factionId == null) { + this.factionId = "0"; + } + return Factions.getInstance().getFactionById(this.factionId); + } + + public void setFaction(Faction faction, boolean alt) { + Faction oldFaction = this.getFaction(); + if (oldFaction != null) { + if (this.isAlt()) { + oldFaction.removeAltPlayer(this); + } + + oldFaction.removeFPlayer(this); + } + if (alt) { + faction.addAltPlayer(this); + } else { + faction.addFPlayer(this); + } + this.factionId = faction.getId(); + } + + @Override + public void setNotificationsEnabled(boolean enabled) { + this.notificationsEnabled = enabled; + } + + @Override + public boolean hasNotificationsEnabled() { + return this.notificationsEnabled; + } + + 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) { + if (this.role == role) { + return; + } + + FPlayerRoleChangeEvent event = new FPlayerRoleChangeEvent(getFaction(), this, role); + Bukkit.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.role = event.getTo(); + } + } + + 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; + FactionsPlugin.getInstance().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; + this.isAlt = false; + } + + 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.getScheduler().runTask(FactionsPlugin.getInstance(), () -> 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 = FactionsPlugin.getInstance().getConfig().getBoolean("scoreboard.also-send-chat", true); + } + if (showChat) { + this.sendMessage(FactionsPlugin.getInstance().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() && FactionsPlugin.getInstance().getConfig().contains("scoreboard.finfo") && FactionsPlugin.getInstance().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) { + FactionsPlugin.getInstance().log(TL.LEAVE_LEFT.format(this.getName(), myFaction.getTag())); + } + } + + myFaction.removeAnnouncements(this); + + if (this.isAlt()) { + myFaction.removeAltPlayer(this); + this.msg(TL.LEAVE_LEFT, this.describeTo(this, true), myFaction.describeTo(this)); + } + + this.resetFactionData(); + setFlying(false); + + 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(getPlayer(), myFaction.getId(), PlayerDisbandReason.LEAVE); + Bukkit.getPluginManager().callEvent(disbandEvent); + + Factions.getInstance().removeFaction(myFaction.getId()); + if (Conf.logFactionDisband) { + FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().getConfig().getInt("hcf.buffer-zone", 0); + int worldBuffer = FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0); + + if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(flocation)) { + // Checks for WorldGuard regions in the chunk attempting to be claimed + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PROTECTED.toString()); + } else if (flocation.isOutsideWorldBorder(FactionsPlugin.getInstance().getConfig().getInt("world-border.buffer", 0))) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); + } else if (Conf.useWorldConfigurationsAsWhitelist != Conf.worldsNoClaiming.contains(flocation.getWorldName())) { + error = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); + } else if (forFaction == currentFaction) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true)); + } else if (this.getRole().value < Role.MODERATOR.value) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_MUSTBE.toString(), Role.MODERATOR.getTranslation()); + } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_MEMBERS.toString(), Conf.claimsRequireMinFactionMembers); + } else if (currentFaction.isSafeZone()) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_SAFEZONE.toString()); + } else if (currentFaction.isWarZone()) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_WARZONE.toString()); + } else if (FactionsPlugin.getInstance().getConfig().getBoolean("hcf.allow-overclaim", true) && ownedLand >= forFaction.getPowerRounded()) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_POWER.toString()); + } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_LIMIT.toString()); + } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { + error = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_CONTIGIOUS.toString()); + } else { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_FACTIONCONTIGUOUS.toString()); + } + } else if (factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer)); + } else if (flocation.isOutsideWorldBorder(worldBuffer)) { + if (worldBuffer > 0) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer)); + } else { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); + } + } else if (currentFaction.isNormal()) { + if (myFaction.isPeaceful()) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this)); + } else if (currentFaction.isPeaceful()) { + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this)); + } else if (!currentFaction.hasLandInflation()) { + // TODO more messages WARN current faction most importantly + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this)); + } else if (currentFaction.hasLandInflation() && !FactionsPlugin.getInstance().getConfig().getBoolean("hcf.allow-overclaim", true)) { + // deny over claim when it normally would be allowed. + error = FactionsPlugin.getInstance().txt.parse(TL.CLAIM_OVERCLAIM_DISABLED.toString()); + } else if (!Board.getInstance().isBorderLocation(flocation)) { + error = FactionsPlugin.getInstance().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(FactionsPlugin.getInstance().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) return; + + 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}", FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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(FactionsPlugin.getInstance(), () -> 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(); + + if (me == null) { + return false; + } + + int radius = Conf.stealthFlyCheckRadius; + for (Entity e : me.getNearbyEntities(radius, 255, radius)) { + if (e == null) { continue; - } - FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); - if (efplayer == null) { - continue; - } - if (efplayer.isVanished()) continue; - if (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; - } + } + 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.isVanished()) continue; + if (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 canflyinWilderness() { + return getPlayer().hasPermission("factions.fly.wilderness"); + } - @Override - public Boolean canflyinWarzone() { - return getPlayer().hasPermission("factions.fly.warzone"); + @Override + public Boolean canflyinWarzone() { + return getPlayer().hasPermission("factions.fly.warzone"); - } + } - @Override - public Boolean canflyinSafezone() { - return getPlayer().hasPermission("factions.fly.safezone"); + @Override + public Boolean canflyinSafezone() { + return getPlayer().hasPermission("factions.fly.safezone"); - } + } - @Override - public Boolean canflyinEnemy() { - return getPlayer().hasPermission("factions.fly.enemy"); + @Override + public Boolean canflyinEnemy() { + return getPlayer().hasPermission("factions.fly.enemy"); - } + } - @Override - public Boolean canflyinAlly() { - return getPlayer().hasPermission("factions.fly.ally"); + @Override + public Boolean canflyinAlly() { + return getPlayer().hasPermission("factions.fly.ally"); - } + } - @Override - public Boolean canflyinTruce() { - return getPlayer().hasPermission("factions.fly.truce"); + @Override + public Boolean canflyinTruce() { + return getPlayer().hasPermission("factions.fly.truce"); - } + } - @Override - public Boolean canflyinNeutral() { - return getPlayer().hasPermission("factions.fly.neutral"); + @Override + public Boolean canflyinNeutral() { + return getPlayer().hasPermission("factions.fly.neutral"); - } + } - @Override - public boolean isInspectMode() { - return inspectMode; - } + @Override + public boolean isInspectMode() { + return inspectMode; + } - @Override - public void setInspectMode(boolean status) { - inspectMode = status; - } + @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(); + 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 (!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 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.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 (Conf.bankEnabled && Conf.bankFactionPaysLandCosts && this.hasFaction()) { + payee = this.getFaction(); + } else { + payee = this; + } - if (!Econ.hasAtLeast(payee, cost, TL.CLAIM_TOCLAIM.toString())) { - return false; - } - } + if (!Econ.hasAtLeast(payee, cost, TL.CLAIM_TOCLAIM.toString())) { + return false; + } + } - LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); - Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> Bukkit.getPluginManager().callEvent(claimEvent)); - if (claimEvent.isCancelled()) { - return false; - } + LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); + Bukkit.getScheduler().runTask(FactionsPlugin.getInstance(), () -> 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; - } + // 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 (mustPay && currentFaction.isNormal() && currentFaction.hasLandInflation()) { - // Give them money for over claiming. - Econ.modifyMoney(payee, Conf.econOverclaimRewardMultiplier, TL.CLAIM_TOOVERCLAIM.toString(), TL.CLAIM_FOROVERCLAIM.toString()); - } + // Was an over claim + if (mustPay && 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)); - } + // 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); + Board.getInstance().setFactionAt(forFaction, flocation); - if (Conf.logLandClaims) { - FactionsPlugin.getInstance().log(TL.CLAIM_CLAIMEDLOG.toString(), this.getName(), flocation.getCoordString(), forFaction.getTag()); - } + if (Conf.logLandClaims) { + FactionsPlugin.getInstance().log(TL.CLAIM_CLAIMEDLOG.toString(), this.getName(), flocation.getCoordString(), forFaction.getTag()); + } - return true; - } + return true; + } - @Override - public String getRolePrefix() { + @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; - } + 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; - } + return null; + } - @Override - public boolean hasMoney(int amt) { - Economy econ = FactionsPlugin.getInstance().getEcon(); - if (econ.getBalance(getPlayer()) >= amt) { - return true; - } else { - getPlayer().closeInventory(); - msg(TL.GENERIC_NOTENOUGHMONEY); - return false; - } - } + @Override + public boolean hasMoney(int amt) { + Economy econ = FactionsPlugin.getInstance().getEcon(); + if (econ.getBalance(getPlayer()) >= amt) { + return true; + } else { + getPlayer().closeInventory(); + msg(TL.GENERIC_NOTENOUGHMONEY); + return false; + } + } - public String commas(final double amount) { - final DecimalFormat formatter = new DecimalFormat("#,###.00"); - return formatter.format(amount); - } + public String commas(final double amount) { + final DecimalFormat formatter = new DecimalFormat("#,###.00"); + return formatter.format(amount); + } - @Override - public void takeMoney(int amt) { - if (hasMoney(amt)) { - Economy econ = FactionsPlugin.getInstance().getEcon(); - econ.withdrawPlayer(getPlayer(), amt); - sendMessage(TL.GENERIC_MONEYTAKE.toString().replace("{amount}", commas(amt))); - } - } + @Override + public void takeMoney(int amt) { + if (hasMoney(amt)) { + Economy econ = FactionsPlugin.getInstance().getEcon(); + econ.withdrawPlayer(getPlayer(), amt); + sendMessage(TL.GENERIC_MONEYTAKE.toString().replace("{amount}", commas(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 3999de39..ea596f87 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())) { - FactionsPlugin.getInstance().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())) { + FactionsPlugin.getInstance().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 58e51761..9b5beb48 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java @@ -35,1319 +35,1319 @@ 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 transient Set alts = new HashSet<>(); - protected Set invites = new HashSet<>(); - protected Set altinvites = 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; - private int strikes = 0; - private int points = 0; - private Map missions = new ConcurrentHashMap<>(); - private int wallCheckMinutes; - private int bufferCheckMinutes; - private Map checks; - private Map playerWallCheckCount; - private Map playerBufferCheckCount; - private boolean weeWoo; - - - // -------------------------------------------- // - // 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.missions = new ConcurrentHashMap<>(); - this.foundedDate = System.currentTimeMillis(); - this.maxVaults = Conf.defaultMaxVaults; - this.defaultRole = Role.RECRUIT; - this.wallCheckMinutes = 0; - this.bufferCheckMinutes = 0; - this.weeWoo = false; - this.checks = new ConcurrentHashMap<>(); - this.playerWallCheckCount = new ConcurrentHashMap<>(); - this.playerBufferCheckCount = new ConcurrentHashMap<>(); - 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; - missions = new ConcurrentHashMap<>(); - relationWish = old.relationWish; - claimOwnership = old.claimOwnership; - fplayers = new HashSet<>(); - alts = new HashSet<>(); - invites = old.invites; - announcements = old.announcements; - this.defaultRole = Role.NORMAL; - this.wallCheckMinutes = 0; - this.bufferCheckMinutes = 0; - this.weeWoo = false; - this.checks = new ConcurrentHashMap<>(); - this.playerWallCheckCount = new ConcurrentHashMap<>(); - this.playerBufferCheckCount = new ConcurrentHashMap<>(); - - resetPerms(); // Reset on new Faction so it has default values. - } - - public int getPoints() { - return points; - } - - public void setPoints(int points) { - this.points = points; - } - - public int getStrikes() { - return strikes; - } - - public void setStrikes(int strikes) { - this.strikes = strikes; - } - - 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 Set getAltInvites() { - return altinvites; - } - - public void deinviteAlt(FPlayer fplayer) { - altinvites.remove(fplayer.getId()); - } - - public void deinviteAllAlts() { - altinvites.clear(); - } - - 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 altInvite(FPlayer fplayer) { - this.altinvites.add(fplayer.getId()); - } - - public void deinvite(FPlayer fplayer) { - this.invites.remove(fplayer.getId()); - this.altinvites.remove(fplayer.getId()); - } - - public boolean altInvited(FPlayer fplayer) { - return this.altinvites.contains(fplayer.getId()); - } - - public boolean isInvited(FPlayer fplayer) { - return this.invites.contains(fplayer.getId()) || this.altinvites.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) { - bans.removeIf(banInfo -> banInfo.getBanned().equalsIgnoreCase(player.getId())); - } - - @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. - FactionsPlugin.getInstance().log("The faction " + this.getTag() + " (" + this.getId() + ") was disbanded by " + (disbanderIsConsole ? "console command" : fdisbander.getName()) + "."); - } - - if (Econ.shouldBeUsed() && !disbanderIsConsole) { - // Should we prevent to withdraw money if the faction was just created - if (Conf.econFactionStartingBalance != 0 && (System.currentTimeMillis() - this.foundedDate) <= (Conf.econDenyWithdrawWhenMinutesAgeLessThan * 6000)) { - msg("Your faction is too young to withdraw money like this"); - } else { - //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 - FactionsPlugin.getInstance().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(UpgradeType upgrade) { - if (upgrades.keySet().contains(upgrade.toString())) return upgrades.get(upgrade.toString()); - return 0; - } - - @Override - public Inventory getChestInventory() { - if (chest != null) return chest; - - int size = 9; - switch (getUpgrade(UpgradeType.CHEST)) { - case 1: - size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-1") * 9; - break; - case 2: - size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-2") * 9; - break; - case 3: - size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-3") * 9; - break; - } - chest = Bukkit.createInventory(null, size, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fchest.Inventory-Title"))); - return chest; - } - - - @Override - public void setChestSize(int chestSize) { - ItemStack[] contents = this.getChestInventory().getContents(); - chest = Bukkit.createInventory(null, chestSize, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().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(UpgradeType upgrade, int level) { - upgrades.put(upgrade.toString(), level); - } - - public int getWallCheckMinutes() { - return this.wallCheckMinutes; - } - - public void setWallCheckMinutes(final int wallCheckMinutes) { - this.wallCheckMinutes = wallCheckMinutes; - } - - public int getBufferCheckMinutes() { - return this.bufferCheckMinutes; - } - - public void setBufferCheckMinutes(final int bufferCheckMinutes) { - this.bufferCheckMinutes = bufferCheckMinutes; - } - - public Map getChecks() { - return this.checks; - } - - public Map getPlayerBufferCheckCount() { - return this.playerBufferCheckCount; - } - - public Map getPlayerWallCheckCount() { - return this.playerWallCheckCount; - } - - public boolean isWeeWoo() { - return this.weeWoo; - } - - public void setWeeWoo(final boolean weeWoo) { - this.weeWoo = weeWoo; - } - - 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 = FactionsPlugin.getInstance().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 boolean setPermission(Permissable permissable, PermissableAction permissableAction, Access access) { - if (Conf.useLockedPermissions && Conf.lockedPermissions.contains(permissableAction)) return false; - Map accessMap = permissions.get(permissable); - if (accessMap == null) accessMap = new HashMap<>(); - accessMap.put(permissableAction, access); - return true; - } - - public void resetPerms() { - FactionsPlugin.getInstance().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() { - Map defaultMap = new HashMap<>(); - for (PermissableAction action : PermissableAction.values()) defaultMap.put(action, Access.UNDEFINED); - - for (Relation rel : Relation.values()) { - if (rel != Relation.MEMBER) { - if (Conf.defaultFactionPermissions.containsKey(rel.nicename.toUpperCase())) { + 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 transient Set alts = new HashSet<>(); + protected Set invites = new HashSet<>(); + protected Set altinvites = 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; + private int strikes = 0; + private int points = 0; + private Map missions = new ConcurrentHashMap<>(); + private int wallCheckMinutes; + private int bufferCheckMinutes; + private Map checks; + private Map playerWallCheckCount; + private Map playerBufferCheckCount; + private boolean weeWoo; + + + // -------------------------------------------- // + // 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.missions = new ConcurrentHashMap<>(); + this.foundedDate = System.currentTimeMillis(); + this.maxVaults = Conf.defaultMaxVaults; + this.defaultRole = Role.RECRUIT; + this.wallCheckMinutes = 0; + this.bufferCheckMinutes = 0; + this.weeWoo = false; + this.checks = new ConcurrentHashMap<>(); + this.playerWallCheckCount = new ConcurrentHashMap<>(); + this.playerBufferCheckCount = new ConcurrentHashMap<>(); + 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; + missions = new ConcurrentHashMap<>(); + relationWish = old.relationWish; + claimOwnership = old.claimOwnership; + fplayers = new HashSet<>(); + alts = new HashSet<>(); + invites = old.invites; + announcements = old.announcements; + this.defaultRole = Role.NORMAL; + this.wallCheckMinutes = 0; + this.bufferCheckMinutes = 0; + this.weeWoo = false; + this.checks = new ConcurrentHashMap<>(); + this.playerWallCheckCount = new ConcurrentHashMap<>(); + this.playerBufferCheckCount = new ConcurrentHashMap<>(); + + resetPerms(); // Reset on new Faction so it has default values. + } + + public int getPoints() { + return points; + } + + public void setPoints(int points) { + this.points = points; + } + + public int getStrikes() { + return strikes; + } + + public void setStrikes(int strikes) { + this.strikes = strikes; + } + + 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 Set getAltInvites() { + return altinvites; + } + + public void deinviteAlt(FPlayer fplayer) { + altinvites.remove(fplayer.getId()); + } + + public void deinviteAllAlts() { + altinvites.clear(); + } + + 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 altInvite(FPlayer fplayer) { + this.altinvites.add(fplayer.getId()); + } + + public void deinvite(FPlayer fplayer) { + this.invites.remove(fplayer.getId()); + this.altinvites.remove(fplayer.getId()); + } + + public boolean altInvited(FPlayer fplayer) { + return this.altinvites.contains(fplayer.getId()); + } + + public boolean isInvited(FPlayer fplayer) { + return this.invites.contains(fplayer.getId()) || this.altinvites.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) { + bans.removeIf(banInfo -> banInfo.getBanned().equalsIgnoreCase(player.getId())); + } + + @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. + FactionsPlugin.getInstance().log("The faction " + this.getTag() + " (" + this.getId() + ") was disbanded by " + (disbanderIsConsole ? "console command" : fdisbander.getName()) + "."); + } + + if (Econ.shouldBeUsed() && !disbanderIsConsole) { + // Should we prevent to withdraw money if the faction was just created + if (Conf.econFactionStartingBalance != 0 && (System.currentTimeMillis() - this.foundedDate) <= (Conf.econDenyWithdrawWhenMinutesAgeLessThan * 6000)) { + msg("Your faction is too young to withdraw money like this"); + } else { + //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 + FactionsPlugin.getInstance().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(UpgradeType upgrade) { + if (upgrades.keySet().contains(upgrade.toString())) return upgrades.get(upgrade.toString()); + return 0; + } + + @Override + public Inventory getChestInventory() { + if (chest != null) return chest; + + int size = 9; + switch (getUpgrade(UpgradeType.CHEST)) { + case 1: + size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-1") * 9; + break; + case 2: + size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-2") * 9; + break; + case 3: + size = FactionsPlugin.getInstance().getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-3") * 9; + break; + } + chest = Bukkit.createInventory(null, size, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().getConfig().getString("fchest.Inventory-Title"))); + return chest; + } + + + @Override + public void setChestSize(int chestSize) { + ItemStack[] contents = this.getChestInventory().getContents(); + chest = Bukkit.createInventory(null, chestSize, FactionsPlugin.getInstance().color(FactionsPlugin.getInstance().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(UpgradeType upgrade, int level) { + upgrades.put(upgrade.toString(), level); + } + + public int getWallCheckMinutes() { + return this.wallCheckMinutes; + } + + public void setWallCheckMinutes(final int wallCheckMinutes) { + this.wallCheckMinutes = wallCheckMinutes; + } + + public int getBufferCheckMinutes() { + return this.bufferCheckMinutes; + } + + public void setBufferCheckMinutes(final int bufferCheckMinutes) { + this.bufferCheckMinutes = bufferCheckMinutes; + } + + public Map getChecks() { + return this.checks; + } + + public Map getPlayerBufferCheckCount() { + return this.playerBufferCheckCount; + } + + public Map getPlayerWallCheckCount() { + return this.playerWallCheckCount; + } + + public boolean isWeeWoo() { + return this.weeWoo; + } + + public void setWeeWoo(final boolean weeWoo) { + this.weeWoo = weeWoo; + } + + 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 = FactionsPlugin.getInstance().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 boolean setPermission(Permissable permissable, PermissableAction permissableAction, Access access) { + if (Conf.useLockedPermissions && Conf.lockedPermissions.contains(permissableAction)) return false; + Map accessMap = permissions.get(permissable); + if (accessMap == null) accessMap = new HashMap<>(); + accessMap.put(permissableAction, access); + return true; + } + + public void resetPerms() { + FactionsPlugin.getInstance().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() { + Map defaultMap = new HashMap<>(); + for (PermissableAction action : PermissableAction.values()) defaultMap.put(action, Access.UNDEFINED); + + for (Relation rel : Relation.values()) { + if (rel != Relation.MEMBER) { + if (Conf.defaultFactionPermissions.containsKey(rel.nicename.toUpperCase())) { + permissions.put(rel, PermissableAction.fromDefaults(Conf.defaultFactionPermissions.get(rel.nicename.toUpperCase()))); + } else permissions.put(rel, new HashMap<>(defaultMap)); + } + } + + for (Role rel : Role.values()) { + if (Conf.defaultFactionPermissions.containsKey(rel.nicename.toUpperCase())) { permissions.put(rel, PermissableAction.fromDefaults(Conf.defaultFactionPermissions.get(rel.nicename.toUpperCase()))); - } else permissions.put(rel, new HashMap<>(defaultMap)); - } - } - - for (Role rel : Role.values()) { - if (Conf.defaultFactionPermissions.containsKey(rel.nicename.toUpperCase())) { - permissions.put(rel, PermissableAction.fromDefaults(Conf.defaultFactionPermissions.get(rel.nicename.toUpperCase()))); - } else permissions.put(rel, new HashMap<>(defaultMap)); - } - } - - /** - * 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 isSystemFaction() { - return this.isSafeZone() || this.isWarZone() || this.isWilderness(); - } - - 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(FactionsPlugin.getInstance().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(); - for (FPlayer fplayer : alts) 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(); - - for (FPlayer fplayer : alts) 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(); - alts.clear(); - if (this.isPlayerFreeType()) { - return; - } - - for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { - if (fplayer.getFactionId().equalsIgnoreCase(id)) { - if (fplayer.isAlt()) { - alts.add(fplayer); - } else { - 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 boolean addAltPlayer(FPlayer fplayer) { - return !this.isPlayerFreeType() && alts.add(fplayer); - } - - public boolean removeAltPlayer(FPlayer fplayer) { - return !this.isPlayerFreeType() && alts.remove(fplayer); - } - - public int getSize() { - return fplayers.size() + alts.size(); - } - - public Set getFPlayers() { - // return a shallow copy of the FPlayer list, to prevent tampering and - // concurrency issues - return new HashSet<>(fplayers); - } - - public Set getAltPlayers() { - // return a shallow copy of the FPlayer list, to prevent tampering and - // concurrency issues - return new HashSet<>(alts); - } - - public Set getFPlayersWhereOnline(boolean online) { - Set ret = new HashSet<>(); - - 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 : FactionsPlugin.getInstance().getServer().getOnlinePlayers()) { - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - if (fplayer.getFaction() == this && !fplayer.isAlt()) { - 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 : FactionsPlugin.getInstance().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) { + } else permissions.put(rel, new HashMap<>(defaultMap)); + } + } + + /** + * 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 isSystemFaction() { + return this.isSafeZone() || this.isWarZone() || this.isWilderness(); + } + + 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(FactionsPlugin.getInstance().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(); + for (FPlayer fplayer : alts) 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(); + + for (FPlayer fplayer : alts) 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(); + alts.clear(); + if (this.isPlayerFreeType()) { + return; + } + + for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { + if (fplayer.getFactionId().equalsIgnoreCase(id)) { + if (fplayer.isAlt()) { + alts.add(fplayer); + } else { + 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 boolean addAltPlayer(FPlayer fplayer) { + return !this.isPlayerFreeType() && alts.add(fplayer); + } + + public boolean removeAltPlayer(FPlayer fplayer) { + return !this.isPlayerFreeType() && alts.remove(fplayer); + } + + public int getSize() { + return fplayers.size() + alts.size(); + } + + public Set getFPlayers() { + // return a shallow copy of the FPlayer list, to prevent tampering and + // concurrency issues + return new HashSet<>(fplayers); + } + + public Set getAltPlayers() { + // return a shallow copy of the FPlayer list, to prevent tampering and + // concurrency issues + return new HashSet<>(alts); + } + + public Set getFPlayersWhereOnline(boolean online) { + Set ret = new HashSet<>(); + + 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 : FactionsPlugin.getInstance().getServer().getOnlinePlayers()) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (fplayer.getFaction() == this && !fplayer.isAlt()) { + 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 : FactionsPlugin.getInstance().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) { + FactionsPlugin.getInstance().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); - } - return; - } + } + 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()); + FactionsPlugin.getInstance().log("Faction " + this.getTag() + " (" + this.getId() + ") admin was removed. Replacement admin: " + replacements.get(0).getName()); + } + } - // no members left and faction isn't permanent, so disband it - if (Conf.logFactionDisband) { - FactionsPlugin.getInstance().log("The faction " + this.getTag() + " (" + this.getId() + ") has been disbanded since it has no members left" + (autoLeave ? " and by inactivity" : "") + "."); - } + // ----------------------------------------------// + // Messages + // ----------------------------------------------// + public void msg(String message, Object... args) { + message = FactionsPlugin.getInstance().txt.parse(message, args); - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - fplayer.msg("The faction %s was disbanded.", this.getTag(fplayer)); - } + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(message); + } + } - FactionDisbandEvent disbandEvent = new FactionDisbandEvent(null, getId(), autoLeave ? PlayerDisbandReason.INACTIVITY : PlayerDisbandReason.LEAVE); - Bukkit.getPluginManager().callEvent(disbandEvent); + public void msg(TL translation, Object... args) { + msg(translation.toString(), args); + } - 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()); - FactionsPlugin.getInstance().log("Faction " + this.getTag() + " (" + this.getId() + ") admin was removed. Replacement admin: " + replacements.get(0).getName()); - } - } + public void sendMessage(String message) { + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(message); + } + } - // ----------------------------------------------// - // Messages - // ----------------------------------------------// - public void msg(String message, Object... args) { - message = FactionsPlugin.getInstance().txt.parse(message, args); + public void sendMessage(List messages) { + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(messages); + } + } - for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { - fplayer.sendMessage(message); - } - } + // ----------------------------------------------// + // Ownership of specific claims + // ----------------------------------------------// - 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 Map> getClaimOwnership() { + return claimOwnership; + } - @Override - public Map getMissions() { - return this.missions; - } + @Override + public Map getMissions() { + return this.missions; + } - public void clearAllClaimOwnership() { - claimOwnership.clear(); - } + public void clearAllClaimOwnership() { + claimOwnership.clear(); + } - public void clearClaimOwnership(FLocation loc) { - claimOwnership.remove(loc); - } + public void clearClaimOwnership(FLocation loc) { + claimOwnership.remove(loc); + } - public void clearClaimOwnership(FPlayer player) { - if (id == null || id.isEmpty()) { - return; - } + public void clearClaimOwnership(FPlayer player) { + if (id == null || id.isEmpty()) { + return; + } - Set ownerData; + Set ownerData; - for (Entry> entry : claimOwnership.entrySet()) { - ownerData = entry.getValue(); + for (Entry> entry : claimOwnership.entrySet()) { + ownerData = entry.getValue(); - if (ownerData == null) { - continue; - } + if (ownerData == null) { + continue; + } - ownerData.removeIf(s -> s.equals(player.getId())); + ownerData.removeIf(s -> s.equals(player.getId())); - if (ownerData.isEmpty()) { - claimOwnership.remove(entry.getKey()); - } - } - } + if (ownerData.isEmpty()) { + claimOwnership.remove(entry.getKey()); + } + } + } - public int getCountOfClaimsWithOwners() { - return claimOwnership.isEmpty() ? 0 : claimOwnership.size(); - } + public int getCountOfClaimsWithOwners() { + return claimOwnership.isEmpty() ? 0 : claimOwnership.size(); + } - public boolean doesLocationHaveOwnersSet(FLocation loc) { - if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) { - return false; - } + public boolean doesLocationHaveOwnersSet(FLocation loc) { + if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) { + return false; + } - Set ownerData = claimOwnership.get(loc); - return ownerData != null && !ownerData.isEmpty(); - } + 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 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 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; + public void removePlayerAsOwner(FPlayer player, FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null) return; - ownerData.remove(player.getId()); - claimOwnership.put(loc, ownerData); - } + ownerData.remove(player.getId()); + claimOwnership.put(loc, ownerData); + } - public Set getOwnerList(FLocation loc) { - return claimOwnership.get(loc); - } + 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 ""; - } + public String getOwnerListString(FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null || ownerData.isEmpty()) { + return ""; + } - StringBuilder ownerList = new StringBuilder(); + 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(); - } + 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; + 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; + // make sure claimOwnership is initialized + if (claimOwnership.isEmpty()) return true; - // need to check the ownership list, then - Set ownerData = claimOwnership.get(loc); + // 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()); - } + // 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); - } + // ----------------------------------------------// + // Persistance and entity management + // ----------------------------------------------// + public void remove() { + if (Econ.shouldBeUsed()) { + Econ.setBalance(getAccountId(), 0); + } - // Clean the board - ((MemoryBoard) Board.getInstance()).clean(id); + // Clean the board + ((MemoryBoard) Board.getInstance()).clean(id); - for (FPlayer fPlayer : fplayers) { - fPlayer.resetFactionData(false); - } + for (FPlayer fPlayer : fplayers) { + fPlayer.resetFactionData(false); + } - for (FPlayer fPlayer : alts) { - fPlayer.resetFactionData(false); - } - } + for (FPlayer fPlayer : alts) { + fPlayer.resetFactionData(false); + } + } - public Set getAllClaims() { - return Board.getInstance().getAllClaims(this); - } + 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..fb575cbc 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..19780544 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 442514bc..cbc35f2d 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 = FactionsPlugin.getInstance().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(FactionsPlugin.getInstance()); - } + 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 = FactionsPlugin.getInstance().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(FactionsPlugin.getInstance()); + } } 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 b0baaf3e..d0982695 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(FactionsPlugin.getInstance().getDataFolder(), "board.json"); + private static transient File file = new File(FactionsPlugin.getInstance().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, FactionsPlugin.getInstance().gson.toJson(dumpAsSaveFormat()), sync); - } + public void forceSave(boolean sync) { + DiscUtil.writeCatch(file, FactionsPlugin.getInstance().gson.toJson(dumpAsSaveFormat()), sync); + } - public boolean load() { - FactionsPlugin.getInstance().log("Loading board from disk"); + public boolean load() { + FactionsPlugin.getInstance().log("Loading board from disk"); - if (!file.exists()) { - FactionsPlugin.getInstance().log("No board to load from disk. Creating new file."); - forceSave(); - return true; - } + if (!file.exists()) { + FactionsPlugin.getInstance().log("No board to load from disk. Creating new file."); + forceSave(); + return true; + } - try { - Type type = new TypeToken>>() { - }.getType(); - Map> worldCoordIds = FactionsPlugin.getInstance().gson.fromJson(DiscUtil.read(file), type); - loadFromSaveFormat(worldCoordIds); - FactionsPlugin.getInstance().log("Loaded " + flocationIds.size() + " board locations"); - } catch (Exception e) { - e.printStackTrace(); - FactionsPlugin.getInstance().log("Failed to load the board from disk."); - return false; - } + try { + Type type = new TypeToken>>() { + }.getType(); + Map> worldCoordIds = FactionsPlugin.getInstance().gson.fromJson(DiscUtil.read(file), type); + loadFromSaveFormat(worldCoordIds); + FactionsPlugin.getInstance().log("Loaded " + flocationIds.size() + " board locations"); + } catch (Exception e) { + e.printStackTrace(); + FactionsPlugin.getInstance().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..64db9e7e 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 677c062e..bde0ac27 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(FactionsPlugin.getInstance().getDataFolder(), "players.json"); - gson = FactionsPlugin.getInstance().gson; - } + public JSONFPlayers() { + file = new File(FactionsPlugin.getInstance().getDataFolder(), "players.json"); + gson = FactionsPlugin.getInstance().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); - FactionsPlugin.getInstance().log("Loaded " + fPlayers.size() + " players"); - } + public void load() { + Map fplayers = this.loadCore(); + if (fplayers == null) { + return; + } + this.fPlayers.clear(); + this.fPlayers.putAll(fplayers); + FactionsPlugin.getInstance().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); - } - } - } - - 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()); - - // 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); + 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); } - } - 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); + if (list.size() > 0) { + // We've got some converting to do! + Bukkit.getLogger().log(Level.INFO, "Factions is now updating players.json"); - if (player == null) { - // The player never existed here, and shouldn't persist - invalidList.add(value); - continue; + // 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(); - player.setId(id); // Update the object so it knows + JSONFPlayer player = data.get(value); - 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; - } + if (player == null) { + // The player never existed here, and shouldn't persist + invalidList.add(value); + continue; + } - 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; - } + player.setId(id); // Update the object so it knows - private boolean isKeyInvalid(String key) { - return !key.matches("[a-zA-Z0-9_]{2,16}"); - } + 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; + } - @Override - public FPlayer generateFPlayer(String id) { - FPlayer player = new JSONFPlayer(id); - this.fPlayers.put(player.getId(), player); - return player; - } + 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}"); + } + + @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 c5805ba0..ae3d9b7e 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,15 +4,15 @@ 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 a3bfe2a5..dfcdf8f8 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 @@ -21,233 +21,233 @@ 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; + // Info on how to persist + private final Gson gson; + private final File file; - public JSONFactions() { - this.file = new File(FactionsPlugin.getInstance().getDataFolder(), "factions.json"); - this.gson = FactionsPlugin.getInstance().gson; - this.nextId = 1; - } + public JSONFactions() { + this.file = new File(FactionsPlugin.getInstance().getDataFolder(), "factions.json"); + this.gson = FactionsPlugin.getInstance().gson; + this.nextId = 1; + } - public Gson getGson() { - return gson; - } + public Gson getGson() { + return gson; + } - // -------------------------------------------- // - // CONSTRUCTORS - // -------------------------------------------- // + // -------------------------------------------- // + // CONSTRUCTORS + // -------------------------------------------- // - public File getFile() { - return file; - } + public File getFile() { + return file; + } - public void forceSave() { - forceSave(true); - } + 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); - } + 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); - } + saveCore(file, entitiesThatShouldBeSaved, sync); + } - private boolean saveCore(File target, Map entities, boolean sync) { - return DiscUtil.writeCatch(target, this.gson.toJson(entities), 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); + public void load() { + Map factions = this.loadCore(); + if (factions == null) { + return; + } + this.factions.putAll(factions); - super.load(); - FactionsPlugin.getInstance().log("Loaded " + factions.size() + " Factions"); - } + super.load(); + FactionsPlugin.getInstance().log("Loaded " + factions.size() + " Factions"); + } - 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()); + Map data = this.gson.fromJson(content, new TypeToken>() { + }.getType()); - this.nextId = 1; - // Do we have any names that need updating in claims or invites? + 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(); - } - } + 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"); + 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()); + // 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."); + Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + needsUpdate + " old player names to UUID. This may take a while."); - // Update claim ownership + // 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); + 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); + 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(); - 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 + 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(); + } } - } - } + } - // Update invites + saveCore(this.file, data, true); // Update the flatfile + Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID."); + } + return data; + } - 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(); + 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; + } - saveCore(this.file, data, true); // Update the flatfile - Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID."); - } - return data; - } + // -------------------------------------------- // + // ID MANAGEMENT + // -------------------------------------------- // - 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; - } + public String getNextId() { + while (!isIdFree(this.nextId)) { + this.nextId += 1; + } + return Integer.toString(this.nextId); + } - // -------------------------------------------- // - // ID MANAGEMENT - // -------------------------------------------- // + public boolean isIdFree(String id) { + return !this.factions.containsKey(id); + } - public String getNextId() { - while (!isIdFree(this.nextId)) { - this.nextId += 1; - } - return Integer.toString(this.nextId); - } + public boolean isIdFree(int id) { + return this.isIdFree(Integer.toString(id)); + } - public boolean isIdFree(String id) { - return !this.factions.containsKey(id); - } + protected synchronized void updateNextIdForId(int id) { + if (this.nextId < id) { + this.nextId = id + 1; + } + } - public boolean isIdFree(int id) { - return this.isIdFree(Integer.toString(id)); - } + protected void updateNextIdForId(String id) { + try { + int idAsInt = Integer.parseInt(id); + this.updateNextIdForId(idAsInt); + } catch (Exception ignored) { + } + } - protected synchronized void updateNextIdForId(int id) { - if (this.nextId < id) { - this.nextId = id + 1; - } - } + @Override + public Faction generateFactionObject() { + String id = getNextId(); + Faction faction = new JSONFaction(id); + updateNextIdForId(id); + return faction; + } - protected void updateNextIdForId(String id) { - try { - int idAsInt = Integer.parseInt(id); - this.updateNextIdForId(idAsInt); - } catch (Exception ignored) { - } - } + @Override + public Faction generateFactionObject(String id) { + return new JSONFaction(id); + } - @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; - } + @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 ffb83178..0f2f374b 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java @@ -12,107 +12,107 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; public class DiscUtil { - // -------------------------------------------- // - // CONSTANTS - // -------------------------------------------- // + // -------------------------------------------- // + // CONSTANTS + // -------------------------------------------- // - private final static String UTF8 = "UTF-8"; + private final static String UTF8 = "UTF-8"; - // -------------------------------------------- // - // BYTE - // -------------------------------------------- // - private static HashMap locks = new HashMap<>(); + // -------------------------------------------- // + // 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; - } + 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 - // -------------------------------------------- // + // -------------------------------------------- // + // STRING + // -------------------------------------------- // - public static void writeBytes(File file, byte[] bytes) throws IOException { - FileOutputStream out = new FileOutputStream(file); - out.write(bytes); - out.close(); - } + 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)); - } + public static void write(File file, String content) throws IOException { + writeBytes(file, utf8(content)); + } - // -------------------------------------------- // - // CATCH - // -------------------------------------------- // + // -------------------------------------------- // + // CATCH + // -------------------------------------------- // - public static String read(File file) throws IOException { - return utf8(readBytes(file)); - } + 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; + 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); - } + // 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(FactionsPlugin.getInstance(), () -> { - lock.lock(); - try { + if (sync) { + lock.lock(); + try { write(file, content); - } catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); - } finally { + } finally { lock.unlock(); - } - }); - } + } + } else { + Bukkit.getScheduler().runTaskAsynchronously(FactionsPlugin.getInstance(), () -> { + 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. - } + 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; - } - } + public static String readCatch(File file) { + try { + return read(file); + } catch (IOException e) { + return null; + } + } - // -------------------------------------------- // - // UTF8 ENCODE AND DECODE - // -------------------------------------------- // + // -------------------------------------------- // + // UTF8 ENCODE AND DECODE + // -------------------------------------------- // - public static byte[] utf8(String string) { - return string.getBytes(StandardCharsets.UTF_8); - } + 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); - } + 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..4e05984a 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 7b637b47..59585a81 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), false); - } + public boolean save(Object instance, File file) { + return DiscUtil.writeCatch(file, p.gson.toJson(instance), false); + } - // 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 6451a699..072cc9a8 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java @@ -24,59 +24,59 @@ import java.util.Random; public class SmokeUtil { - public static Random random = new Random(); + public static Random random = new Random(); - // -------------------------------------------- // - // Spawn once - // -------------------------------------------- // + // -------------------------------------------- // + // Spawn once + // -------------------------------------------- // - // Single ======== - public static void spawnSingle(Location location, int direction) { - if (location == null) { - return; - } - location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); - } + // 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 spawnSingle(Location location) { + spawnSingle(location, 4); + } - public static void spawnSingleRandom(Location location) { - spawnSingle(location, random.nextInt(9)); - } + 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); - } - } + // 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); - } - } + 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()); - } - } + // 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); - } - } + public static void spawnCloudRandom(Collection locations, float thickness) { + for (Location location : locations) { + spawnCloudRandom(location, thickness); + } + } - // -------------------------------------------- // - // Attach continuous effects to or locations - // -------------------------------------------- // + // -------------------------------------------- // + // Attach continuous effects to or locations + // -------------------------------------------- // - // TODO + // 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 344894b5..3cbfb65b 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TL.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TL.java @@ -26,1185 +26,1185 @@ 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. - /** - * Actions translations - */ - ACTIONS_NOPERMISSION("{faction} does not allow you to {action}"), - ACTIONS_NOPERMISSIONPAIN("It is painful to try to {action} in the territory of {faction}"), - ACTIONS_OWNEDTERRITORYDENY("You cant do that in this territory, it is owned by {owners}"), - ACTIONS_OWNEDTERRITORYPAINDENY("It is painful to try to {action} in this territory, it is owned by {owners}"), - ACTIONS_MUSTBE("Youmust be {role} to {action}."), - ACTIONS_NOSAMEROLE("{role} can't control each other..."), - ACTIONS_NOFACTION("You are not member of any faction."), - /** - * Command translations - */ - COMMAND_USEAGE_TEMPLATE_COLOR("&c"), - - /** - * 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_CONTEXT_ADMINISTER_DIF_FACTION("&c[!] %1$s is not in the same faction as you."), - COMMAND_CONTEXT_ADMINISTER_ADMIN_REQUIRED("&c[!] Only the faction admin can do that."), - COMMAND_CONTEXT_ADMINISTER_SAME_RANK_CONTROL("&c[!] Moderators can't control each other..."), - COMMAND_CONTEXT_ADMINISTER_MOD_REQUIRED("&c[!] You must be a faction moderator to do that."), - - COMMAND_UPGRADES_DESCRIPTION("&cOpen the Upgrades Menu"), - COMMAND_CORNER_CANT_CLAIM("&c&l[!] &cYou may not claim this corner!"), - COMMAND_CORNER_CLAIMED("\n&2&l[!] &aYou have claimed the corner successfully, totalling in &b%1$d &achunks!\n"), - COMMAND_CORNER_ATTEMPTING_CLAIM("&c&l[!] &7Attempting to claim corner..."), - COMMAND_CORNER_NOT_CORNER("&c&l[!] &7You must be in a corner to use this command!"), - COMMAND_CORNER_DESCRIPTION("claim a corner at world border"), - COMMAND_CORNERLIST_DESCRIPTION("list of all corners"), - - 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_ALTS_DESCRIPTION("Faction Alts Commands"), - - COMMAND_ALTS_LIST_DESCRIPTION("List all alts in your 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_ALTINVITE_DESCRIPTION("Invite Alts to your faction."), - COMMAND_ALTKICK_DESCRIPTION("Kick alts from your faction"), - COMMAND_ALTKICK_NOTALT("&c&l[!] &7Player is not an alt."), - COMMAND_ALTKICK_NOTMEMBER("&c&l[!] &7This player is not a member of your faction."), - - COMMAND_ALTS_LIST_NOALTS("&c&l[!] &7%s does not have any alts in their faction!"), - COMMAND_AUTOHELP_HELPFOR("Help for command \""), - COMMAND_HOME_OTHER_NOTSET("&c&l[!] &7%s does not have their faction home set!"), - COMMAND_HOME_TELEPORT_OTHER("&c&l[!] &7You have teleported to %s's faction home!"), - COMMAND_SHOP_DESCRIPTION("opens shop gui"), - - 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"), - BANNER_CANNOT_BREAK("&c&l[!] &7You may not break a faction banner!"), - COMMAND_BANNER_NOBANNER("&c&l[!] &cPlease set a banner using /f setbanner"), - 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_CHECK_DESCRIPTION("manage your factions check system!"), - CHECK_BUFFERS_CHECK("\n &c&lFaction Walls&7 » &bCheck Your Buffers! \n"), - CHECK_WALLS_CHECK("\n &c&lFaction Walls&7 » &bCheck Your Walls! \n"), - CHECK_ALREADY_CHECKED("&c&lFaction Settings&7 » &bWalls have already been checked"), - CHECK_NO_CHECKS("&c&lFaction Walls&7 » &bNothing to Check!"), - CHECK_WALLS_MARKED_CHECKED("&c&lFaction Walls&7 » &aMarked walls as checked"), - CHECK_BUFFERS_MARKED_CHECKED("&c&lFaction Walls&7 » &aMarked buffers as checked"), - CHECK_HISTORY_GUI_TITLE("&aCheck History"), - CHECK_SETTINGS_GUI_TITLE("&a&lManage Check Settings"), - CHECK_WALL_CHECK_GUI_ICON("&a&lWall Check Settings"), - CHECK_BUFFER_CHECK_GUI_ICON("&a&lBuffer Check Settings"), - CHECK_CHECK_LORE_LINE("&bCheck: &a%1$s"), - CHECK_WALLS_CHECKED_GUI_ICON("&aWalls checked"), - CHECK_BUFFERS_CHECKED_GUI_ICON("&aBuffers checked"), - CHECK_WALLS_UNCHECKED_GUI_ICON("&cWalls unchecked"), - CHECK_BUFFERS_UNCHECKED_GUI_ICON("&cBuffers unchecked"), - CHECK_TIME_LORE_LINE("&bTime: &f%1$s"), - CHECK_PLAYER_LORE_LINE("&bPlayer: &f%1$s"), - CHECK_HISTORY_GUI_ICON("&bCheck history"), - CHECK_MUST_BE_ATLEAST_COLEADER("&cYou must be atleast &dCo Leader &cto access &fcheck settings"), - WEE_WOO_MESSAGE("&c&lFaction WeeWoo&7 » We Are Being Raided!"), - COMMAND_WEEWOO_STARTED("&c&lFaction WeeWoo&7 » &aWeewoo started by %1$s"), - COMMAND_WEEWOO_STOPPED("&c&lFaction WeeWoo&7 » &aWeewoo stopped by %1$s"), - COMMAND_WEEWOO_ALREADY_STARTED("&cWeewoo already started"), - COMMAND_WEEWOO_ALREADY_STOPPED("&cWeewoo already stopped"), - COMMAND_WEEWOO_DESCRIPTION("notifies all faction members you are being raided"), - CHECK_LEADERBOARD_HEADER("&8---- Check Leaderboard ----"), - CHECK_LEADERBOARD_LINE("&f%1$s. &d%2$s: &f%3$s (%4$s Buffer, %5$s Walls)"), - CHECK_LEADERBOARD_NO_DATA("&8No data"), - - 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_GRACE_DESCRIPTION("Toggles Grace Period on/off"), - COMMAND_GRACE_ENABLED("&cYou cannot place &e%s &cwhile grace period is active!"), - COMMAND_GRACE_TOGGLE("&8» &7Grace period is now &c%1$s"), - - 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_INVENTORYSEE_DESCRIPTION("View a faction members inventory"), - - 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_ALTINVITE_INVITED_ALT("&c&l[!]&7 &c%1$s&7 invited &c%2$s&7 to your faction as an alt."), - - 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."), - - BANKNOTE_WITHDRAW_NOT_ENOUGH("&c&l[!] &7You do not have enough money!"), - BANKNOTE_WITHDRAW_NO_ARGS("&c&l[!] &7Try /withdraw "), - XPBOTTLE_NOT_ENOUGH("&c&l[!] &7You do not have enough experience!"), - XPBOTTLE_WITHDRAW_NO_ARGS("&c&l[!] &7Try /bottle "), - - 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_SPAM_ENABLED("&c&l[!]&7 Factions Anti-Spam is now&a enabled"), - COMMAND_SPAM_DISABLED("&c&l[!]&7 Factions Anti-Spam in now&c disabled"), - COMMAND_SPAM_DESCRIPTION("enable antispam system"), - - 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_CONVERTCONFIG_DESCRIPTION("Convert your SavageFactions config to SaberFactions"), - COMMAND_CONVERTCONFIG_SUCCESS("&cConfiguration successfully converted"), - COMMAND_CONVERTCONFIG_FAIL("&cConfiguration conversion failed!"), - COMMAND_CONVERTCONFIG_FAILCONFIGMISSING("&cPlease ensure you have placed SavageFactions files in a folder called SavageFactions"), - - 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"), - - PAYPALSEE_PLAYER_PAYPAL("&c&l[!] &7You're factions paypal is: &b%1$s&7."), - COMMAND_PAYPAL_NOTSET("&c&l[!] &7Your faction does not have their paypal set!"), - COMMAND_PAYPALSET_ADMIN_SUCCESSFUL("&c&l[!] &7You have set &b%1$s's &7paypal to &b%2$s&7."), - COMMAND_PAYPALSET_ADMIN_FAILED("&c&l[!] &b%1$s &7is not an email!"), - COMMAND_PAYPALSET_NOTEMAIL("&c&l[!] &b%1$s &7is not an email!"), - 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_PERM_LOCKED("&cThis permission has been locked by the server"), - - COMMAND_POINTS_FAILURE("&c&l[!] &c{faction} does not exist."), - COMMAND_POINTS_SUCCESSFUL("&c&l[!] &7You have added &e%1$s &7points to &b%2$s&7. &b%2$s's &7New Point Balance: &e%3$s"), - COMMAND_POINTS_INSUFFICIENT("&c&l[!] &7You may not add/set/remove a negative number of points to a faction!"), - COMMAND_POINTS_DESCRIPTION("General Command For Faction Points"), - - COMMAND_ADDPOINTS_DESCRIPTION("Add Points to Faction"), - - - COMMAND_REMOVEPOINTS_SUCCESSFUL("&c&l[!] &7You have taken &e%1$s &7points from &b%2$s&7. &b%2$s's &7New Point Balance: &e%3$s"), - COMMAND_REMOVEPOINTS_DESCRIPTION("Remove Points from a Faction"), - - COMMAND_SETPOINTS_SUCCESSFUL("&c&l[!] &7You have set &e%1$s &7points to &b%2$s&7. &b%2$s's &7New Point Balance: &e%3$s"), - COMMAND_SETPOINTS_DESCRIPTION("Set Points of a Faction"), - - 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_ONCOOOLDOWN("&c&l[!] &7You cannot use this command for another &b%1$s &7seconds."), - - COMMAND_STRIKES_CHANGED("&c&l[!] &7You have set &c%1$s's &7strikes to &c%2$s"), - COMMAND_STRIKES_INFO("&c&l[!] &7%1$s has %2$s strikes"), - COMMAND_STRIKES_TARGET_INVALID("&c&l[!] &7The faction %1$s is invalid."), - COMMAND_STRIKES_STRUCK("&c&l[!] &7Your faction strikes have changed by &c%1$s &7strike(s)! Your faction now has &c%2$s/%3$s"), - COMMAND_STRIKES_DESCRIPTION("Set strikes on factions to warn them"), - COMMAND_STRIKESGIVE_DESCRIPTION("Give a faction 1 strike"), - COMMAND_STRIKETAKE_DESCRIPTION("Take a strike from a faction"), - COMMAND_STRIKESET_DESCRIPTION("Set a faction's strikes explicitly."), - COMMAND_STRIKESINFO_DESCRIPTION("Get a faction's strikes"), - - SHOP_NOT_ENOUGH_POINTS("&c&l[!] &7Your faction does not have enough points to purchase this!"), - SHOP_BOUGHT_BROADCAST_FACTION("\n&c&l[!] &e&lFactionShop » &b{player} &7bought &b{item}&7!\n"), - - - COMMAND_VIEWCHEST_DESCRIPTION("view a factions chest/pv"), - - 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_LOGOUT_KICK_MESSAGE("&2You have safely logged out!"), - COMMAND_LOGOUT_ACTIVE("&c&l[!] &7You are already logging out!"), - COMMAND_LOGOUT_LOGGING("&c&l[!] &7You are logging out. Please wait &b%1$s &7seconds."), - COMMAND_LOGOUT_DESCRIPTION("logout safely from the server"), - COMMAND_LOGOUT_MOVED("&c&l[!] &7Your logout was cancelled because you moved!"), - COMMAND_LOGOUT_DAMAGE_TAKEN("&c&l[!] &7Your logout was cancelled because you were damaged!"), - COMMAND_LOGOUT_TELEPORTED("&c&l[!] &7Your logout was cancelled because you teleported!"), - - COMMAND_NOTIFICATIONS_TOGGLED_ON("&c&l[!] &7You will now see claimed land notifications!"), - COMMAND_NOTIFICATIONS_TOGGLED_OFF("&c&l[!] &7You will no longer see claimed land notifications!"), - COMMAND_NOTIFICATIONS_DESCRIPTION("Toggle notifications for land claiming"), - - 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_ALTS_LIST_FORMAT("%1$s Power: %2$s Last Seen: %3$s"), - COMMAND_ALTS_DEINVITE_DESCRIPTION("Base command for revoking alt invitations"), - - 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_WIDTHDRAW_NOTENOUGH_TNT("&cNot enough tnt in bank."), - COMMAND_TNTFILL_NODISPENSERS("&c&l[!] &7No dispensers were found in a radius of {radius} blocks."), - 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_TARGET_IN_OTHER_FACTION("&c%1$s is not in your faction!"), - 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&4SaberFactions&7 &c&k|||&r &c» &7By Driftay"), - 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!"), - - // F Global \\ - COMMAND_F_GLOBAL_TOGGLE("&c&l[!] &7You have &b%1$s &7Global Chat"), - COMMAND_F_GLOBAL_DESCRIPTION("Toggle global chat and only allow factions based chats"), - - /** - * 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."), - GENERIC_FPERM_OWNER_NOPERMISSION("&7This land is ownerclaimed, you need to be an owner to %1$s it."), - GENERIC_NOFACTION_FOUND("&cCouldn't find a faction with that name!"), - GENERIC_YOUMUSTBE("&cYour must be atleast %1$s to do this!"), - GENERIC_MEMBERONLY("&cYou must be in a faction to do this!"), - - - MISSION_MISSION_STARTED("&f%1$s &dstarted the %2$s &fmission"), - MISSION_MISSION_ACTIVE("&c&l[!] &7This mission is currently active!"), - MISSION_MISSION_MAX_ALLOWED("&c&l[!] &7You may not have more then &b%1$s &7missions active at once."), - MISSION_MISSION_FINISHED("&c&l[!] &7Your faction has successfully completed %1$s mission!"), - COMMAND_MISSION_DESCRIPTION("Opens missions gui"), - // F Global \\ - - - PLAYER_NOT_FOUND("&c&l[!] &b%1$s &7is either not online or not in your faction!"), - PLACEHOLDER_ROLE_NAME("None"), - - - 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("###,###.###"), - ECON_DISABLED("Factions econ is disabled."), - ECON_OVER_BAL_CAP("&4The amount &e%s &4is over Essentials' balance cap."), - - /** - * 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("Co-Leader"), - 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[&ano-faction&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. + /** + * Actions translations + */ + ACTIONS_NOPERMISSION("{faction} does not allow you to {action}"), + ACTIONS_NOPERMISSIONPAIN("It is painful to try to {action} in the territory of {faction}"), + ACTIONS_OWNEDTERRITORYDENY("You cant do that in this territory, it is owned by {owners}"), + ACTIONS_OWNEDTERRITORYPAINDENY("It is painful to try to {action} in this territory, it is owned by {owners}"), + ACTIONS_MUSTBE("Youmust be {role} to {action}."), + ACTIONS_NOSAMEROLE("{role} can't control each other..."), + ACTIONS_NOFACTION("You are not member of any faction."), + /** + * Command translations + */ + COMMAND_USEAGE_TEMPLATE_COLOR("&c"), + + /** + * 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_CONTEXT_ADMINISTER_DIF_FACTION("&c[!] %1$s is not in the same faction as you."), + COMMAND_CONTEXT_ADMINISTER_ADMIN_REQUIRED("&c[!] Only the faction admin can do that."), + COMMAND_CONTEXT_ADMINISTER_SAME_RANK_CONTROL("&c[!] Moderators can't control each other..."), + COMMAND_CONTEXT_ADMINISTER_MOD_REQUIRED("&c[!] You must be a faction moderator to do that."), + + COMMAND_UPGRADES_DESCRIPTION("&cOpen the Upgrades Menu"), + COMMAND_CORNER_CANT_CLAIM("&c&l[!] &cYou may not claim this corner!"), + COMMAND_CORNER_CLAIMED("\n&2&l[!] &aYou have claimed the corner successfully, totalling in &b%1$d &achunks!\n"), + COMMAND_CORNER_ATTEMPTING_CLAIM("&c&l[!] &7Attempting to claim corner..."), + COMMAND_CORNER_NOT_CORNER("&c&l[!] &7You must be in a corner to use this command!"), + COMMAND_CORNER_DESCRIPTION("claim a corner at world border"), + COMMAND_CORNERLIST_DESCRIPTION("list of all corners"), + + 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_ALTS_DESCRIPTION("Faction Alts Commands"), + + COMMAND_ALTS_LIST_DESCRIPTION("List all alts in your 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_ALTINVITE_DESCRIPTION("Invite Alts to your faction."), + COMMAND_ALTKICK_DESCRIPTION("Kick alts from your faction"), + COMMAND_ALTKICK_NOTALT("&c&l[!] &7Player is not an alt."), + COMMAND_ALTKICK_NOTMEMBER("&c&l[!] &7This player is not a member of your faction."), + + COMMAND_ALTS_LIST_NOALTS("&c&l[!] &7%s does not have any alts in their faction!"), + COMMAND_AUTOHELP_HELPFOR("Help for command \""), + COMMAND_HOME_OTHER_NOTSET("&c&l[!] &7%s does not have their faction home set!"), + COMMAND_HOME_TELEPORT_OTHER("&c&l[!] &7You have teleported to %s's faction home!"), + COMMAND_SHOP_DESCRIPTION("opens shop gui"), + + 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"), + BANNER_CANNOT_BREAK("&c&l[!] &7You may not break a faction banner!"), + COMMAND_BANNER_NOBANNER("&c&l[!] &cPlease set a banner using /f setbanner"), + 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_CHECK_DESCRIPTION("manage your factions check system!"), + CHECK_BUFFERS_CHECK("\n &c&lFaction Walls&7 » &bCheck Your Buffers! \n"), + CHECK_WALLS_CHECK("\n &c&lFaction Walls&7 » &bCheck Your Walls! \n"), + CHECK_ALREADY_CHECKED("&c&lFaction Settings&7 » &bWalls have already been checked"), + CHECK_NO_CHECKS("&c&lFaction Walls&7 » &bNothing to Check!"), + CHECK_WALLS_MARKED_CHECKED("&c&lFaction Walls&7 » &aMarked walls as checked"), + CHECK_BUFFERS_MARKED_CHECKED("&c&lFaction Walls&7 » &aMarked buffers as checked"), + CHECK_HISTORY_GUI_TITLE("&aCheck History"), + CHECK_SETTINGS_GUI_TITLE("&a&lManage Check Settings"), + CHECK_WALL_CHECK_GUI_ICON("&a&lWall Check Settings"), + CHECK_BUFFER_CHECK_GUI_ICON("&a&lBuffer Check Settings"), + CHECK_CHECK_LORE_LINE("&bCheck: &a%1$s"), + CHECK_WALLS_CHECKED_GUI_ICON("&aWalls checked"), + CHECK_BUFFERS_CHECKED_GUI_ICON("&aBuffers checked"), + CHECK_WALLS_UNCHECKED_GUI_ICON("&cWalls unchecked"), + CHECK_BUFFERS_UNCHECKED_GUI_ICON("&cBuffers unchecked"), + CHECK_TIME_LORE_LINE("&bTime: &f%1$s"), + CHECK_PLAYER_LORE_LINE("&bPlayer: &f%1$s"), + CHECK_HISTORY_GUI_ICON("&bCheck history"), + CHECK_MUST_BE_ATLEAST_COLEADER("&cYou must be atleast &dCo Leader &cto access &fcheck settings"), + WEE_WOO_MESSAGE("&c&lFaction WeeWoo&7 » We Are Being Raided!"), + COMMAND_WEEWOO_STARTED("&c&lFaction WeeWoo&7 » &aWeewoo started by %1$s"), + COMMAND_WEEWOO_STOPPED("&c&lFaction WeeWoo&7 » &aWeewoo stopped by %1$s"), + COMMAND_WEEWOO_ALREADY_STARTED("&cWeewoo already started"), + COMMAND_WEEWOO_ALREADY_STOPPED("&cWeewoo already stopped"), + COMMAND_WEEWOO_DESCRIPTION("notifies all faction members you are being raided"), + CHECK_LEADERBOARD_HEADER("&8---- Check Leaderboard ----"), + CHECK_LEADERBOARD_LINE("&f%1$s. &d%2$s: &f%3$s (%4$s Buffer, %5$s Walls)"), + CHECK_LEADERBOARD_NO_DATA("&8No data"), + + 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_GRACE_DESCRIPTION("Toggles Grace Period on/off"), + COMMAND_GRACE_ENABLED("&cYou cannot place &e%s &cwhile grace period is active!"), + COMMAND_GRACE_TOGGLE("&8» &7Grace period is now &c%1$s"), + + 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_INVENTORYSEE_DESCRIPTION("View a faction members inventory"), + + 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_ALTINVITE_INVITED_ALT("&c&l[!]&7 &c%1$s&7 invited &c%2$s&7 to your faction as an alt."), + + 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."), + + BANKNOTE_WITHDRAW_NOT_ENOUGH("&c&l[!] &7You do not have enough money!"), + BANKNOTE_WITHDRAW_NO_ARGS("&c&l[!] &7Try /withdraw "), + XPBOTTLE_NOT_ENOUGH("&c&l[!] &7You do not have enough experience!"), + XPBOTTLE_WITHDRAW_NO_ARGS("&c&l[!] &7Try /bottle "), + + 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_SPAM_ENABLED("&c&l[!]&7 Factions Anti-Spam is now&a enabled"), + COMMAND_SPAM_DISABLED("&c&l[!]&7 Factions Anti-Spam in now&c disabled"), + COMMAND_SPAM_DESCRIPTION("enable antispam system"), + + 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_CONVERTCONFIG_DESCRIPTION("Convert your SavageFactions config to SaberFactions"), + COMMAND_CONVERTCONFIG_SUCCESS("&cConfiguration successfully converted"), + COMMAND_CONVERTCONFIG_FAIL("&cConfiguration conversion failed!"), + COMMAND_CONVERTCONFIG_FAILCONFIGMISSING("&cPlease ensure you have placed SavageFactions files in a folder called SavageFactions"), + + 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"), + + PAYPALSEE_PLAYER_PAYPAL("&c&l[!] &7You're factions paypal is: &b%1$s&7."), + COMMAND_PAYPAL_NOTSET("&c&l[!] &7Your faction does not have their paypal set!"), + COMMAND_PAYPALSET_ADMIN_SUCCESSFUL("&c&l[!] &7You have set &b%1$s's &7paypal to &b%2$s&7."), + COMMAND_PAYPALSET_ADMIN_FAILED("&c&l[!] &b%1$s &7is not an email!"), + COMMAND_PAYPALSET_NOTEMAIL("&c&l[!] &b%1$s &7is not an email!"), + 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_PERM_LOCKED("&cThis permission has been locked by the server"), + + COMMAND_POINTS_FAILURE("&c&l[!] &c{faction} does not exist."), + COMMAND_POINTS_SUCCESSFUL("&c&l[!] &7You have added &e%1$s &7points to &b%2$s&7. &b%2$s's &7New Point Balance: &e%3$s"), + COMMAND_POINTS_INSUFFICIENT("&c&l[!] &7You may not add/set/remove a negative number of points to a faction!"), + COMMAND_POINTS_DESCRIPTION("General Command For Faction Points"), + + COMMAND_ADDPOINTS_DESCRIPTION("Add Points to Faction"), + + + COMMAND_REMOVEPOINTS_SUCCESSFUL("&c&l[!] &7You have taken &e%1$s &7points from &b%2$s&7. &b%2$s's &7New Point Balance: &e%3$s"), + COMMAND_REMOVEPOINTS_DESCRIPTION("Remove Points from a Faction"), + + COMMAND_SETPOINTS_SUCCESSFUL("&c&l[!] &7You have set &e%1$s &7points to &b%2$s&7. &b%2$s's &7New Point Balance: &e%3$s"), + COMMAND_SETPOINTS_DESCRIPTION("Set Points of a Faction"), + + 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_ONCOOOLDOWN("&c&l[!] &7You cannot use this command for another &b%1$s &7seconds."), + + COMMAND_STRIKES_CHANGED("&c&l[!] &7You have set &c%1$s's &7strikes to &c%2$s"), + COMMAND_STRIKES_INFO("&c&l[!] &7%1$s has %2$s strikes"), + COMMAND_STRIKES_TARGET_INVALID("&c&l[!] &7The faction %1$s is invalid."), + COMMAND_STRIKES_STRUCK("&c&l[!] &7Your faction strikes have changed by &c%1$s &7strike(s)! Your faction now has &c%2$s/%3$s"), + COMMAND_STRIKES_DESCRIPTION("Set strikes on factions to warn them"), + COMMAND_STRIKESGIVE_DESCRIPTION("Give a faction 1 strike"), + COMMAND_STRIKETAKE_DESCRIPTION("Take a strike from a faction"), + COMMAND_STRIKESET_DESCRIPTION("Set a faction's strikes explicitly."), + COMMAND_STRIKESINFO_DESCRIPTION("Get a faction's strikes"), + + SHOP_NOT_ENOUGH_POINTS("&c&l[!] &7Your faction does not have enough points to purchase this!"), + SHOP_BOUGHT_BROADCAST_FACTION("\n&c&l[!] &e&lFactionShop » &b{player} &7bought &b{item}&7!\n"), + + + COMMAND_VIEWCHEST_DESCRIPTION("view a factions chest/pv"), + + 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_LOGOUT_KICK_MESSAGE("&2You have safely logged out!"), + COMMAND_LOGOUT_ACTIVE("&c&l[!] &7You are already logging out!"), + COMMAND_LOGOUT_LOGGING("&c&l[!] &7You are logging out. Please wait &b%1$s &7seconds."), + COMMAND_LOGOUT_DESCRIPTION("logout safely from the server"), + COMMAND_LOGOUT_MOVED("&c&l[!] &7Your logout was cancelled because you moved!"), + COMMAND_LOGOUT_DAMAGE_TAKEN("&c&l[!] &7Your logout was cancelled because you were damaged!"), + COMMAND_LOGOUT_TELEPORTED("&c&l[!] &7Your logout was cancelled because you teleported!"), + + COMMAND_NOTIFICATIONS_TOGGLED_ON("&c&l[!] &7You will now see claimed land notifications!"), + COMMAND_NOTIFICATIONS_TOGGLED_OFF("&c&l[!] &7You will no longer see claimed land notifications!"), + COMMAND_NOTIFICATIONS_DESCRIPTION("Toggle notifications for land claiming"), + + 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_ALTS_LIST_FORMAT("%1$s Power: %2$s Last Seen: %3$s"), + COMMAND_ALTS_DEINVITE_DESCRIPTION("Base command for revoking alt invitations"), + + 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_WIDTHDRAW_NOTENOUGH_TNT("&cNot enough tnt in bank."), + COMMAND_TNTFILL_NODISPENSERS("&c&l[!] &7No dispensers were found in a radius of {radius} blocks."), + 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_TARGET_IN_OTHER_FACTION("&c%1$s is not in your faction!"), + 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&4SaberFactions&7 &c&k|||&r &c» &7By Driftay"), + 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!"), + + // F Global \\ + COMMAND_F_GLOBAL_TOGGLE("&c&l[!] &7You have &b%1$s &7Global Chat"), + COMMAND_F_GLOBAL_DESCRIPTION("Toggle global chat and only allow factions based chats"), + + /** + * 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."), + GENERIC_FPERM_OWNER_NOPERMISSION("&7This land is ownerclaimed, you need to be an owner to %1$s it."), + GENERIC_NOFACTION_FOUND("&cCouldn't find a faction with that name!"), + GENERIC_YOUMUSTBE("&cYour must be atleast %1$s to do this!"), + GENERIC_MEMBERONLY("&cYou must be in a faction to do this!"), + + + MISSION_MISSION_STARTED("&f%1$s &dstarted the %2$s &fmission"), + MISSION_MISSION_ACTIVE("&c&l[!] &7This mission is currently active!"), + MISSION_MISSION_MAX_ALLOWED("&c&l[!] &7You may not have more then &b%1$s &7missions active at once."), + MISSION_MISSION_FINISHED("&c&l[!] &7Your faction has successfully completed %1$s mission!"), + COMMAND_MISSION_DESCRIPTION("Opens missions gui"), + // F Global \\ + + + PLAYER_NOT_FOUND("&c&l[!] &b%1$s &7is either not online or not in your faction!"), + PLACEHOLDER_ROLE_NAME("None"), + + + 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("###,###.###"), + ECON_DISABLED("Factions econ is disabled."), + ECON_OVER_BAL_CAP("&4The amount &e%s &4is over Essentials' balance cap."), + + /** + * 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("Co-Leader"), + 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[&ano-faction&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 72ee09c7..1d3c61d5 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java @@ -17,293 +17,293 @@ 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}"), - ALTS(TagType.FANCY, "{alts}"), + /** + * 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}"), + ALTS(TagType.FANCY, "{alts}"), - /** - * 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_STRIKES(TagType.FACTION, "{strikes}"), - FACTION_POINTS(TagType.FACTION, "{faction-points}"), + /** + * 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_STRIKES(TagType.FACTION, "{strikes}"), + FACTION_POINTS(TagType.FACTION, "{faction-points}"), - /** - * 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) { + /** + * 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); - } - } else if (tagReplacer.type.id >= type.id) { - tagReplacers.add(tagReplacer); - } - } - return tagReplacers; - } + } + } + 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(FPlayers.getInstance().getAllFPlayers().stream().filter(p -> !p.hasFaction()).count()); - case MAX_ALLIES: - if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-relations.ally", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_ENEMIES: - if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-relations.enemy", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_TRUCES: - if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-relations.truce", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_WARPS: - return String.valueOf(FactionsPlugin.getInstance().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(FPlayers.getInstance().getAllFPlayers().stream().filter(p -> !p.hasFaction()).count()); + case MAX_ALLIES: + if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-relations.ally", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_ENEMIES: + if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-relations.enemy", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_TRUCES: + if (FactionsPlugin.getInstance().getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(FactionsPlugin.getInstance().getConfig().getInt("max-relations.truce", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_WARPS: + return String.valueOf(FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().getConfig().getBoolean("minimal-show", false); + boolean minimal = FactionsPlugin.getInstance().getConfig().getBoolean("minimal-show", false); - if (fp != null) { - switch (this) { - case HEADER: - return FactionsPlugin.getInstance().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 FactionsPlugin.getInstance().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 FactionsPlugin.getInstance().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 FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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()); - case FACTION_STRIKES: - return String.valueOf(fac.getStrikes()); - case FACTION_POINTS: - return String.valueOf(fac.getPoints()); + 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 = FactionsPlugin.getInstance().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()); + case FACTION_STRIKES: + return String.valueOf(fac.getStrikes()); + case FACTION_POINTS: + return String.valueOf(fac.getPoints()); - default: - } - return null; - } + 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 != null && value != null) ? original.replace(tag, value) : original; + /** + * @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 != null && value != null) ? original.replace(tag, value) : original; - } + } - /** - * @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 bfa4e215..fe43df45 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java @@ -19,275 +19,275 @@ 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 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; - } - - public static String parsePlaceholders(Player player, String line) { - if (FactionsPlugin.getInstance().isClipPlaceholderAPIHooked() && player.isOnline()) { - line = PlaceholderAPI.setPlaceholders(player, line); - } - - if (FactionsPlugin.getInstance().isMVdWPlaceholderAPIHooked() && player.isOnline()) { - line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, 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; - } - - /** - * 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 = FactionsPlugin.getInstance().getConfig().getBoolean("minimal-show", false); - - switch (type) { - case ALLIES_LIST: - FancyMessage currentAllies = FactionsPlugin.getInstance().txt.parseFancy(prefix); - boolean firstAlly = true; - for (Faction otherFaction : Factions.getInstance().getAllFactions()) { - if (otherFaction == target) { - continue; + /** + * 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 } - 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 = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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 - case ALTS: - FancyMessage alts = FactionsPlugin.getInstance().txt.parseFancy(prefix); - boolean firstAlt = true; - for (FPlayer p : target.getAltPlayers()) { - String name = p.getName(); - ChatColor color; + line = tagReplacer.replace(line, rep); + } + } + return line; + } - if (p.isOnline()) { - color = ChatColor.GREEN; + /** + * 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 { - color = ChatColor.RED; + return null; // minimal show, entire line to be ignored } + } + } + return line; + } - alts.then(firstAlt ? name : ", " + name); - alts.tooltip(tipPlayer(p)).color(color); - firstAlt = false; - if (alts.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(alts); - currentOffline = new FancyMessage(""); + /** + * 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 (FactionsPlugin.getInstance().isClipPlaceholderAPIHooked() && player.isOnline()) { + line = PlaceholderAPI.setPlaceholders(player, line); + } + + if (FactionsPlugin.getInstance().isMVdWPlaceholderAPIHooked() && player.isOnline()) { + line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, 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; + } + + /** + * 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 = FactionsPlugin.getInstance().getConfig().getBoolean("minimal-show", false); + + switch (type) { + case ALLIES_LIST: + FancyMessage currentAllies = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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 = FactionsPlugin.getInstance().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 + case ALTS: + FancyMessage alts = FactionsPlugin.getInstance().txt.parseFancy(prefix); + boolean firstAlt = true; + for (FPlayer p : target.getAltPlayers()) { + String name = p.getName(); + ChatColor color; - } - fancyMessages.add(alts); - return firstAlt && minimal ? null : fancyMessages; - default: - break; - } - return null; - } + if (p.isOnline()) { + color = ChatColor.GREEN; + } else { + color = ChatColor.RED; + } - /** - * 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 : FactionsPlugin.getInstance().getConfig().getStringList("tooltips.list")) { - lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(faction, line))); - } - return lines; - } + alts.then(firstAlt ? name : ", " + name); + alts.tooltip(tipPlayer(p)).color(color); + firstAlt = false; + if (alts.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(alts); + currentOffline = new FancyMessage(""); + } - /** - * 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 : FactionsPlugin.getInstance().getConfig().getStringList("tooltips.show")) { - lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(fplayer, line))); - } - return lines; - } + } + fancyMessages.add(alts); + return firstAlt && minimal ? null : fancyMessages; + default: + break; + } + 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 : FactionsPlugin.getInstance().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 : FactionsPlugin.getInstance().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 6c4fe525..a981b601 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); + 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 { - message.then(text).style(color); + color = ChatColor.getByChar(chars[i + 1]); } - 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; - } + 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("`FactionsPlugin", 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("`FactionsPlugin", 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..a5bc9094 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; + } }