diff --git a/src/main/java/com/massivecraft/factions/Board.java b/src/main/java/com/massivecraft/factions/Board.java index 7665e940..bfd3622c 100644 --- a/src/main/java/com/massivecraft/factions/Board.java +++ b/src/main/java/com/massivecraft/factions/Board.java @@ -46,28 +46,23 @@ public class Board { } public static void removeAt(FLocation flocation) { - clearOwnershipAt(flocation); - flocationIds.remove(flocation); + clearOwnershipAt(flocation); flocationIds.remove(flocation); } // not to be confused with claims, ownership referring to further member-specific ownership of a claim public static void clearOwnershipAt(FLocation flocation) { - Faction faction = getFactionAt(flocation); - if (faction != null && faction.isNormal()) { + Faction faction = getFactionAt(flocation); if (faction != null && faction.isNormal()) { faction.clearClaimOwnership(flocation); } } public static void unclaimAll(String factionId) { - Faction faction = Factions.i.get(factionId); - if (faction != null && faction.isNormal()) { + Faction faction = Factions.i.get(factionId); if (faction != null && faction.isNormal()) { faction.clearAllClaimOwnership(); } - Iterator> iter = flocationIds.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (entry.getValue().equals(factionId)) { + Iterator> iter = flocationIds.entrySet().iterator(); while (iter.hasNext()) { + Entry entry = iter.next(); if (entry.getValue().equals(factionId)) { iter.remove(); } } @@ -76,20 +71,16 @@ public class Board { // 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 static 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); + 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 static 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); + 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); } @@ -99,12 +90,9 @@ public class Board { //----------------------------------------------// public static void clean() { - Iterator> iter = flocationIds.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (!Factions.i.exists(entry.getValue())) { - P.p.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); - iter.remove(); + Iterator> iter = flocationIds.entrySet().iterator(); while (iter.hasNext()) { + Entry entry = iter.next(); if (!Factions.i.exists(entry.getValue())) { + P.p.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); iter.remove(); } } } @@ -114,13 +102,11 @@ public class Board { //----------------------------------------------// public static int getFactionCoordCount(String factionId) { - int ret = 0; - for (String thatFactionId : flocationIds.values()) { + int ret = 0; for (String thatFactionId : flocationIds.values()) { if (thatFactionId.equals(factionId)) { ret += 1; } - } - return ret; + } return ret; } public static int getFactionCoordCount(Faction faction) { @@ -128,16 +114,13 @@ public class Board { } public static int getFactionCoordCountInWorld(Faction faction, String worldName) { - String factionId = faction.getId(); - int ret = 0; - Iterator> iter = flocationIds.entrySet().iterator(); - while (iter.hasNext()) { + String factionId = faction.getId(); int ret = 0; + Iterator> iter = flocationIds.entrySet().iterator(); while (iter.hasNext()) { Entry entry = iter.next(); if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) { ret += 1; } - } - return ret; + } return ret; } //----------------------------------------------// @@ -149,68 +132,47 @@ public class Board { * of decreasing z */ public static ArrayList getMap(Faction faction, FLocation flocation, double inDegrees) { - ArrayList ret = new ArrayList(); - Faction factionLoc = getFactionAt(flocation); + ArrayList ret = new ArrayList(); Faction factionLoc = getFactionAt(flocation); ret.add(P.p.txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(faction))); - int halfWidth = Conf.mapWidth / 2; - int halfHeight = Conf.mapHeight / 2; - FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); - int width = halfWidth * 2 + 1; + int halfWidth = Conf.mapWidth / 2; int halfHeight = Conf.mapHeight / 2; + FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); int width = halfWidth * 2 + 1; int height = halfHeight * 2 + 1; 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 - String row = ""; - for (int dx = 0; dx < width; dx++) { + String row = ""; for (int dx = 0; dx < width; dx++) { if (dx == halfWidth && dz == halfHeight) { row += ChatColor.AQUA + "+"; - } - else { + } else { FLocation flocationHere = topLeft.getRelative(dx, dz); Faction factionHere = getFactionAt(flocationHere); - Relation relation = faction.getRelationTo(factionHere); - if (factionHere.isNone()) { + Relation relation = faction.getRelationTo(factionHere); if (factionHere.isNone()) { row += ChatColor.GRAY + "-"; - } - else if (factionHere.isSafeZone()) { + } else if (factionHere.isSafeZone()) { row += Conf.colorPeaceful + "+"; - } - else if (factionHere.isWarZone()) { + } else if (factionHere.isWarZone()) { row += ChatColor.DARK_RED + "+"; - } - else if - ( - factionHere == faction - || - factionHere == factionLoc - || - relation.isAtLeast(Relation.ALLY) - || - (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) - || - (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) - ) { + } else if (factionHere == faction || + factionHere == factionLoc || + relation.isAtLeast(Relation.ALLY) || + (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) || + (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY))) { if (!fList.containsKey(factionHere.getTag())) { fList.put(factionHere.getTag(), Conf.mapKeyChrs[chrIdx++]); - } - char tag = fList.get(factionHere.getTag()); - row += factionHere.getColorTo(faction) + "" + tag; - } - else { + } char tag = fList.get(factionHere.getTag()); row += factionHere.getColorTo(faction) + "" + tag; + } else { row += ChatColor.GRAY + "-"; } } - } - ret.add(row); + } ret.add(row); } // Get the compass @@ -223,11 +185,9 @@ public class Board { // Add the faction key if (Conf.showMapFactionKey) { - String fRow = ""; - for (String key : fList.keySet()) { + String fRow = ""; for (String key : fList.keySet()) { fRow += String.format("%s%s: %s ", ChatColor.GRAY, fList.get(key), key); - } - ret.add(fRow); + } ret.add(fRow); } return ret; @@ -241,13 +201,10 @@ public class Board { public static 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(); + worldName = entry.getKey().getWorldName(); coords = entry.getKey().getCoordString(); id = entry.getValue(); if (!worldCoordIds.containsKey(worldName)) { worldCoordIds.put(worldName, new TreeMap()); } @@ -261,18 +218,12 @@ public class Board { public static 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(); + 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); } } @@ -284,9 +235,7 @@ public class Board { try { DiscUtil.write(file, P.p.gson.toJson(dumpAsSaveFormat())); } catch (Exception e) { - e.printStackTrace(); - P.p.log("Failed to save the board to disk."); - return false; + e.printStackTrace(); P.p.log("Failed to save the board to disk."); return false; } return true; @@ -296,20 +245,15 @@ public class Board { P.p.log("Loading board from disk"); if (!file.exists()) { - P.p.log("No board to load from disk. Creating new file."); - save(); - return true; + P.p.log("No board to load from disk. Creating new file."); save(); return true; } try { - Type type = new TypeToken>>() { - }.getType(); + Type type = new TypeToken>>() {}.getType(); Map> worldCoordIds = P.p.gson.fromJson(DiscUtil.read(file), type); loadFromSaveFormat(worldCoordIds); } catch (Exception e) { - e.printStackTrace(); - P.p.log("Failed to load the board from disk."); - return false; + e.printStackTrace(); P.p.log("Failed to load the board from disk."); return false; } return true; diff --git a/src/main/java/com/massivecraft/factions/Conf.java b/src/main/java/com/massivecraft/factions/Conf.java index 3c321f4d..d371cf8f 100644 --- a/src/main/java/com/massivecraft/factions/Conf.java +++ b/src/main/java/com/massivecraft/factions/Conf.java @@ -266,37 +266,24 @@ public class Conf { static { baseCommandAliases.add("f"); - territoryEnemyDenyCommands.add("home"); - territoryEnemyDenyCommands.add("sethome"); - territoryEnemyDenyCommands.add("spawn"); - territoryEnemyDenyCommands.add("tpahere"); - territoryEnemyDenyCommands.add("tpaccept"); - territoryEnemyDenyCommands.add("tpa"); + territoryEnemyDenyCommands.add("home"); territoryEnemyDenyCommands.add("sethome"); + territoryEnemyDenyCommands.add("spawn"); territoryEnemyDenyCommands.add("tpahere"); + territoryEnemyDenyCommands.add("tpaccept"); territoryEnemyDenyCommands.add("tpa"); - territoryProtectedMaterials.add(Material.WOODEN_DOOR); - territoryProtectedMaterials.add(Material.TRAP_DOOR); - territoryProtectedMaterials.add(Material.FENCE_GATE); - territoryProtectedMaterials.add(Material.DISPENSER); - territoryProtectedMaterials.add(Material.CHEST); - territoryProtectedMaterials.add(Material.FURNACE); + territoryProtectedMaterials.add(Material.WOODEN_DOOR); territoryProtectedMaterials.add(Material.TRAP_DOOR); + territoryProtectedMaterials.add(Material.FENCE_GATE); territoryProtectedMaterials.add(Material.DISPENSER); + territoryProtectedMaterials.add(Material.CHEST); territoryProtectedMaterials.add(Material.FURNACE); territoryProtectedMaterials.add(Material.BURNING_FURNACE); territoryProtectedMaterials.add(Material.DIODE_BLOCK_OFF); - territoryProtectedMaterials.add(Material.DIODE_BLOCK_ON); - territoryProtectedMaterials.add(Material.JUKEBOX); + territoryProtectedMaterials.add(Material.DIODE_BLOCK_ON); territoryProtectedMaterials.add(Material.JUKEBOX); territoryProtectedMaterials.add(Material.BREWING_STAND); - territoryProtectedMaterials.add(Material.ENCHANTMENT_TABLE); - territoryProtectedMaterials.add(Material.CAULDRON); - territoryProtectedMaterials.add(Material.SOIL); - territoryProtectedMaterials.add(Material.BEACON); - territoryProtectedMaterials.add(Material.ANVIL); - territoryProtectedMaterials.add(Material.TRAPPED_CHEST); - territoryProtectedMaterials.add(Material.DROPPER); - territoryProtectedMaterials.add(Material.HOPPER); + territoryProtectedMaterials.add(Material.ENCHANTMENT_TABLE); territoryProtectedMaterials.add(Material.CAULDRON); + territoryProtectedMaterials.add(Material.SOIL); territoryProtectedMaterials.add(Material.BEACON); + territoryProtectedMaterials.add(Material.ANVIL); territoryProtectedMaterials.add(Material.TRAPPED_CHEST); + territoryProtectedMaterials.add(Material.DROPPER); territoryProtectedMaterials.add(Material.HOPPER); - territoryDenyUseageMaterials.add(Material.FIREBALL); - territoryDenyUseageMaterials.add(Material.FLINT_AND_STEEL); - territoryDenyUseageMaterials.add(Material.BUCKET); - territoryDenyUseageMaterials.add(Material.WATER_BUCKET); + territoryDenyUseageMaterials.add(Material.FIREBALL); territoryDenyUseageMaterials.add(Material.FLINT_AND_STEEL); + territoryDenyUseageMaterials.add(Material.BUCKET); territoryDenyUseageMaterials.add(Material.WATER_BUCKET); territoryDenyUseageMaterials.add(Material.LAVA_BUCKET); territoryProtectedMaterialsWhenOffline.add(Material.WOODEN_DOOR); @@ -325,20 +312,13 @@ public class Conf { territoryDenyUseageMaterialsWhenOffline.add(Material.WATER_BUCKET); territoryDenyUseageMaterialsWhenOffline.add(Material.LAVA_BUCKET); - 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.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); } diff --git a/src/main/java/com/massivecraft/factions/FLocation.java b/src/main/java/com/massivecraft/factions/FLocation.java index a7cf44ce..2097e528 100644 --- a/src/main/java/com/massivecraft/factions/FLocation.java +++ b/src/main/java/com/massivecraft/factions/FLocation.java @@ -26,9 +26,7 @@ public class FLocation { } public FLocation(String worldName, int x, int z) { - this.worldName = worldName; - this.x = x; - this.z = z; + this.worldName = worldName; this.x = x; this.z = z; } public FLocation(Location location) { @@ -126,22 +124,17 @@ public class FLocation { } public double getDistanceTo(FLocation that) { - double dx = that.x - this.x; - double dz = that.z - this.z; - return Math.sqrt(dx * dx + dz * dz); + double dx = that.x - this.x; double dz = that.z - this.z; return Math.sqrt(dx * dx + dz * dz); } //----------------------------------------------// // Some Geometry //----------------------------------------------// public Set getCircle(double 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++) { @@ -177,8 +170,7 @@ public class FLocation { @Override public boolean equals(Object obj) { - if (obj == this) { return true; } - if (!(obj instanceof FLocation)) { return false; } + if (obj == this) { return true; } if (!(obj instanceof FLocation)) { return false; } FLocation that = (FLocation) obj; return this.x == that.x && this.z == that.z && (this.worldName == null ? that.worldName == null : this.worldName.equals(that.worldName)); diff --git a/src/main/java/com/massivecraft/factions/FPlayer.java b/src/main/java/com/massivecraft/factions/FPlayer.java index 62ed8445..4a8b957b 100644 --- a/src/main/java/com/massivecraft/factions/FPlayer.java +++ b/src/main/java/com/massivecraft/factions/FPlayer.java @@ -44,8 +44,7 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { public Faction getFaction() { if (this.factionId == null) { return null; - } - return Factions.i.get(this.factionId); + } return Factions.i.get(this.factionId); } public String getFactionId() { @@ -57,10 +56,8 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { } public void setFaction(Faction faction) { - Faction oldFaction = this.getFaction(); - if (oldFaction != null) { oldFaction.removeFPlayer(this); } - faction.addFPlayer(this); - this.factionId = faction.getId(); + Faction oldFaction = this.getFaction(); if (oldFaction != null) { oldFaction.removeFPlayer(this); } + faction.addFPlayer(this); this.factionId = faction.getId(); } // FIELD: role @@ -109,11 +106,9 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { } public void setAutoClaimFor(Faction faction) { - this.autoClaimFor = faction; - if (this.autoClaimFor != null) { + this.autoClaimFor = faction; if (this.autoClaimFor != null) { // TODO: merge these into same autoclaim - this.autoSafeZoneEnabled = false; - this.autoWarZoneEnabled = false; + this.autoSafeZoneEnabled = false; this.autoWarZoneEnabled = false; } } @@ -125,10 +120,8 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { } public void setIsAutoSafeClaimEnabled(boolean enabled) { - this.autoSafeZoneEnabled = enabled; - if (enabled) { - this.autoClaimFor = null; - this.autoWarZoneEnabled = false; + this.autoSafeZoneEnabled = enabled; if (enabled) { + this.autoClaimFor = null; this.autoWarZoneEnabled = false; } } @@ -140,10 +133,8 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { } public void setIsAutoWarClaimEnabled(boolean enabled) { - this.autoWarZoneEnabled = enabled; - if (enabled) { - this.autoClaimFor = null; - this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = enabled; if (enabled) { + this.autoClaimFor = null; this.autoSafeZoneEnabled = false; } } @@ -173,8 +164,7 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { public ChatMode getChatMode() { if (this.factionId.equals("0") || !Conf.factionOnlyChat) { this.chatMode = ChatMode.PUBLIC; - } - return chatMode; + } return chatMode; } // FIELD: chatSpy @@ -199,17 +189,12 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { // GSON need this noarg constructor. public FPlayer() { - this.resetFactionData(false); - this.power = Conf.powerPlayerStarting; - this.lastPowerUpdateTime = System.currentTimeMillis(); - this.lastLoginTime = System.currentTimeMillis(); - this.mapAutoUpdating = false; - this.autoClaimFor = null; - this.autoSafeZoneEnabled = false; + this.resetFactionData(false); this.power = Conf.powerPlayerStarting; + this.lastPowerUpdateTime = System.currentTimeMillis(); this.lastLoginTime = System.currentTimeMillis(); + this.mapAutoUpdating = false; this.autoClaimFor = null; this.autoSafeZoneEnabled = false; this.autoWarZoneEnabled = false; this.loginPvpDisabled = (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) ? true : false; - this.deleteMe = false; - this.powerBoost = 0.0; + this.deleteMe = false; this.powerBoost = 0.0; if (!Conf.newPlayerStartingFactionID.equals("0") && Factions.i.exists(Conf.newPlayerStartingFactionID)) { this.factionId = Conf.newPlayerStartingFactionID; @@ -219,18 +204,14 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { public final void resetFactionData(boolean doSpoutUpdate) { // clean up any territory ownership in old faction, if there is one if (Factions.i.exists(this.getFactionId())) { - Faction currentFaction = this.getFaction(); - currentFaction.removeFPlayer(this); + 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.chatMode = ChatMode.PUBLIC; this.role = Role.NORMAL; this.title = ""; this.autoClaimFor = null; } public void resetFactionData() { @@ -248,9 +229,7 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { public void setLastLoginTime(long lastLoginTime) { - losePowerFromBeingOffline(); - this.lastLoginTime = lastLoginTime; - this.lastPowerUpdateTime = lastLoginTime; + losePowerFromBeingOffline(); this.lastLoginTime = lastLoginTime; this.lastPowerUpdateTime = lastLoginTime; if (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) { this.loginPvpDisabled = true; } @@ -269,10 +248,8 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { return false; } if (this.lastLoginTime + (Conf.noPVPDamageToOthersForXSecondsAfterLogin * 1000) < System.currentTimeMillis()) { - this.loginPvpDisabled = false; - return false; - } - return true; + this.loginPvpDisabled = false; return false; + } return true; } public FLocation getLastStoodAt() { @@ -304,27 +281,22 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { public String getName() { if (isOnline()) { return getPlayer().getName(); - } - OfflinePlayer player = Bukkit.getOfflinePlayer(UUID.fromString(getId())); + } OfflinePlayer player = Bukkit.getOfflinePlayer(UUID.fromString(getId())); return player.getName() != null ? player.getName() : getId(); } public String getTag() { if (!this.hasFaction()) { return ""; - } - return this.getFaction().getTag(); + } return this.getFaction().getTag(); } // Base concatenations: public String getNameAndSomething(String something) { - String ret = this.role.getPrefix(); - if (something.length() > 0) { + String ret = this.role.getPrefix(); if (something.length() > 0) { ret += something + " "; - } - ret += this.getName(); - return ret; + } ret += this.getName(); return ret; } public String getNameAndTitle() { @@ -440,11 +412,9 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { // Health //----------------------------------------------// public void heal(int amnt) { - Player player = this.getPlayer(); - if (player == null) { + Player player = this.getPlayer(); if (player == null) { return; - } - player.setHealth(player.getHealth() + amnt); + } player.setHealth(player.getHealth() + amnt); } @@ -452,14 +422,13 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { // Power //----------------------------------------------// public double getPower() { - this.updatePower(); - return this.power; + this.updatePower(); return this.power; } protected 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(); } + 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() { @@ -484,41 +453,33 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { protected void updatePower() { if (this.isOffline()) { - losePowerFromBeingOffline(); - if (!Conf.powerRegenOffline) { + losePowerFromBeingOffline(); if (!Conf.powerRegenOffline) { return; } - } - long now = System.currentTimeMillis(); - long millisPassed = now - this.lastPowerUpdateTime; + } long now = System.currentTimeMillis(); long millisPassed = now - this.lastPowerUpdateTime; this.lastPowerUpdateTime = now; - Player thisPlayer = this.getPlayer(); - if (thisPlayer != null && thisPlayer.isDead()) { + Player thisPlayer = this.getPlayer(); if (thisPlayer != null && thisPlayer.isDead()) { return; // don't let dead players regain power until they respawn } - int millisPerMinute = 60 * 1000; - this.alterPower(millisPassed * Conf.powerPerMinute / millisPerMinute); + int millisPerMinute = 60 * 1000; this.alterPower(millisPassed * Conf.powerPerMinute / millisPerMinute); } protected void losePowerFromBeingOffline() { if (Conf.powerOfflineLossPerDay > 0.0 && this.power > Conf.powerOfflineLossLimit) { - long now = System.currentTimeMillis(); - long millisPassed = now - this.lastPowerUpdateTime; + 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); + } this.alterPower(-loss); } } public void onDeath() { - this.updatePower(); - this.alterPower(-Conf.powerPerDeath); + this.updatePower(); this.alterPower(-Conf.powerPerDeath); } //----------------------------------------------// @@ -550,8 +511,7 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { String msg = P.p.txt.parse("") + " ~ " + factionHere.getTag(this); if (factionHere.getDescription().length() > 0) { msg += " - " + factionHere.getDescription(); - } - this.sendMessage(msg); + } this.sendMessage(msg); } // ------------------------------- @@ -559,32 +519,27 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { // ------------------------------- public void leave(boolean makePay) { - Faction myFaction = this.getFaction(); - makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); + Faction myFaction = this.getFaction(); makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); if (myFaction == null) { - resetFactionData(); - return; + resetFactionData(); return; } boolean perm = myFaction.isPermanent(); if (!perm && this.getRole() == Role.ADMIN && myFaction.getFPlayers().size() > 1) { - msg("You must give the admin role to someone else first."); - return; + msg("You must give the admin role to someone else first."); return; } if (!Conf.canLeaveWithNegativePower && this.getPower() < 0) { - msg("You cannot leave until your power is positive."); - return; + msg("You cannot leave until your power is positive."); 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, "to leave your faction.")) { return; } FPlayerLeaveEvent leaveEvent = new FPlayerLeaveEvent(this, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.LEAVE); - Bukkit.getServer().getPluginManager().callEvent(leaveEvent); - if (leaveEvent.isCancelled()) { return; } + Bukkit.getServer().getPluginManager().callEvent(leaveEvent); if (leaveEvent.isCancelled()) { return; } // then make 'em pay (if applicable) if (makePay && !Econ.modifyMoney(this, -Conf.econCostLeave, "to leave your faction.", "for leaving your faction.")) { @@ -615,8 +570,7 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { fplayer.msg("%s was disbanded.", myFaction.describeTo(fplayer, true)); } - myFaction.detach(); - if (Conf.logFactionDisband) { + myFaction.detach(); if (Conf.logFactionDisband) { P.p.log("The faction " + myFaction.getTag() + " (" + myFaction.getId() + ") was disbanded due to the last player (" + this.getName() + ") leaving."); } } @@ -625,10 +579,7 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { public boolean canClaimForFaction(Faction forFaction) { if (forFaction.isNone()) { return false; } - if (this.isAdminBypassing() - || (forFaction == this.getFaction() && this.getRole().isAtLeast(Role.MODERATOR)) - || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) - || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer()))) { + if (this.isAdminBypassing() || (forFaction == this.getFaction() && this.getRole().isAtLeast(Role.MODERATOR)) || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer()))) { return true; } @@ -636,95 +587,67 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { } public boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure) { - String error = null; - FLocation flocation = new FLocation(location); - Faction myFaction = getFaction(); - Faction currentFaction = Board.getFactionAt(flocation); - int ownedLand = forFaction.getLandRounded(); + String error = null; FLocation flocation = new FLocation(location); Faction myFaction = getFaction(); + Faction currentFaction = Board.getFactionAt(flocation); int ownedLand = forFaction.getLandRounded(); if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(location)) { // Checks for WorldGuard regions in the chunk attempting to be claimed error = P.p.txt.parse("This land is protected"); - } - else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) { + } else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) { error = P.p.txt.parse("Sorry, this world has land claiming disabled."); - } - else if (this.isAdminBypassing()) { + } else if (this.isAdminBypassing()) { return true; - } - else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { + } else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { return true; - } - else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { + } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { return true; - } - else if (myFaction != forFaction) { + } else if (myFaction != forFaction) { error = P.p.txt.parse("You can't claim land for %s.", forFaction.describeTo(this)); - } - else if (forFaction == currentFaction) { + } else if (forFaction == currentFaction) { error = P.p.txt.parse("%s already own this land.", forFaction.describeTo(this, true)); - } - else if (this.getRole().value < Role.MODERATOR.value) { + } else if (this.getRole().value < Role.MODERATOR.value) { error = P.p.txt.parse("You must be %s to claim land.", Role.MODERATOR.toString()); - } - else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { + } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { error = P.p.txt.parse("Factions must have at least %s members to claim land.", Conf.claimsRequireMinFactionMembers); - } - else if (currentFaction.isSafeZone()) { + } else if (currentFaction.isSafeZone()) { error = P.p.txt.parse("You can not claim a Safe Zone."); - } - else if (currentFaction.isWarZone()) { + } else if (currentFaction.isWarZone()) { error = P.p.txt.parse("You can not claim a War Zone."); - } - else if (ownedLand >= forFaction.getPowerRounded()) { + } else if (ownedLand >= forFaction.getPowerRounded()) { error = P.p.txt.parse("You can't claim more land! You need more power!"); - } - else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { + } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { error = P.p.txt.parse("Limit reached. You can't claim more land!"); - } - else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { + } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { error = P.p.txt.parse("You can't claim the land of your allies."); - } - else if (Conf.claimsMustBeConnected - && !this.isAdminBypassing() - && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 - && !Board.isConnectedLocation(flocation, myFaction) - && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal())) { + } else if (Conf.claimsMustBeConnected && !this.isAdminBypassing() && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.isConnectedLocation(flocation, myFaction) && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal())) { if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) { error = P.p.txt.parse("You can only claim additional land which is connected to your first claim or controlled by another faction!"); - } - else { + } else { error = P.p.txt.parse("You can only claim additional land which is connected to your first claim!"); } - } - else if (currentFaction.isNormal()) { + } else if (currentFaction.isNormal()) { if (myFaction.isPeaceful()) { error = P.p.txt.parse("%s owns this land. Your faction is peaceful, so you cannot claim land from other factions.", currentFaction.getTag(this)); - } - else if (currentFaction.isPeaceful()) { + } else if (currentFaction.isPeaceful()) { error = P.p.txt.parse("%s owns this land, and is a peaceful faction. You cannot claim land from them.", currentFaction.getTag(this)); - } - else if (!currentFaction.hasLandInflation()) { + } else if (!currentFaction.hasLandInflation()) { // TODO more messages WARN current faction most importantly error = P.p.txt.parse("%s owns this land and is strong enough to keep it.", currentFaction.getTag(this)); - } - else if (!Board.isBorderLocation(flocation)) { + } else if (!Board.isBorderLocation(flocation)) { error = P.p.txt.parse("You must start claiming land at the border of the territory."); } } if (notifyFailure && error != null) { msg(error); - } - return error == null; + } return error == null; } public boolean attemptClaim(Faction forFaction, Location location, 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 - FLocation flocation = new FLocation(location); - Faction currentFaction = Board.getFactionAt(flocation); + FLocation flocation = new FLocation(location); Faction currentFaction = Board.getFactionAt(flocation); int ownedLand = forFaction.getLandRounded(); @@ -732,24 +655,22 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { // 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) { + 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.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, "to claim this land")) { return false; } } LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); - Bukkit.getServer().getPluginManager().callEvent(claimEvent); - if (claimEvent.isCancelled()) { return false; } + Bukkit.getServer().getPluginManager().callEvent(claimEvent); if (claimEvent.isCancelled()) { return false; } // then make 'em pay (if applicable) if (mustPay && !Econ.modifyMoney(payee, -cost, "to claim this land", "for claiming this land")) { @@ -757,10 +678,8 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { } // announce success - Set informTheseFPlayers = new HashSet(); - informTheseFPlayers.add(this); - informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); - for (FPlayer fp : informTheseFPlayers) { + Set informTheseFPlayers = new HashSet(); informTheseFPlayers.add(this); + informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); for (FPlayer fp : informTheseFPlayers) { fp.msg("%s claimed land for %s from %s.", this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); } @@ -781,8 +700,7 @@ public class FPlayer extends PlayerEntity implements EconomyParticipator { public boolean shouldBeSaved() { if (!this.hasFaction() && (this.getPowerRounded() == this.getPowerMaxRounded() || this.getPowerRounded() == (int) Math.round(Conf.powerPlayerStarting))) { return false; - } - return !this.deleteMe; + } return !this.deleteMe; } public void msg(String str, Object... args) { diff --git a/src/main/java/com/massivecraft/factions/FPlayers.java b/src/main/java/com/massivecraft/factions/FPlayers.java index a18456f0..919bf937 100644 --- a/src/main/java/com/massivecraft/factions/FPlayers.java +++ b/src/main/java/com/massivecraft/factions/FPlayers.java @@ -15,22 +15,14 @@ public class FPlayers extends PlayerEntityCollection { P p = P.p; private FPlayers() { - super - ( - FPlayer.class, - new CopyOnWriteArrayList(), - new ConcurrentSkipListMap(String.CASE_INSENSITIVE_ORDER), - new File(P.p.getDataFolder(), "players.json"), - P.p.gson - ); + super(FPlayer.class, new CopyOnWriteArrayList(), new ConcurrentSkipListMap(String.CASE_INSENSITIVE_ORDER), new File(P.p.getDataFolder(), "players.json"), P.p.gson); this.setCreative(true); } @Override public Type getMapType() { - return new TypeToken>() { - }.getType(); + return new TypeToken>() {}.getType(); } public void clean() { diff --git a/src/main/java/com/massivecraft/factions/Faction.java b/src/main/java/com/massivecraft/factions/Faction.java index 5f1fb0fc..e55464c1 100644 --- a/src/main/java/com/massivecraft/factions/Faction.java +++ b/src/main/java/com/massivecraft/factions/Faction.java @@ -115,22 +115,19 @@ public class Faction extends Entity implements EconomyParticipator { public String getTag(Faction otherFaction) { if (otherFaction == null) { return getTag(); - } - return this.getTag(this.getColorTo(otherFaction).toString()); + } return this.getTag(this.getColorTo(otherFaction).toString()); } public String getTag(FPlayer otherFplayer) { if (otherFplayer == null) { return getTag(); - } - return this.getTag(this.getColorTo(otherFplayer).toString()); + } return this.getTag(this.getColorTo(otherFplayer).toString()); } public void setTag(String str) { if (Conf.factionTagForceUpperCase) { str = str.toUpperCase(); - } - this.tag = str; + } this.tag = str; } public String getComparisonTag() { @@ -160,8 +157,7 @@ public class Faction extends Entity implements EconomyParticipator { } public Location getHome() { - confirmValidHome(); - return (this.home != null) ? this.home.getLocation() : null; + confirmValidHome(); return (this.home != null) ? this.home.getLocation() : null; } public void confirmValidHome() { @@ -169,8 +165,7 @@ public class Faction extends Entity implements EconomyParticipator { return; } - msg("Your faction home has been un-set since it is no longer in your territory."); - this.home = null; + msg("Your faction home has been un-set since it is no longer in your territory."); this.home = null; } // FIELD: lastPlayerLoggedOffTime @@ -222,17 +217,10 @@ public class Faction extends Entity implements EconomyParticipator { // -------------------------------------------- // public Faction() { - this.relationWish = new HashMap(); - this.invites = new HashSet(); - this.open = Conf.newFactionsDefaultOpen; - this.tag = "???"; - this.description = "Default faction description :("; - this.lastPlayerLoggedOffTime = 0; - this.peaceful = false; - this.peacefulExplosionsEnabled = false; - this.permanent = false; - this.money = 0.0; - this.powerBoost = 0.0; + this.relationWish = new HashMap(); this.invites = new HashSet(); + this.open = Conf.newFactionsDefaultOpen; this.tag = "???"; this.description = "Default faction description :("; + this.lastPlayerLoggedOffTime = 0; this.peaceful = false; this.peacefulExplosionsEnabled = false; + this.permanent = false; this.money = 0.0; this.powerBoost = 0.0; } // -------------------------------------------- // @@ -305,15 +293,13 @@ public class Faction extends Entity implements EconomyParticipator { public Relation getRelationWish(Faction otherFaction) { if (this.relationWish.containsKey(otherFaction.getId())) { return this.relationWish.get(otherFaction.getId()); - } - return Relation.NEUTRAL; + } return Relation.NEUTRAL; } public void setRelationWish(Faction otherFaction, Relation relation) { if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL)) { this.relationWish.remove(otherFaction.getId()); - } - else { + } else { this.relationWish.put(otherFaction.getId(), relation); } } @@ -326,14 +312,11 @@ public class Faction extends Entity implements EconomyParticipator { return this.getPermanentPower(); } - double ret = 0; - for (FPlayer fplayer : fplayers) { + double ret = 0; for (FPlayer fplayer : fplayers) { ret += fplayer.getPower(); - } - if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { + } if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { ret = Conf.powerFactionMax; - } - return ret + this.powerBoost; + } return ret + this.powerBoost; } public double getPowerMax() { @@ -341,14 +324,11 @@ public class Faction extends Entity implements EconomyParticipator { return this.getPermanentPower(); } - double ret = 0; - for (FPlayer fplayer : fplayers) { + double ret = 0; for (FPlayer fplayer : fplayers) { ret += fplayer.getPowerMax(); - } - if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { + } if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { ret = Conf.powerFactionMax; - } - return ret + this.powerBoost; + } return ret + this.powerBoost; } public int getPowerRounded() { @@ -377,8 +357,7 @@ public class Faction extends Entity implements EconomyParticipator { // maintain the reference list of FPlayers in this faction public void refreshFPlayers() { - fplayers.clear(); - if (this.isPlayerFreeType()) { return; } + fplayers.clear(); if (this.isPlayerFreeType()) { return; } for (FPlayer fplayer : FPlayers.i.get()) { if (fplayer.getFaction() == this) { @@ -401,8 +380,7 @@ public class Faction extends Entity implements EconomyParticipator { public Set getFPlayers() { // return a shallow copy of the FPlayer list, to prevent tampering and concurrency issues - Set ret = new HashSet(fplayers); - return ret; + Set ret = new HashSet(fplayers); return ret; } public Set getFPlayersWhereOnline(boolean online) { @@ -424,13 +402,11 @@ public class Faction extends Entity implements EconomyParticipator { if (fplayer.getRole() == Role.ADMIN) { return fplayer; } - } - return null; + } return null; } public ArrayList getFPlayersWhereRole(Role role) { - ArrayList ret = new ArrayList(); - if (!this.isNormal()) { return ret; } + ArrayList ret = new ArrayList(); if (!this.isNormal()) { return ret; } for (FPlayer fplayer : fplayers) { if (fplayer.getRole() == role) { @@ -442,12 +418,10 @@ public class Faction extends Entity implements EconomyParticipator { } public ArrayList getOnlinePlayers() { - ArrayList ret = new ArrayList(); - if (this.isPlayerFreeType()) { return ret; } + ArrayList ret = new ArrayList(); if (this.isPlayerFreeType()) { return ret; } for (Player player : P.p.getServer().getOnlinePlayers()) { - FPlayer fplayer = FPlayers.i.get(player); - if (fplayer.getFaction() == this) { + FPlayer fplayer = FPlayers.i.get(player); if (fplayer.getFaction() == this) { ret.add(player); } } @@ -461,8 +435,7 @@ public class Faction extends Entity implements EconomyParticipator { if (this.isPlayerFreeType()) { return false; } for (Player player : P.p.getServer().getOnlinePlayers()) { - FPlayer fplayer = FPlayers.i.get(player); - if (fplayer != null && fplayer.getFaction() == this) { + FPlayer fplayer = FPlayers.i.get(player); if (fplayer != null && fplayer.getFaction() == this) { return true; } } @@ -470,8 +443,7 @@ public class Faction extends Entity implements EconomyParticipator { // even if all players are technically logged off, maybe someone was on recently enough to not consider them officially offline yet if (Conf.considerFactionsReallyOfflineAfterXMinutes > 0 && System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000)) { return true; - } - return false; + } return false; } public void memberLoggedOff() { @@ -493,8 +465,7 @@ public class Faction extends Entity implements EconomyParticipator { 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; + if (oldLeader != null) { oldLeader.setRole(Role.NORMAL); } return; } // no members left and faction isn't permanent, so disband it @@ -507,10 +478,8 @@ public class Faction extends Entity implements EconomyParticipator { } this.detach(); - } - else { // promote new faction admin - if (oldLeader != null) { oldLeader.setRole(Role.NORMAL); } - replacements.get(0).setRole(Role.ADMIN); + } else { // promote new faction admin + if (oldLeader != null) { oldLeader.setRole(Role.NORMAL); } replacements.get(0).setRole(Role.ADMIN); 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()); P.p.log("Faction " + this.getTag() + " (" + this.getId() + ") admin was removed. Replacement admin: " + replacements.get(0).getName()); } @@ -568,8 +537,7 @@ public class Faction extends Entity implements EconomyParticipator { if (ownerData == null) { continue; } - Iterator iter = ownerData.iterator(); - while (iter.hasNext()) { + Iterator iter = ownerData.iterator(); while (iter.hasNext()) { if (iter.next().equals(player.getId())) { iter.remove(); } @@ -590,19 +558,15 @@ public class Faction extends Entity implements EconomyParticipator { 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); - if (ownerData == null) { + } Set ownerData = claimOwnership.get(loc); if (ownerData == null) { return false; - } - if (ownerData.contains(player.getId())) { + } if (ownerData.contains(player.getId())) { return true; } @@ -610,21 +574,15 @@ public class Faction extends Entity implements EconomyParticipator { } public void setPlayerAsOwner(FPlayer player, FLocation loc) { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null) { + Set ownerData = claimOwnership.get(loc); if (ownerData == null) { ownerData = new HashSet(); - } - ownerData.add(player.getId()); - claimOwnership.put(loc, ownerData); + } ownerData.add(player.getId()); claimOwnership.put(loc, ownerData); } public void removePlayerAsOwner(FPlayer player, FLocation loc) { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null) { + 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) { @@ -632,29 +590,23 @@ public class Faction extends Entity implements EconomyParticipator { } public String getOwnerListString(FLocation loc) { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null || ownerData.isEmpty()) { + Set ownerData = claimOwnership.get(loc); if (ownerData == null || ownerData.isEmpty()) { return ""; } String ownerList = ""; - Iterator iter = ownerData.iterator(); - while (iter.hasNext()) { + Iterator iter = ownerData.iterator(); while (iter.hasNext()) { if (!ownerList.isEmpty()) { ownerList += ", "; - } - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(iter.next())); + } OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(iter.next())); ownerList += offlinePlayer != null ? offlinePlayer.getName() : "null player"; - } - return ownerList; + } return ownerList; } 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.ADMIN) - || Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()))) { + if (fplayer.getFaction() == this && (fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.ADMIN) || Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()))) { return true; } diff --git a/src/main/java/com/massivecraft/factions/Factions.java b/src/main/java/com/massivecraft/factions/Factions.java index fe6e2abf..5659536e 100644 --- a/src/main/java/com/massivecraft/factions/Factions.java +++ b/src/main/java/com/massivecraft/factions/Factions.java @@ -27,8 +27,7 @@ public class Factions extends EntityCollection { @Override public Type getMapType() { - return new TypeToken>() { - }.getType(); + return new TypeToken>() {}.getType(); } @Override @@ -37,30 +36,24 @@ public class Factions extends EntityCollection { // Make sure the default neutral faction exists if (!this.exists("0")) { - Faction faction = this.create("0"); - faction.setTag(TL.WILDERNESS.toString()); + Faction faction = this.create("0"); faction.setTag(TL.WILDERNESS.toString()); faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); - } - else { + } else { if (!this.get("0").getTag().equalsIgnoreCase(TL.WILDERNESS.toString())) { get("0").setTag(TL.WILDERNESS.toString()); - } - if (!this.get("0").getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) { + } if (!this.get("0").getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) { get("0").setDescription(TL.WILDERNESS_DESCRIPTION.toString()); } } // Make sure the safe zone faction exists if (!this.exists("-1")) { - Faction faction = this.create("-1"); - faction.setTag(TL.SAFEZONE.toString()); + Faction faction = this.create("-1"); faction.setTag(TL.SAFEZONE.toString()); faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); - } - else { + } else { if (!getSafeZone().getTag().equalsIgnoreCase(TL.SAFEZONE.toString())) { getSafeZone().setTag(TL.SAFEZONE.toString()); - } - if (!getSafeZone().getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) { + } if (!getSafeZone().getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) { getSafeZone().setDescription(TL.SAFEZONE_DESCRIPTION.toString()); } // if SafeZone has old pre-1.6.0 name, rename it to remove troublesome " " @@ -70,15 +63,12 @@ public class Factions extends EntityCollection { // Make sure the war zone faction exists if (!this.exists("-2")) { - Faction faction = this.create("-2"); - faction.setTag(TL.WARZONE.toString()); + Faction faction = this.create("-2"); faction.setTag(TL.WARZONE.toString()); faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); - } - else { + } else { if (!getWarZone().getTag().equalsIgnoreCase(TL.WARZONE.toString())) { getWarZone().setTag(TL.WARZONE.toString()); - } - if (!getWarZone().getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) { + } if (!getWarZone().getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) { getWarZone().setDescription(TL.WARZONE_DESCRIPTION.toString()); } // if WarZone has old pre-1.6.0 name, rename it to remove troublesome " " @@ -102,8 +92,7 @@ public class Factions extends EntityCollection { @Override public Faction get(String id) { if (!this.exists(id)) { - p.log(Level.WARNING, "Non existing factionId " + id + " requested! Issuing cleaning!"); - Board.clean(); + p.log(Level.WARNING, "Non existing factionId " + id + " requested! Issuing cleaning!"); Board.clean(); FPlayers.i.clean(); } @@ -149,13 +138,11 @@ public class Factions extends EntityCollection { // Loops through all faction tags. Case and color insensitive. public Faction getByTag(String str) { - String compStr = MiscUtil.getComparisonString(str); - for (Faction faction : this.get()) { + String compStr = MiscUtil.getComparisonString(str); for (Faction faction : this.get()) { if (faction.getComparisonTag().equals(compStr)) { return faction; } - } - return null; + } return null; } public Faction getBestTagMatch(String searchFor) { @@ -166,8 +153,7 @@ public class Factions extends EntityCollection { tag2faction.put(ChatColor.stripColor(faction.getTag()), faction); } - String tag = TextUtil.getBestStartWithCI(tag2faction.keySet(), searchFor); - if (tag == null) { return null; } + String tag = TextUtil.getBestStartWithCI(tag2faction.keySet(), searchFor); if (tag == null) { return null; } return tag2faction.get(tag); } diff --git a/src/main/java/com/massivecraft/factions/P.java b/src/main/java/com/massivecraft/factions/P.java index 92035d8b..3bc21cec 100644 --- a/src/main/java/com/massivecraft/factions/P.java +++ b/src/main/java/com/massivecraft/factions/P.java @@ -48,8 +48,7 @@ public class P extends MPlugin { } public void setLocked(boolean val) { - this.locked = val; - this.setAutoSave(val); + this.locked = val; this.setAutoSave(val); } private Integer AutoLeaveTask = null; @@ -59,12 +58,9 @@ public class P extends MPlugin { public CmdAutoHelp cmdAutoHelp; public P() { - p = this; - this.playerListener = new FactionsPlayerListener(this); - this.chatListener = new FactionsChatListener(this); - this.entityListener = new FactionsEntityListener(this); - this.exploitListener = new FactionsExploitListener(); - this.blockListener = new FactionsBlockListener(this); + p = this; this.playerListener = new FactionsPlayerListener(this); + this.chatListener = new FactionsChatListener(this); this.entityListener = new FactionsEntityListener(this); + this.exploitListener = new FactionsExploitListener(); this.blockListener = new FactionsBlockListener(this); } @@ -75,24 +71,16 @@ public class P extends MPlugin { Class.forName("org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken"); } catch (ClassNotFoundException ex) { this.log(Level.SEVERE, "GSON lib not found. Your CraftBukkit build is too old (< 1.3.2) or otherwise not compatible."); - this.suicide(); - return; + this.suicide(); return; } - if (!preEnable()) { return; } - this.loadSuccessful = false; + if (!preEnable()) { return; } this.loadSuccessful = false; // Load Conf from disk - Conf.load(); - Essentials.setup(); - FPlayers.i.loadFromDisc(); - Factions.i.loadFromDisc(); - Board.load(); + Conf.load(); Essentials.setup(); FPlayers.i.loadFromDisc(); Factions.i.loadFromDisc(); Board.load(); // Add Base Commands - this.cmdBase = new FCmdRoot(); - this.cmdAutoHelp = new CmdAutoHelp(); - this.getBaseCommands().add(cmdBase); + this.cmdBase = new FCmdRoot(); this.cmdAutoHelp = new CmdAutoHelp(); this.getBaseCommands().add(cmdBase); Econ.setup(); @@ -113,41 +101,29 @@ public class P extends MPlugin { // since some other plugins execute commands directly through this command interface, provide it this.getCommand(this.refCommand).setExecutor(this); - postEnable(); - this.loadSuccessful = true; + postEnable(); this.loadSuccessful = true; } @Override public GsonBuilder getGsonBuilder() { - Type mapFLocToStringSetType = new TypeToken>>() { - }.getType(); + Type mapFLocToStringSetType = new TypeToken>>() {}.getType(); - return new GsonBuilder() - .setPrettyPrinting() - .disableHtmlEscaping() - .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE) - .registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()) - .registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()); + return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE).registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()).registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()); } @Override public void onDisable() { // only save data if plugin actually completely loaded successfully if (this.loadSuccessful) { - Board.save(); - Conf.save(); - } - if (AutoLeaveTask != null) { - this.getServer().getScheduler().cancelTask(AutoLeaveTask); - AutoLeaveTask = null; - } - super.onDisable(); + Board.save(); 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 (!restartIfRunning) { return; } this.getServer().getScheduler().cancelTask(AutoLeaveTask); } if (Conf.autoLeaveRoutineRunsEveryXMinutes > 0.0) { @@ -158,8 +134,7 @@ public class P extends MPlugin { @Override public void postAutoSave() { - Board.save(); - Conf.save(); + Board.save(); Conf.save(); } @Override @@ -212,11 +187,9 @@ public class P extends MPlugin { // 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.i.get(player); + if (player == null) { return false; } FPlayer me = FPlayers.i.get(player); - if (me == null) { return false; } - return me.getChatMode().isAtLeast(ChatMode.ALLIANCE); + if (me == null) { return false; } return me.getChatMode().isAtLeast(ChatMode.ALLIANCE); } // Is this chat message actually a Factions command, and thus should be left alone by other plugins? @@ -224,8 +197,7 @@ public class P extends MPlugin { // TODO: GET THIS BACK AND WORKING public boolean isFactionsCommand(String check) { - if (check == null || check.isEmpty()) { return false; } - return this.handleCommand(null, check, true); + if (check == null || check.isEmpty()) { return false; } return this.handleCommand(null, check, true); } // Get a player's faction tag (faction name), mainly for usage by chat plugins for local/channel chat @@ -239,20 +211,16 @@ public class P extends MPlugin { if (speaker == null) { return tag; } - FPlayer me = FPlayers.i.get(speaker); - if (me == null) { return tag; } + FPlayer me = FPlayers.i.get(speaker); if (me == null) { return tag; } // if listener isn't set, or config option is disabled, give back uncolored tag if (listener == null || !Conf.chatTagRelationColored) { tag = me.getChatTag().trim(); - } - else { + } else { FPlayer you = FPlayers.i.get(listener); - if (you == null) { tag = me.getChatTag().trim(); } - else // everything checks out, give the colored tag + if (you == null) { tag = me.getChatTag().trim(); } else // everything checks out, give the colored tag { tag = me.getChatTag(you).trim(); } - } - if (tag.isEmpty()) { tag = "~"; } + } if (tag.isEmpty()) { tag = "~"; } return tag; } @@ -261,42 +229,35 @@ public class P extends MPlugin { public String getPlayerTitle(Player player) { if (player == null) { return ""; } - FPlayer me = FPlayers.i.get(player); - if (me == null) { return ""; } + FPlayer me = FPlayers.i.get(player); if (me == null) { return ""; } return me.getTitle().trim(); } // Get a list of all faction tags (names) public Set getFactionTags() { - Set tags = new HashSet(); - for (Faction faction : Factions.i.get()) { + Set tags = new HashSet(); for (Faction faction : Factions.i.get()) { tags.add(faction.getTag()); - } - return tags; + } return tags; } // Get a list of all players in the specified faction public Set getPlayersInFaction(String factionTag) { - Set players = new HashSet(); - Faction faction = Factions.i.getByTag(factionTag); + Set players = new HashSet(); Faction faction = Factions.i.getByTag(factionTag); if (faction != null) { for (FPlayer fplayer : faction.getFPlayers()) { players.add(fplayer.getName()); } - } - return players; + } return players; } // Get a list of all online players in the specified faction public Set getOnlinePlayersInFaction(String factionTag) { - Set players = new HashSet(); - Faction faction = Factions.i.getByTag(factionTag); + Set players = new HashSet(); Faction faction = Factions.i.getByTag(factionTag); if (faction != null) { for (FPlayer fplayer : faction.getFPlayersWhereOnline(true)) { players.add(fplayer.getName()); } - } - return players; + } return players; } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java index c329fefc..14b51005 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java @@ -10,49 +10,39 @@ import org.bukkit.Bukkit; public class CmdAdmin extends FCommand { public CmdAdmin() { - super(); - this.aliases.add("admin"); + super(); this.aliases.add("admin"); this.requiredArgs.add("player name"); //this.optionalArgs.put("", ""); - this.permission = Permission.ADMIN.node; - this.disableOnLock = true; + this.permission = Permission.ADMIN.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - FPlayer fyou = this.argAsBestFPlayerMatch(0); - if (fyou == null) { return; } + FPlayer fyou = this.argAsBestFPlayerMatch(0); if (fyou == null) { return; } - boolean permAny = Permission.ADMIN_ANY.has(sender, false); - Faction targetFaction = fyou.getFaction(); + boolean permAny = Permission.ADMIN_ANY.has(sender, false); Faction targetFaction = fyou.getFaction(); if (targetFaction != myFaction && !permAny) { - msg("%s is not a member in your faction.", fyou.describeTo(fme, true)); - return; + msg("%s is not a member in your faction.", fyou.describeTo(fme, true)); return; } if (fme != null && fme.getRole() != Role.ADMIN && !permAny) { - msg("You are not the faction admin."); - return; + msg("You are not the faction admin."); return; } if (fyou == fme && !permAny) { - msg("The target player musn't be yourself."); - return; + msg("The target player musn't be yourself."); return; } // only perform a FPlayerJoinEvent when newLeader isn't actually in the faction if (fyou.getFaction() != targetFaction) { FPlayerJoinEvent event = new FPlayerJoinEvent(FPlayers.i.get(me), targetFaction, FPlayerJoinEvent.PlayerJoinReason.LEADER); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { return; } + Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; } } FPlayer admin = targetFaction.getFPlayerAdmin(); @@ -66,8 +56,7 @@ public class CmdAdmin extends FCommand { } // promote target player, and demote existing admin if one exists - if (admin != null) { admin.setRole(Role.MODERATOR); } - fyou.setRole(Role.ADMIN); + if (admin != null) { admin.setRole(Role.MODERATOR); } fyou.setRole(Role.ADMIN); msg("You have promoted %s to the position of faction admin.", fyou.describeTo(fme, true)); // Inform all players diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java index 559c7e51..94fcdc06 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java @@ -6,33 +6,27 @@ import com.massivecraft.factions.struct.Role; public class CmdAutoClaim extends FCommand { public CmdAutoClaim() { - super(); - this.aliases.add("autoclaim"); + super(); this.aliases.add("autoclaim"); //this.requiredArgs.add(""); this.optionalArgs.put("faction", "your"); - this.permission = Permission.AUTOCLAIM.node; - this.disableOnLock = true; + this.permission = Permission.AUTOCLAIM.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { Faction forFaction = this.argAsFaction(0, myFaction); if (forFaction == null || forFaction == fme.getAutoClaimFor()) { - fme.setAutoClaimFor(null); - msg("Auto-claiming of land disabled."); - return; + fme.setAutoClaimFor(null); msg("Auto-claiming of land disabled."); return; } if (!fme.canClaimForFaction(forFaction)) { - if (myFaction == forFaction) { msg("You must be %s to claim land.", Role.MODERATOR.toString()); } - else { msg("You can't claim land for %s.", forFaction.describeTo(fme)); } + if (myFaction == forFaction) { + msg("You must be %s to claim land.", Role.MODERATOR.toString()); + } else { msg("You can't claim land for %s.", forFaction.describeTo(fme)); } return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java b/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java index 465cfd6c..e207f1a2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java @@ -8,10 +8,7 @@ import java.util.ArrayList; public class CmdAutoHelp extends MCommand

{ public CmdAutoHelp() { - super(P.p); - this.aliases.add("?"); - this.aliases.add("h"); - this.aliases.add("help"); + super(P.p); this.aliases.add("?"); this.aliases.add("h"); this.aliases.add("help"); this.setHelpShort(""); @@ -28,12 +25,7 @@ public class CmdAutoHelp extends MCommand

{ lines.addAll(pcmd.helpLong); for (MCommand scmd : pcmd.subCommands) { - if - ( - scmd.visibility == CommandVisibility.VISIBLE - || - (scmd.visibility == CommandVisibility.SECRET && scmd.validSenderPermissions(sender, false)) - ) { + if (scmd.visibility == CommandVisibility.VISIBLE || (scmd.visibility == CommandVisibility.SECRET && scmd.validSenderPermissions(sender, false))) { lines.add(scmd.getUseageTemplate(this.commandChain, true)); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java b/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java index 8ef31d7a..b9603983 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java @@ -5,26 +5,20 @@ import com.massivecraft.factions.struct.Permission; public class CmdBoom extends FCommand { public CmdBoom() { - super(); - this.aliases.add("noboom"); + super(); this.aliases.add("noboom"); //this.requiredArgs.add(""); this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.NO_BOOM.node; - this.disableOnLock = true; + this.permission = Permission.NO_BOOM.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override public void perform() { if (!myFaction.isPeaceful()) { - fme.msg("This command is only usable by factions which are specially designated as peaceful."); - return; + fme.msg("This command is only usable by factions which are specially designated as peaceful."); return; } // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java b/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java index 2ffba0aa..f230afe8 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java @@ -5,19 +5,14 @@ import com.massivecraft.factions.struct.Permission; public class CmdBypass extends FCommand { public CmdBypass() { - super(); - this.aliases.add("bypass"); + super(); this.aliases.add("bypass"); //this.requiredArgs.add(""); this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.BYPASS.node; - this.disableOnLock = false; + this.permission = Permission.BYPASS.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override @@ -28,10 +23,8 @@ public class CmdBypass extends FCommand { if (fme.isAdminBypassing()) { fme.msg("You have enabled admin bypass mode. You will be able to build or destroy anywhere."); P.p.log(fme.getName() + " has ENABLED admin bypass mode."); - } - else { - fme.msg("You have disabled admin bypass mode."); - P.p.log(fme.getName() + " DISABLED admin bypass mode."); + } else { + fme.msg("You have disabled admin bypass mode."); P.p.log(fme.getName() + " DISABLED admin bypass mode."); } } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdChat.java b/src/main/java/com/massivecraft/factions/cmd/CmdChat.java index 66004141..b7d15a71 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChat.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChat.java @@ -7,46 +7,33 @@ import com.massivecraft.factions.struct.Permission; public class CmdChat extends FCommand { public CmdChat() { - super(); - this.aliases.add("c"); - this.aliases.add("chat"); + super(); this.aliases.add("c"); this.aliases.add("chat"); //this.requiredArgs.add(""); this.optionalArgs.put("mode", "next"); - this.permission = Permission.CHAT.node; - this.disableOnLock = false; + this.permission = Permission.CHAT.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = true; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { if (!Conf.factionOnlyChat) { - msg("The built in chat chat channels are disabled on this server."); - return; + msg("The built in chat chat channels are disabled on this server."); return; } - String modeString = this.argAsString(0); - ChatMode modeTarget = fme.getChatMode().getNext(); + String modeString = this.argAsString(0); ChatMode modeTarget = fme.getChatMode().getNext(); if (modeString != null) { - modeString.toLowerCase(); - if (modeString.startsWith("p")) { + modeString.toLowerCase(); if (modeString.startsWith("p")) { modeTarget = ChatMode.PUBLIC; - } - else if (modeString.startsWith("a")) { + } else if (modeString.startsWith("a")) { modeTarget = ChatMode.ALLIANCE; - } - else if (modeString.startsWith("f")) { + } else if (modeString.startsWith("f")) { modeTarget = ChatMode.FACTION; - } - else { - msg("Unrecognised chat mode. Please enter either 'a','f' or 'p'"); - return; + } else { + msg("Unrecognised chat mode. Please enter either 'a','f' or 'p'"); return; } } @@ -54,11 +41,9 @@ public class CmdChat extends FCommand { if (fme.getChatMode() == ChatMode.PUBLIC) { msg("Public chat mode."); - } - else if (fme.getChatMode() == ChatMode.ALLIANCE) { + } else if (fme.getChatMode() == ChatMode.ALLIANCE) { msg("Alliance only chat mode."); - } - else { + } else { msg("Faction only chat mode."); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java b/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java index f1b9ae16..36963458 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java @@ -5,18 +5,13 @@ import com.massivecraft.factions.struct.Permission; public class CmdChatSpy extends FCommand { public CmdChatSpy() { - super(); - this.aliases.add("chatspy"); + super(); this.aliases.add("chatspy"); this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.CHATSPY.node; - this.disableOnLock = false; + this.permission = Permission.CHATSPY.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override @@ -24,12 +19,9 @@ public class CmdChatSpy extends FCommand { fme.setSpyingChat(this.argAsBool(0, !fme.isSpyingChat())); if (fme.isSpyingChat()) { - fme.msg("You have enabled chat spying mode."); - P.p.log(fme.getName() + " has ENABLED chat spying mode."); - } - else { - fme.msg("You have disabled chat spying mode."); - P.p.log(fme.getName() + " DISABLED chat spying mode."); + fme.msg("You have enabled chat spying mode."); P.p.log(fme.getName() + " has ENABLED chat spying mode."); + } else { + fme.msg("You have disabled chat spying mode."); P.p.log(fme.getName() + " DISABLED chat spying mode."); } } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java index 33bcfc50..12a771e3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java @@ -10,42 +10,32 @@ import com.massivecraft.factions.util.SpiralTask; public class CmdClaim extends FCommand { public CmdClaim() { - super(); - this.aliases.add("claim"); + super(); this.aliases.add("claim"); //this.requiredArgs.add(""); - this.optionalArgs.put("faction", "your"); - this.optionalArgs.put("radius", "1"); + this.optionalArgs.put("faction", "your"); this.optionalArgs.put("radius", "1"); - this.permission = Permission.CLAIM.node; - this.disableOnLock = true; + this.permission = Permission.CLAIM.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { // Read and validate input - final Faction forFaction = this.argAsFaction(0, myFaction); - int radius = this.argAsInt(1, 1); + final Faction forFaction = this.argAsFaction(0, myFaction); int radius = this.argAsInt(1, 1); if (radius < 1) { - msg("If you specify a radius, it must be at least 1."); - return; + msg("If you specify a radius, it must be at least 1."); return; } if (radius < 2) { // single chunk fme.attemptClaim(forFaction, me.getLocation(), true); - } - else { + } else { // radius claim if (!Permission.CLAIM_RADIUS.has(sender, false)) { - msg("You do not have permission to claim in a radius."); - return; + msg("You do not have permission to claim in a radius."); return; } new SpiralTask(new FLocation(me), radius) { @@ -55,10 +45,8 @@ public class CmdClaim extends FCommand { @Override public boolean work() { boolean success = fme.attemptClaim(forFaction, this.currentLocation(), true); - if (success) { failCount = 0; } - else if (!success && failCount++ >= limit) { - this.stop(); - return false; + if (success) { failCount = 0; } else if (!success && failCount++ >= limit) { + this.stop(); return false; } return true; diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java b/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java index ceb0478a..1978531d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java @@ -17,19 +17,13 @@ public class CmdConfig extends FCommand { private static HashMap properFieldNames = new HashMap(); public CmdConfig() { - super(); - this.aliases.add("config"); + super(); this.aliases.add("config"); - this.requiredArgs.add("setting"); - this.requiredArgs.add("value"); - this.errorOnToManyArgs = false; + this.requiredArgs.add("setting"); this.requiredArgs.add("value"); this.errorOnToManyArgs = false; - this.permission = Permission.CONFIG.node; - this.disableOnLock = true; + this.permission = Permission.CONFIG.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @@ -38,27 +32,22 @@ public class CmdConfig extends FCommand { // 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 (int i = 0; i < fields.length; i++) { + Field[] fields = Conf.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { properFieldNames.put(fields[i].getName().toLowerCase(), fields[i].getName()); } } - String field = this.argAsString(0).toLowerCase(); - if (field.startsWith("\"") && field.endsWith("\"")) { + String field = this.argAsString(0).toLowerCase(); if (field.startsWith("\"") && field.endsWith("\"")) { field = field.substring(1, field.length() - 1); - } - String fieldName = properFieldNames.get(field); + } String fieldName = properFieldNames.get(field); if (fieldName == null || fieldName.isEmpty()) { - msg("No configuration setting \"%s\" exists.", field); - return; + msg("No configuration setting \"%s\" exists.", field); return; } String success; - String value = args.get(1); - for (int i = 2; i < args.size(); i++) { + String value = args.get(1); for (int i = 2; i < args.size(); i++) { value += ' ' + args.get(i); } @@ -67,13 +56,11 @@ public class CmdConfig extends FCommand { // boolean if (target.getType() == boolean.class) { - boolean targetValue = this.strAsBool(value); - target.setBoolean(null, targetValue); + boolean targetValue = this.strAsBool(value); target.setBoolean(null, targetValue); if (targetValue) { success = "\"" + fieldName + "\" option set to true (enabled)."; - } - else { + } else { success = "\"" + fieldName + "\" option set to false (disabled)."; } } @@ -81,20 +68,17 @@ public class CmdConfig extends FCommand { // int else if (target.getType() == int.class) { try { - int intVal = Integer.parseInt(value); - target.setInt(null, intVal); + int intVal = Integer.parseInt(value); target.setInt(null, intVal); success = "\"" + fieldName + "\" option set to " + intVal + "."; } catch (NumberFormatException ex) { - sendMessage("Cannot set \"" + fieldName + "\": integer (whole number) value required."); - return; + sendMessage("Cannot set \"" + fieldName + "\": integer (whole number) value required."); return; } } // long else if (target.getType() == long.class) { try { - long longVal = Long.parseLong(value); - target.setLong(null, longVal); + long longVal = Long.parseLong(value); target.setLong(null, longVal); success = "\"" + fieldName + "\" option set to " + longVal + "."; } catch (NumberFormatException ex) { sendMessage("Cannot set \"" + fieldName + "\": long integer (whole number) value required."); @@ -105,46 +89,38 @@ public class CmdConfig extends FCommand { // double else if (target.getType() == double.class) { try { - double doubleVal = Double.parseDouble(value); - target.setDouble(null, doubleVal); + double doubleVal = Double.parseDouble(value); target.setDouble(null, doubleVal); success = "\"" + fieldName + "\" option set to " + doubleVal + "."; } catch (NumberFormatException ex) { - sendMessage("Cannot set \"" + fieldName + "\": double (numeric) value required."); - return; + sendMessage("Cannot set \"" + fieldName + "\": double (numeric) value required."); return; } } // float else if (target.getType() == float.class) { try { - float floatVal = Float.parseFloat(value); - target.setFloat(null, floatVal); + float floatVal = Float.parseFloat(value); target.setFloat(null, floatVal); success = "\"" + fieldName + "\" option set to " + floatVal + "."; } catch (NumberFormatException ex) { - sendMessage("Cannot set \"" + fieldName + "\": float (numeric) value required."); - return; + sendMessage("Cannot set \"" + fieldName + "\": float (numeric) value required."); return; } } // String else if (target.getType() == String.class) { - target.set(null, value); - success = "\"" + fieldName + "\" option set to \"" + value + "\"."; + target.set(null, value); success = "\"" + fieldName + "\" option set to \"" + value + "\"."; } // ChatColor else if (target.getType() == ChatColor.class) { - ChatColor newColor = null; - try { + ChatColor newColor = null; try { newColor = ChatColor.valueOf(value.toUpperCase()); } catch (IllegalArgumentException ex) { - } - if (newColor == null) { + } if (newColor == null) { sendMessage("Cannot set \"" + fieldName + "\": \"" + value.toUpperCase() + "\" is not a valid color."); return; - } - target.set(null, newColor); + } target.set(null, newColor); success = "\"" + fieldName + "\" color option set to \"" + value.toUpperCase() + "\"."; } @@ -161,49 +137,41 @@ public class CmdConfig extends FCommand { // Set else if (innerType == Material.class) { - Material newMat = null; - try { + Material newMat = null; try { newMat = Material.valueOf(value.toUpperCase()); } catch (IllegalArgumentException ex) { - } - if (newMat == null) { + } if (newMat == null) { sendMessage("Cannot change \"" + fieldName + "\" set: \"" + value.toUpperCase() + "\" is not a valid material."); return; } - @SuppressWarnings("unchecked") - Set matSet = (Set) target.get(null); + @SuppressWarnings("unchecked") Set matSet = (Set) target.get(null); // Material already present, so remove it if (matSet.contains(newMat)) { - matSet.remove(newMat); - target.set(null, matSet); + matSet.remove(newMat); target.set(null, matSet); success = "\"" + fieldName + "\" set: Material \"" + value.toUpperCase() + "\" removed."; } // Material not present yet, add it else { - matSet.add(newMat); - target.set(null, matSet); + matSet.add(newMat); target.set(null, matSet); success = "\"" + fieldName + "\" set: Material \"" + value.toUpperCase() + "\" added."; } } // Set else if (innerType == String.class) { - @SuppressWarnings("unchecked") - Set stringSet = (Set) target.get(null); + @SuppressWarnings("unchecked") Set stringSet = (Set) target.get(null); // String already present, so remove it if (stringSet.contains(value)) { - stringSet.remove(value); - target.set(null, stringSet); + stringSet.remove(value); target.set(null, stringSet); success = "\"" + fieldName + "\" set: \"" + value + "\" removed."; } // String not present yet, add it else { - stringSet.add(value); - target.set(null, stringSet); + stringSet.add(value); target.set(null, stringSet); success = "\"" + fieldName + "\" set: \"" + value + "\" added."; } } @@ -224,16 +192,13 @@ public class CmdConfig extends FCommand { sendMessage("Configuration setting \"" + fieldName + "\" couldn't be matched, though it should be... please report this error."); return; } catch (IllegalAccessException ex) { - sendMessage("Error setting configuration setting \"" + fieldName + "\" to \"" + value + "\"."); - return; + sendMessage("Error setting configuration setting \"" + fieldName + "\" to \"" + value + "\"."); return; } if (!success.isEmpty()) { if (sender instanceof Player) { - sendMessage(success); - P.p.log(success + " Command was run by " + fme.getName() + "."); - } - else // using P.p.log() instead of sendMessage if run from server console so that "[Factions v#.#.#]" is prepended in server log + sendMessage(success); P.p.log(success + " Command was run by " + fme.getName() + "."); + } else // using P.p.log() instead of sendMessage if run from server console so that "[Factions v#.#.#]" is prepended in server log { P.p.log(success); } } // save change to disk diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java index c9649993..1c555eb5 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java @@ -12,19 +12,14 @@ import java.util.ArrayList; public class CmdCreate extends FCommand { public CmdCreate() { - super(); - this.aliases.add("create"); + super(); this.aliases.add("create"); this.requiredArgs.add("faction tag"); //this.optionalArgs.put("", ""); - this.permission = Permission.CREATE.node; - this.disableOnLock = true; + this.permission = Permission.CREATE.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override @@ -32,19 +27,15 @@ public class CmdCreate extends FCommand { String tag = this.argAsString(0); if (fme.hasFaction()) { - msg("You must leave your current faction first."); - return; + msg("You must leave your current faction first."); return; } if (Factions.i.isTagTaken(tag)) { - msg("That tag is already in use."); - return; + msg("That tag is already in use."); return; } - ArrayList tagValidationErrors = Factions.validateTag(tag); - if (tagValidationErrors.size() > 0) { - sendMessage(tagValidationErrors); - return; + ArrayList tagValidationErrors = Factions.validateTag(tag); if (tagValidationErrors.size() > 0) { + sendMessage(tagValidationErrors); return; } // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay @@ -52,8 +43,7 @@ public class CmdCreate extends FCommand { // trigger the faction creation event (cancellable) FactionCreateEvent createEvent = new FactionCreateEvent(me, tag); - Bukkit.getServer().getPluginManager().callEvent(createEvent); - if (createEvent.isCancelled()) { return; } + Bukkit.getServer().getPluginManager().callEvent(createEvent); if (createEvent.isCancelled()) { return; } // then make 'em pay (if applicable) if (!payForCommand(Conf.econCostCreate, "to create a new faction", "for creating a new faction")) { return; } @@ -62,8 +52,7 @@ public class CmdCreate extends FCommand { // TODO: Why would this even happen??? Auto increment clash?? if (faction == null) { - msg("There was an internal error while trying to create your faction. Please try again."); - return; + msg("There was an internal error while trying to create your faction. Please try again."); return; } // finish setting up the Faction @@ -75,8 +64,7 @@ public class CmdCreate extends FCommand { // join event cannot be cancelled or you'll have an empty faction // finish setting up the FPlayer - fme.setRole(Role.ADMIN); - fme.setFaction(faction); + fme.setRole(Role.ADMIN); fme.setFaction(faction); for (FPlayer follower : FPlayers.i.getOnline()) { follower.msg("%s created a new faction %s", fme.describeTo(follower, true), faction.getTag(follower)); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java index 1dea77bc..523eaefc 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java @@ -6,31 +6,23 @@ import com.massivecraft.factions.struct.Permission; public class CmdDeinvite extends FCommand { public CmdDeinvite() { - super(); - this.aliases.add("deinvite"); - this.aliases.add("deinv"); + super(); this.aliases.add("deinvite"); this.aliases.add("deinv"); this.requiredArgs.add("player name"); //this.optionalArgs.put("", ""); - this.permission = Permission.DEINVITE.node; - this.disableOnLock = true; + this.permission = Permission.DEINVITE.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) { return; } + FPlayer you = this.argAsBestFPlayerMatch(0); if (you == null) { return; } if (you.getFaction() == myFaction) { msg("%s is already a member of %s", you.getName(), myFaction.getTag()); - msg("You might want to: %s", p.cmdBase.cmdKick.getUseageTemplate(false)); - return; + msg("You might want to: %s", p.cmdBase.cmdKick.getUseageTemplate(false)); return; } myFaction.deinvite(you); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java b/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java index bdd815c1..c709320a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java @@ -8,20 +8,14 @@ import com.massivecraft.factions.zcore.util.TextUtil; public class CmdDescription extends FCommand { public CmdDescription() { - super(); - this.aliases.add("desc"); + super(); this.aliases.add("desc"); - this.requiredArgs.add("desc"); - this.errorOnToManyArgs = false; + this.requiredArgs.add("desc"); this.errorOnToManyArgs = false; //this.optionalArgs - this.permission = Permission.DESCRIPTION.node; - this.disableOnLock = true; + this.permission = Permission.DESCRIPTION.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override @@ -35,8 +29,7 @@ public class CmdDescription extends FCommand { if (!Conf.broadcastDescriptionChanges) { fme.msg("You have changed the description for %s to:", myFaction.describeTo(fme)); - fme.sendMessage(myFaction.getDescription()); - return; + fme.sendMessage(myFaction.getDescription()); return; } // Broadcast the description to everyone diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java index 80937f0d..26ae8470 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java @@ -11,50 +11,40 @@ import org.bukkit.Bukkit; public class CmdDisband extends FCommand { public CmdDisband() { - super(); - this.aliases.add("disband"); + super(); this.aliases.add("disband"); //this.requiredArgs.add(""); this.optionalArgs.put("faction tag", "yours"); - this.permission = Permission.DISBAND.node; - this.disableOnLock = true; + this.permission = Permission.DISBAND.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { // The faction, default to your own.. but null if console sender. - Faction faction = this.argAsFaction(0, fme == null ? null : myFaction); - if (faction == null) { return; } + Faction faction = this.argAsFaction(0, fme == null ? null : myFaction); if (faction == null) { return; } boolean isMyFaction = fme == null ? false : faction == myFaction; if (isMyFaction) { if (!assertMinRole(Role.ADMIN)) { return; } - } - else { + } else { if (!Permission.DISBAND_ANY.has(sender, true)) { return; } } if (!faction.isNormal()) { - msg("You cannot disband the Wilderness, SafeZone, or WarZone."); - return; - } - if (faction.isPermanent()) { - msg("This faction is designated as permanent, so you cannot disband it."); - return; + msg("You cannot disband the Wilderness, SafeZone, or WarZone."); return; + } if (faction.isPermanent()) { + msg("This faction is designated as permanent, so you cannot disband it."); return; } FactionDisbandEvent disbandEvent = new FactionDisbandEvent(me, faction.getId()); - Bukkit.getServer().getPluginManager().callEvent(disbandEvent); - if (disbandEvent.isCancelled()) { return; } + Bukkit.getServer().getPluginManager().callEvent(disbandEvent); if (disbandEvent.isCancelled()) { return; } // Send FPlayerLeaveEvent for each player in the faction for (FPlayer fplayer : faction.getFPlayers()) { @@ -66,12 +56,10 @@ public class CmdDisband extends FCommand { String who = senderIsConsole ? "A server admin" : fme.describeTo(fplayer); if (fplayer.getFaction() == faction) { fplayer.msg("%s disbanded your faction.", who); - } - else { + } else { fplayer.msg("%s disbanded the faction %s.", who, faction.getTag(fplayer)); } - } - if (Conf.logFactionDisband) { + } if (Conf.logFactionDisband) { P.p.log("The faction " + faction.getTag() + " (" + faction.getId() + ") was disbanded by " + (senderIsConsole ? "console command" : fme.getName()) + "."); } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java b/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java index 8070b558..f559f857 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java @@ -11,20 +11,14 @@ import java.util.ArrayList; public class CmdHelp extends FCommand { public CmdHelp() { - super(); - this.aliases.add("help"); - this.aliases.add("h"); - this.aliases.add("?"); + super(); this.aliases.add("help"); this.aliases.add("h"); this.aliases.add("?"); //this.requiredArgs.add(""); this.optionalArgs.put("page", "1"); - this.permission = Permission.HELP.node; - this.disableOnLock = false; + this.permission = Permission.HELP.node; this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @@ -39,10 +33,8 @@ public class CmdHelp extends FCommand { page -= 1; if (page < 0 || page >= helpPages.size()) { - msg("This page does not exist"); - return; - } - sendMessage(helpPages.get(page)); + msg("This page does not exist"); return; + } sendMessage(helpPages.get(page)); } //----------------------------------------------// @@ -52,11 +44,9 @@ public class CmdHelp extends FCommand { public ArrayList> helpPages; public void updateHelp() { - helpPages = new ArrayList>(); - ArrayList pageLines; + helpPages = new ArrayList>(); ArrayList pageLines; - pageLines = new ArrayList(); - pageLines.add(p.cmdBase.cmdHelp.getUseageTemplate(true)); + pageLines = new ArrayList(); pageLines.add(p.cmdBase.cmdHelp.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdList.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdShow.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdPower.getUseageTemplate(true)); @@ -64,11 +54,9 @@ public class CmdHelp extends FCommand { pageLines.add(p.cmdBase.cmdLeave.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdChat.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdHome.getUseageTemplate(true)); - pageLines.add(p.txt.parse("Learn how to create a faction on the next page.")); - helpPages.add(pageLines); + pageLines.add(p.txt.parse("Learn how to create a faction on the next page.")); helpPages.add(pageLines); - pageLines = new ArrayList(); - pageLines.add(p.cmdBase.cmdCreate.getUseageTemplate(true)); + pageLines = new ArrayList(); pageLines.add(p.cmdBase.cmdCreate.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdDescription.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdTag.getUseageTemplate(true)); pageLines.add(p.txt.parse("You might want to close it and use invitations:")); @@ -76,25 +64,18 @@ public class CmdHelp extends FCommand { pageLines.add(p.cmdBase.cmdInvite.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdDeinvite.getUseageTemplate(true)); pageLines.add(p.txt.parse("And don't forget to set your home:")); - pageLines.add(p.cmdBase.cmdSethome.getUseageTemplate(true)); - helpPages.add(pageLines); + pageLines.add(p.cmdBase.cmdSethome.getUseageTemplate(true)); helpPages.add(pageLines); if (Econ.isSetup() && Conf.econEnabled && Conf.bankEnabled) { - pageLines = new ArrayList(); - pageLines.add(""); + pageLines = new ArrayList(); pageLines.add(""); pageLines.add(p.txt.parse("Your faction has a bank which is used to pay for certain")); pageLines.add(p.txt.parse("things, so it will need to have money deposited into it.")); - pageLines.add(p.txt.parse("To learn more, use the money command.")); - pageLines.add(""); - pageLines.add(p.cmdBase.cmdMoney.getUseageTemplate(true)); - pageLines.add(""); - pageLines.add(""); - pageLines.add(""); - helpPages.add(pageLines); + pageLines.add(p.txt.parse("To learn more, use the money command.")); pageLines.add(""); + pageLines.add(p.cmdBase.cmdMoney.getUseageTemplate(true)); pageLines.add(""); pageLines.add(""); + pageLines.add(""); helpPages.add(pageLines); } - pageLines = new ArrayList(); - pageLines.add(p.cmdBase.cmdClaim.getUseageTemplate(true)); + pageLines = new ArrayList(); pageLines.add(p.cmdBase.cmdClaim.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdAutoClaim.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdUnclaim.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdUnclaimall.getUseageTemplate(true)); @@ -105,20 +86,16 @@ public class CmdHelp extends FCommand { pageLines.add(p.txt.parse("Player titles are just for fun. No rules connected to them.")); helpPages.add(pageLines); - pageLines = new ArrayList(); - pageLines.add(p.cmdBase.cmdMap.getUseageTemplate(true)); + pageLines = new ArrayList(); pageLines.add(p.cmdBase.cmdMap.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdBoom.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdOwner.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdOwnerList.getUseageTemplate(true)); pageLines.add(p.txt.parse("Claimed land with ownership set is further protected so")); pageLines.add(p.txt.parse("that only the owner(s), faction admin, and possibly the")); - pageLines.add(p.txt.parse("faction moderators have full access.")); - helpPages.add(pageLines); + pageLines.add(p.txt.parse("faction moderators have full access.")); helpPages.add(pageLines); - pageLines = new ArrayList(); - pageLines.add(p.cmdBase.cmdDisband.getUseageTemplate(true)); - pageLines.add(""); - pageLines.add(p.cmdBase.cmdRelationAlly.getUseageTemplate(true)); + pageLines = new ArrayList(); pageLines.add(p.cmdBase.cmdDisband.getUseageTemplate(true)); + pageLines.add(""); pageLines.add(p.cmdBase.cmdRelationAlly.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdRelationNeutral.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdRelationEnemy.getUseageTemplate(true)); pageLines.add(p.txt.parse("Set the relation you WISH to have with another faction.")); @@ -127,11 +104,9 @@ public class CmdHelp extends FCommand { pageLines.add(p.txt.parse("If ONE faction chooses \"enemy\" you will be enemies.")); helpPages.add(pageLines); - pageLines = new ArrayList(); - pageLines.add(p.txt.parse("You can never hurt members or allies.")); + pageLines = new ArrayList(); pageLines.add(p.txt.parse("You can never hurt members or allies.")); pageLines.add(p.txt.parse("You can not hurt neutrals in their own territory.")); - pageLines.add(p.txt.parse("You can always hurt enemies and players without faction.")); - pageLines.add(""); + pageLines.add(p.txt.parse("You can always hurt enemies and players without faction.")); pageLines.add(""); pageLines.add(p.txt.parse("Damage from enemies is reduced in your own territory.")); pageLines.add(p.txt.parse("When you die you lose power. It is restored over time.")); pageLines.add(p.txt.parse("The power of a faction is the sum of all member power.")); @@ -142,17 +117,14 @@ public class CmdHelp extends FCommand { pageLines = new ArrayList(); pageLines.add(p.txt.parse("Only faction members can build and destroy in their own")); pageLines.add(p.txt.parse("territory. Usage of the following items is also restricted:")); - pageLines.add(p.txt.parse("Door, Chest, Furnace, Dispenser, Diode.")); - pageLines.add(""); + pageLines.add(p.txt.parse("Door, Chest, Furnace, Dispenser, Diode.")); pageLines.add(""); pageLines.add(p.txt.parse("Make sure to put pressure plates in front of doors for your")); pageLines.add(p.txt.parse("guest visitors. Otherwise they can't get through. You can")); pageLines.add(p.txt.parse("also use this to create member only areas.")); pageLines.add(p.txt.parse("As dispensers are protected, you can create traps without")); - pageLines.add(p.txt.parse("worrying about those arrows getting stolen.")); - helpPages.add(pageLines); + pageLines.add(p.txt.parse("worrying about those arrows getting stolen.")); helpPages.add(pageLines); - pageLines = new ArrayList(); - pageLines.add("Finally some commands for the server admins:"); + pageLines = new ArrayList(); pageLines.add("Finally some commands for the server admins:"); pageLines.add(p.cmdBase.cmdBypass.getUseageTemplate(true)); pageLines.add(p.txt.parse("/f claim safezone claim land for the Safe Zone")); pageLines.add(p.txt.parse("/f claim warzone claim land for the War Zone")); @@ -160,25 +132,20 @@ public class CmdHelp extends FCommand { pageLines.add(p.cmdBase.cmdSafeunclaimall.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdWarunclaimall.getUseageTemplate(true)); pageLines.add(p.txt.parse("Note: " + p.cmdBase.cmdUnclaim.getUseageTemplate(false) + P.p.txt.parse("") + " works on safe/war zones as well.")); - pageLines.add(p.cmdBase.cmdPeaceful.getUseageTemplate(true)); - helpPages.add(pageLines); + pageLines.add(p.cmdBase.cmdPeaceful.getUseageTemplate(true)); helpPages.add(pageLines); - pageLines = new ArrayList(); - pageLines.add(p.txt.parse("More commands for server admins:")); + pageLines = new ArrayList(); pageLines.add(p.txt.parse("More commands for server admins:")); pageLines.add(p.cmdBase.cmdChatSpy.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdPermanent.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdPermanentPower.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdPowerBoost.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdConfig.getUseageTemplate(true)); - helpPages.add(pageLines); + pageLines.add(p.cmdBase.cmdConfig.getUseageTemplate(true)); helpPages.add(pageLines); - pageLines = new ArrayList(); - pageLines.add(p.txt.parse("Even more commands for server admins:")); + pageLines = new ArrayList(); pageLines.add(p.txt.parse("Even more commands for server admins:")); pageLines.add(p.cmdBase.cmdLock.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdReload.getUseageTemplate(true)); pageLines.add(p.cmdBase.cmdSaveAll.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdVersion.getUseageTemplate(true)); - helpPages.add(pageLines); + pageLines.add(p.cmdBase.cmdVersion.getUseageTemplate(true)); helpPages.add(pageLines); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdHome.java b/src/main/java/com/massivecraft/factions/cmd/CmdHome.java index 77c1524e..955dba8e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdHome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdHome.java @@ -17,86 +17,55 @@ import java.util.List; public class CmdHome extends FCommand { public CmdHome() { - super(); - this.aliases.add("home"); + super(); this.aliases.add("home"); //this.requiredArgs.add(""); //this.optionalArgs.put("", ""); - this.permission = Permission.HOME.node; - this.disableOnLock = false; + this.permission = Permission.HOME.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = true; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { // TODO: Hide this command on help also. if (!Conf.homesEnabled) { - fme.msg("Sorry, Faction homes are disabled on this server."); - return; + fme.msg("Sorry, Faction homes are disabled on this server."); return; } if (!Conf.homesTeleportCommandEnabled) { - fme.msg("Sorry, the ability to teleport to Faction homes is disabled on this server."); - return; + fme.msg("Sorry, the ability to teleport to Faction homes is disabled on this server."); return; } if (!myFaction.hasHome()) { fme.msg("Your faction does not have a home. " + (fme.getRole().value < Role.MODERATOR.value ? " Ask your leader to:" : "You should:")); - fme.sendMessage(p.cmdBase.cmdSethome.getUseageTemplate()); - return; + fme.sendMessage(p.cmdBase.cmdSethome.getUseageTemplate()); return; } if (!Conf.homesTeleportAllowedFromEnemyTerritory && fme.isInEnemyTerritory()) { - fme.msg("You cannot teleport to your faction home while in the territory of an enemy faction."); - return; + fme.msg("You cannot teleport to your faction home while in the territory of an enemy faction."); return; } if (!Conf.homesTeleportAllowedFromDifferentWorld && me.getWorld().getUID() != myFaction.getHome().getWorld().getUID()) { - fme.msg("You cannot teleport to your faction home while in a different world."); - return; + fme.msg("You cannot teleport to your faction home while in a different world."); return; } - Faction faction = Board.getFactionAt(new FLocation(me.getLocation())); - Location loc = me.getLocation().clone(); + Faction faction = Board.getFactionAt(new FLocation(me.getLocation())); Location loc = me.getLocation().clone(); // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby - if - ( - Conf.homesTeleportAllowedEnemyDistance > 0 - && - !faction.isSafeZone() - && - ( - !fme.isInOwnTerritory() - || - ( - fme.isInOwnTerritory() - && - !Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory - ) - ) - ) { - World w = loc.getWorld(); - double x = loc.getX(); - double y = loc.getY(); - double z = loc.getZ(); + if (Conf.homesTeleportAllowedEnemyDistance > 0 && + !faction.isSafeZone() && + (!fme.isInOwnTerritory() || (fme.isInOwnTerritory() && !Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory))) { + World w = loc.getWorld(); double x = loc.getX(); double y = loc.getY(); double z = loc.getZ(); for (Player p : me.getServer().getOnlinePlayers()) { if (p == null || !p.isOnline() || p.isDead() || p == me || p.getWorld() != w) { continue; } - FPlayer fp = FPlayers.i.get(p); - if (fme.getRelationTo(fp) != Relation.ENEMY) { continue; } + FPlayer fp = FPlayers.i.get(p); if (fme.getRelationTo(fp) != Relation.ENEMY) { 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; } @@ -116,10 +85,8 @@ public class CmdHome extends FCommand { // Create a smoke effect if (Conf.homesTeleportCommandSmokeEffectEnabled) { - List smokeLocations = new ArrayList(); - smokeLocations.add(loc); - smokeLocations.add(loc.add(0, 1, 0)); - smokeLocations.add(myFaction.getHome()); + List smokeLocations = new ArrayList(); smokeLocations.add(loc); + smokeLocations.add(loc.add(0, 1, 0)); smokeLocations.add(myFaction.getHome()); smokeLocations.add(myFaction.getHome().clone().add(0, 1, 0)); SmokeUtil.spawnCloudRandom(smokeLocations, Conf.homesTeleportCommandSmokeEffectThickness); } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java index 0d2bcfc5..0f7c1921 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java @@ -6,31 +6,23 @@ import com.massivecraft.factions.struct.Permission; public class CmdInvite extends FCommand { public CmdInvite() { - super(); - this.aliases.add("invite"); - this.aliases.add("inv"); + super(); this.aliases.add("invite"); this.aliases.add("inv"); this.requiredArgs.add("player name"); //this.optionalArgs.put("", ""); - this.permission = Permission.INVITE.node; - this.disableOnLock = true; + this.permission = Permission.INVITE.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) { return; } + FPlayer you = this.argAsBestFPlayerMatch(0); if (you == null) { return; } if (you.getFaction() == myFaction) { msg("%s is already a member of %s", you.getName(), myFaction.getTag()); - msg("You might want to: " + p.cmdBase.cmdKick.getUseageTemplate(false)); - return; + msg("You might want to: " + p.cmdBase.cmdKick.getUseageTemplate(false)); return; } // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java index 95d4e446..1858a5c6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java @@ -7,37 +7,27 @@ import org.bukkit.Bukkit; public class CmdJoin extends FCommand { public CmdJoin() { - super(); - this.aliases.add("join"); + super(); this.aliases.add("join"); - this.requiredArgs.add("faction name"); - this.optionalArgs.put("player", "you"); + this.requiredArgs.add("faction name"); this.optionalArgs.put("player", "you"); - this.permission = Permission.JOIN.node; - this.disableOnLock = true; + this.permission = Permission.JOIN.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - Faction faction = this.argAsFaction(0); - if (faction == null) { return; } + Faction faction = this.argAsFaction(0); if (faction == null) { return; } - FPlayer fplayer = this.argAsBestFPlayerMatch(1, fme, false); - boolean samePlayer = fplayer == fme; + FPlayer fplayer = this.argAsBestFPlayerMatch(1, fme, false); boolean samePlayer = fplayer == fme; if (!samePlayer && !Permission.JOIN_OTHERS.has(sender, false)) { - msg("You do not have permission to move other players into a faction."); - return; + msg("You do not have permission to move other players into a faction."); return; } if (!faction.isNormal()) { - msg("Players may only join normal factions. This is a system faction."); - return; + msg("Players may only join normal factions. This is a system faction."); return; } if (faction == fplayer.getFaction()) { @@ -56,8 +46,7 @@ public class CmdJoin extends FCommand { } if (!Conf.canLeaveWithNegativePower && fplayer.getPower() < 0) { - msg("%s cannot join a faction with a negative power level.", fplayer.describeTo(fme, true)); - return; + msg("%s cannot join a faction with a negative power level.", fplayer.describeTo(fme, true)); return; } if (!(faction.getOpen() || faction.isInvited(fplayer) || fme.isAdminBypassing() || Permission.JOIN_ANY.has(sender, false))) { @@ -71,8 +60,7 @@ public class CmdJoin extends FCommand { // trigger the join event (cancellable) FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.i.get(me), faction, FPlayerJoinEvent.PlayerJoinReason.COMMAND); - Bukkit.getServer().getPluginManager().callEvent(joinEvent); - if (joinEvent.isCancelled()) { return; } + Bukkit.getServer().getPluginManager().callEvent(joinEvent); if (joinEvent.isCancelled()) { return; } // then make 'em pay (if applicable) if (samePlayer && !payForCommand(Conf.econCostJoin, "to join a faction", "for joining a faction")) { return; } @@ -81,16 +69,12 @@ public class CmdJoin extends FCommand { if (!samePlayer) { fplayer.msg("%s moved you into the faction %s.", fme.describeTo(fplayer, true), faction.getTag(fplayer)); - } - faction.msg("%s joined your faction.", fplayer.describeTo(faction, true)); + } faction.msg("%s joined your faction.", fplayer.describeTo(faction, true)); - fplayer.resetFactionData(); - fplayer.setFaction(faction); - faction.deinvite(fplayer); + fplayer.resetFactionData(); fplayer.setFaction(faction); faction.deinvite(fplayer); if (Conf.logFactionJoin) { - if (samePlayer) { P.p.log("%s joined the faction %s.", fplayer.getName(), faction.getTag()); } - else { + if (samePlayer) { P.p.log("%s joined the faction %s.", fplayer.getName(), faction.getTag()); } else { P.p.log("%s moved the player %s into the faction %s.", fme.getName(), fplayer.getName(), faction.getTag()); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java index 4360278f..781c9a56 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java @@ -12,30 +12,23 @@ import org.bukkit.Bukkit; public class CmdKick extends FCommand { public CmdKick() { - super(); - this.aliases.add("kick"); + super(); this.aliases.add("kick"); this.requiredArgs.add("player name"); //this.optionalArgs.put("", ""); - this.permission = Permission.KICK.node; - this.disableOnLock = false; + this.permission = Permission.KICK.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) { return; } + FPlayer you = this.argAsBestFPlayerMatch(0); if (you == null) { return; } if (fme == you) { msg("You cannot kick yourself."); - msg("You might want to: %s", p.cmdBase.cmdLeave.getUseageTemplate(false)); - return; + msg("You might want to: %s", p.cmdBase.cmdLeave.getUseageTemplate(false)); return; } Faction yourFaction = you.getFaction(); @@ -43,19 +36,16 @@ public class CmdKick extends FCommand { // players with admin-level "disband" permission can bypass these requirements if (!Permission.KICK_ANY.has(sender)) { if (yourFaction != myFaction) { - msg("%s is not a member of %s", you.describeTo(fme, true), myFaction.describeTo(fme)); - return; + msg("%s is not a member of %s", you.describeTo(fme, true), myFaction.describeTo(fme)); return; } if (you.getRole().value >= fme.getRole().value) { // TODO add more informative messages. - msg("Your rank is too low to kick this player."); - return; + msg("Your rank is too low to kick this player."); return; } if (!Conf.canLeaveWithNegativePower && you.getPower() < 0) { - msg("You cannot kick that member until their power is positive."); - return; + msg("You cannot kick that member until their power is positive."); return; } } @@ -64,8 +54,7 @@ public class CmdKick extends FCommand { // trigger the leave event (cancellable) [reason:kicked] FPlayerLeaveEvent event = new FPlayerLeaveEvent(you, you.getFaction(), FPlayerLeaveEvent.PlayerLeaveReason.KICKED); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { return; } + Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; } // then make 'em pay (if applicable) if (!payForCommand(Conf.econCostKick, "to kick someone from the faction", "for kicking someone from the faction")) { @@ -84,8 +73,7 @@ public class CmdKick extends FCommand { if (you.getRole() == Role.ADMIN) { yourFaction.promoteNewLeader(); } - yourFaction.deinvite(you); - you.resetFactionData(); + yourFaction.deinvite(you); you.resetFactionData(); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java b/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java index b5e4273c..e7bb5a22 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java @@ -5,19 +5,14 @@ import com.massivecraft.factions.struct.Permission; public class CmdLeave extends FCommand { public CmdLeave() { - super(); - this.aliases.add("leave"); + super(); this.aliases.add("leave"); //this.requiredArgs.add(""); //this.optionalArgs.put("", ""); - this.permission = Permission.LEAVE.node; - this.disableOnLock = true; + this.permission = Permission.LEAVE.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = true; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdList.java b/src/main/java/com/massivecraft/factions/cmd/CmdList.java index 88b2544e..f26cf1a1 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdList.java @@ -13,19 +13,14 @@ import java.util.Comparator; public class CmdList extends FCommand { public CmdList() { - super(); - this.aliases.add("list"); - this.aliases.add("ls"); + super(); this.aliases.add("list"); this.aliases.add("ls"); //this.requiredArgs.add(""); this.optionalArgs.put("page", "1"); - this.permission = Permission.LIST.node; - this.disableOnLock = false; + this.permission = Permission.LIST.node; this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @@ -35,19 +30,15 @@ public class CmdList extends FCommand { if (!payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) { return; } ArrayList factionList = new ArrayList(Factions.i.get()); - factionList.remove(Factions.i.getNone()); - factionList.remove(Factions.i.getSafeZone()); + factionList.remove(Factions.i.getNone()); factionList.remove(Factions.i.getSafeZone()); factionList.remove(Factions.i.getWarZone()); // Sort by total followers first Collections.sort(factionList, new Comparator() { @Override public int compare(Faction f1, Faction f2) { - int f1Size = f1.getFPlayers().size(); - int f2Size = f2.getFPlayers().size(); - if (f1Size < f2Size) { return 1; } - else if (f1Size > f2Size) { return -1; } - return 0; + int f1Size = f1.getFPlayers().size(); int f2Size = f2.getFPlayers().size(); + if (f1Size < f2Size) { return 1; } else if (f1Size > f2Size) { return -1; } return 0; } }); @@ -57,9 +48,7 @@ public class CmdList extends FCommand { public int compare(Faction f1, Faction f2) { int f1Size = f1.getFPlayersWhereOnline(true).size(); int f2Size = f2.getFPlayersWhereOnline(true).size(); - if (f1Size < f2Size) { return 1; } - else if (f1Size > f2Size) { return -1; } - return 0; + if (f1Size < f2Size) { return 1; } else if (f1Size > f2Size) { return -1; } return 0; } }); @@ -84,13 +73,10 @@ public class CmdList extends FCommand { factionList.add(0, Factions.i.getNone()); - final int pageheight = 9; - int pagenumber = this.argAsInt(0, 1); + final int pageheight = 9; int pagenumber = this.argAsInt(0, 1); int pagecount = (factionList.size() / pageheight) + 1; - if (pagenumber > pagecount) { pagenumber = pagecount; } - else if (pagenumber < 1) { pagenumber = 1; } - int start = (pagenumber - 1) * pageheight; - int end = start + pageheight; + if (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(p.txt.titleize("Faction List " + pagenumber + "/" + pagecount)); @@ -100,14 +86,7 @@ public class CmdList extends FCommand { lines.add(p.txt.parse("Factionless %d online", Factions.i.getNone().getFPlayersWhereOnline(true).size())); continue; } - lines.add(p.txt.parse("%s %d/%d online, %d/%d/%d", - faction.getTag(fme), - faction.getFPlayersWhereOnline(true).size(), - faction.getFPlayers().size(), - faction.getLandRounded(), - faction.getPowerRounded(), - faction.getPowerMaxRounded()) - ); + lines.add(p.txt.parse("%s %d/%d online, %d/%d/%d", faction.getTag(fme), faction.getFPlayersWhereOnline(true).size(), faction.getFPlayers().size(), faction.getLandRounded(), faction.getPowerRounded(), faction.getPowerMaxRounded())); } sendMessage(lines); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdLock.java b/src/main/java/com/massivecraft/factions/cmd/CmdLock.java index e4e5dd9e..2f4e5d38 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLock.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLock.java @@ -12,18 +12,14 @@ public class CmdLock extends FCommand { */ public CmdLock() { - super(); - this.aliases.add("lock"); + super(); this.aliases.add("lock"); //this.requiredArgs.add(""); this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.LOCK.node; - this.disableOnLock = false; + this.permission = Permission.LOCK.node; this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @@ -33,8 +29,7 @@ public class CmdLock extends FCommand { if (p.getLocked()) { msg("Factions is now locked"); - } - else { + } else { msg("Factions in now unlocked"); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMap.java b/src/main/java/com/massivecraft/factions/cmd/CmdMap.java index 5cd32b5d..f3f17cdf 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMap.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMap.java @@ -8,19 +8,14 @@ import com.massivecraft.factions.struct.Permission; public class CmdMap extends FCommand { public CmdMap() { - super(); - this.aliases.add("map"); + super(); this.aliases.add("map"); //this.requiredArgs.add(""); this.optionalArgs.put("on/off", "once"); - this.permission = Permission.MAP.node; - this.disableOnLock = false; + this.permission = Permission.MAP.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override @@ -32,19 +27,15 @@ public class CmdMap extends FCommand { // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay if (!payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) { return; } - fme.setMapAutoUpdating(true); - msg("Map auto update ENABLED."); + fme.setMapAutoUpdating(true); msg("Map auto update ENABLED."); // And show the map once showMap(); - } - else { + } else { // Turn off - fme.setMapAutoUpdating(false); - msg("Map auto update DISABLED."); + fme.setMapAutoUpdating(false); msg("Map auto update DISABLED."); } - } - else { + } else { // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay if (!payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) { return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java index 2db28ad9..7df77ad9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java @@ -8,47 +8,37 @@ import com.massivecraft.factions.struct.Role; public class CmdMod extends FCommand { public CmdMod() { - super(); - this.aliases.add("mod"); + super(); this.aliases.add("mod"); this.requiredArgs.add("player name"); //this.optionalArgs.put("", ""); - this.permission = Permission.MOD.node; - this.disableOnLock = true; + this.permission = Permission.MOD.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) { return; } + FPlayer you = this.argAsBestFPlayerMatch(0); if (you == null) { return; } - boolean permAny = Permission.MOD_ANY.has(sender, false); - Faction targetFaction = you.getFaction(); + boolean permAny = Permission.MOD_ANY.has(sender, false); Faction targetFaction = you.getFaction(); if (targetFaction != myFaction && !permAny) { - msg("%s is not a member in your faction.", you.describeTo(fme, true)); - return; + msg("%s is not a member in your faction.", you.describeTo(fme, true)); return; } if (fme != null && fme.getRole() != Role.ADMIN && !permAny) { - msg("You are not the faction admin."); - return; + msg("You are not the faction admin."); return; } if (you == fme && !permAny) { - msg("The target player musn't be yourself."); - return; + msg("The target player musn't be yourself."); return; } if (you.getRole() == Role.ADMIN) { - msg("The target player is a faction admin. Demote them first."); - return; + msg("The target player is a faction admin. Demote them first."); return; } if (you.getRole() == Role.MODERATOR) { @@ -56,8 +46,7 @@ public class CmdMod extends FCommand { you.setRole(Role.NORMAL); targetFaction.msg("%s is no longer moderator in your faction.", you.describeTo(targetFaction, true)); msg("You have removed moderator status from %s.", you.describeTo(fme, true)); - } - else { + } else { // Give you.setRole(Role.MODERATOR); targetFaction.msg("%s was promoted to moderator in your faction.", you.describeTo(targetFaction, true)); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java index ea7f81c3..c46049dc 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java @@ -11,34 +11,27 @@ public class CmdMoney extends FCommand { public CmdMoneyTransferPf cmdMoneyTransferPf = new CmdMoneyTransferPf(); public CmdMoney() { - super(); - this.aliases.add("money"); + super(); this.aliases.add("money"); //this.requiredArgs.add(""); //this.optionalArgs.put("","") this.isMoneyCommand = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; this.setHelpShort("faction money commands"); this.helpLong.add(p.txt.parseTags("The faction money commands.")); - this.addSubCommand(this.cmdMoneyBalance); - this.addSubCommand(this.cmdMoneyDeposit); - this.addSubCommand(this.cmdMoneyWithdraw); - this.addSubCommand(this.cmdMoneyTransferFf); - this.addSubCommand(this.cmdMoneyTransferFp); - this.addSubCommand(this.cmdMoneyTransferPf); + this.addSubCommand(this.cmdMoneyBalance); this.addSubCommand(this.cmdMoneyDeposit); + this.addSubCommand(this.cmdMoneyWithdraw); this.addSubCommand(this.cmdMoneyTransferFf); + this.addSubCommand(this.cmdMoneyTransferFp); this.addSubCommand(this.cmdMoneyTransferPf); } @Override public void perform() { - this.commandChain.add(this); - P.p.cmdAutoHelp.execute(this.sender, this.args, this.commandChain); + this.commandChain.add(this); P.p.cmdAutoHelp.execute(this.sender, this.args, this.commandChain); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java index 97536911..ef2c904a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java @@ -6,26 +6,20 @@ import com.massivecraft.factions.struct.Permission; public class CmdMoneyBalance extends FCommand { public CmdMoneyBalance() { - super(); - this.aliases.add("b"); - this.aliases.add("balance"); + super(); this.aliases.add("b"); this.aliases.add("balance"); //this.requiredArgs.add(""); this.optionalArgs.put("faction", "yours"); - this.permission = Permission.MONEY_BALANCE.node; - this.setHelpShort("show faction balance"); + this.permission = Permission.MONEY_BALANCE.node; this.setHelpShort("show faction balance"); - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - Faction faction = myFaction; - if (this.argIsSet(0)) { + Faction faction = myFaction; if (this.argIsSet(0)) { faction = this.argAsFaction(0); } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java index 1d2964ea..ac710b28 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java @@ -11,28 +11,19 @@ import org.bukkit.ChatColor; public class CmdMoneyDeposit extends FCommand { public CmdMoneyDeposit() { - super(); - this.aliases.add("d"); - this.aliases.add("deposit"); + super(); this.aliases.add("d"); this.aliases.add("deposit"); - this.requiredArgs.add("amount"); - this.optionalArgs.put("faction", "yours"); + this.requiredArgs.add("amount"); this.optionalArgs.put("faction", "yours"); - this.permission = Permission.MONEY_DEPOSIT.node; - this.setHelpShort("deposit money"); + this.permission = Permission.MONEY_DEPOSIT.node; this.setHelpShort("deposit money"); - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator faction = this.argAsFaction(1, myFaction); - if (faction == null) { return; } - boolean success = Econ.transferMoney(fme, fme, faction, amount); + double amount = this.argAsDouble(0, 0d); EconomyParticipator faction = this.argAsFaction(1, myFaction); + if (faction == null) { return; } boolean success = Econ.transferMoney(fme, fme, faction, amount); if (success && Conf.logMoneyTransactions) { P.p.log(ChatColor.stripColor(P.p.txt.parse("%s deposited %s in the faction bank: %s", fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java index 91ccb32d..1dc86f4c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java @@ -12,28 +12,20 @@ public class CmdMoneyTransferFf extends FCommand { public CmdMoneyTransferFf() { this.aliases.add("ff"); - this.requiredArgs.add("amount"); - this.requiredArgs.add("faction"); - this.requiredArgs.add("faction"); + this.requiredArgs.add("amount"); this.requiredArgs.add("faction"); this.requiredArgs.add("faction"); //this.optionalArgs.put("", ""); - this.permission = Permission.MONEY_F2F.node; - this.setHelpShort("transfer f -> f"); + this.permission = Permission.MONEY_F2F.node; this.setHelpShort("transfer f -> f"); - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsFaction(1); - if (from == null) { return; } - EconomyParticipator to = this.argAsFaction(2); - if (to == null) { return; } + double amount = this.argAsDouble(0, 0d); EconomyParticipator from = this.argAsFaction(1); + if (from == null) { return; } EconomyParticipator to = this.argAsFaction(2); if (to == null) { return; } boolean success = Econ.transferMoney(fme, from, to, amount); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java index 55023248..9ddf6604 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java @@ -12,27 +12,20 @@ public class CmdMoneyTransferFp extends FCommand { public CmdMoneyTransferFp() { this.aliases.add("fp"); - this.requiredArgs.add("amount"); - this.requiredArgs.add("faction"); - this.requiredArgs.add("player"); + this.requiredArgs.add("amount"); this.requiredArgs.add("faction"); this.requiredArgs.add("player"); //this.optionalArgs.put("", ""); - this.permission = Permission.MONEY_F2P.node; - this.setHelpShort("transfer f -> p"); + this.permission = Permission.MONEY_F2P.node; this.setHelpShort("transfer f -> p"); - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsFaction(1); - if (from == null) { return; } - EconomyParticipator to = this.argAsBestFPlayerMatch(2); + double amount = this.argAsDouble(0, 0d); EconomyParticipator from = this.argAsFaction(1); + if (from == null) { return; } EconomyParticipator to = this.argAsBestFPlayerMatch(2); if (to == null) { return; } boolean success = Econ.transferMoney(fme, from, to, amount); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java index 41155cec..8c635029 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java @@ -12,28 +12,20 @@ public class CmdMoneyTransferPf extends FCommand { public CmdMoneyTransferPf() { this.aliases.add("pf"); - this.requiredArgs.add("amount"); - this.requiredArgs.add("player"); - this.requiredArgs.add("faction"); + this.requiredArgs.add("amount"); this.requiredArgs.add("player"); this.requiredArgs.add("faction"); //this.optionalArgs.put("", ""); - this.permission = Permission.MONEY_P2F.node; - this.setHelpShort("transfer p -> f"); + this.permission = Permission.MONEY_P2F.node; this.setHelpShort("transfer p -> f"); - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsBestFPlayerMatch(1); - if (from == null) { return; } - EconomyParticipator to = this.argAsFaction(2); - if (to == null) { return; } + double amount = this.argAsDouble(0, 0d); EconomyParticipator from = this.argAsBestFPlayerMatch(1); + if (from == null) { return; } EconomyParticipator to = this.argAsFaction(2); if (to == null) { return; } boolean success = Econ.transferMoney(fme, from, to, amount); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java index df5057fa..e514f770 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java @@ -10,27 +10,19 @@ import org.bukkit.ChatColor; public class CmdMoneyWithdraw extends FCommand { public CmdMoneyWithdraw() { - this.aliases.add("w"); - this.aliases.add("withdraw"); + this.aliases.add("w"); this.aliases.add("withdraw"); - this.requiredArgs.add("amount"); - this.optionalArgs.put("faction", "yours"); + this.requiredArgs.add("amount"); this.optionalArgs.put("faction", "yours"); - this.permission = Permission.MONEY_WITHDRAW.node; - this.setHelpShort("withdraw money"); + this.permission = Permission.MONEY_WITHDRAW.node; this.setHelpShort("withdraw money"); - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator faction = this.argAsFaction(1, myFaction); - if (faction == null) { return; } - boolean success = Econ.transferMoney(fme, faction, fme, amount); + double amount = this.argAsDouble(0, 0d); EconomyParticipator faction = this.argAsFaction(1, myFaction); + if (faction == null) { return; } boolean success = Econ.transferMoney(fme, faction, fme, amount); if (success && Conf.logMoneyTransactions) { P.p.log(ChatColor.stripColor(P.p.txt.parse("%s withdrew %s from the faction bank: %s", fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java index a71254fe..4be5bf00 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java @@ -7,19 +7,14 @@ import com.massivecraft.factions.struct.Permission; public class CmdOpen extends FCommand { public CmdOpen() { - super(); - this.aliases.add("open"); + super(); this.aliases.add("open"); //this.requiredArgs.add(""); this.optionalArgs.put("yes/no", "flip"); - this.permission = Permission.OPEN.node; - this.disableOnLock = false; + this.permission = Permission.OPEN.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override @@ -38,8 +33,7 @@ public class CmdOpen extends FCommand { for (Faction faction : Factions.i.get()) { if (faction == myFaction) { continue; - } - faction.msg("The faction %s is now %s", myFaction.getTag(faction), open); + } faction.msg("The faction %s is now %s", myFaction.getTag(faction), open); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java b/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java index 9223e955..d0d1a818 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java @@ -8,19 +8,14 @@ import com.massivecraft.factions.struct.Role; public class CmdOwner extends FCommand { public CmdOwner() { - super(); - this.aliases.add("owner"); + super(); this.aliases.add("owner"); //this.requiredArgs.add(""); this.optionalArgs.put("player name", "you"); - this.permission = Permission.OWNER.node; - this.disableOnLock = true; + this.permission = Permission.OWNER.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } // TODO: Fix colors! @@ -34,8 +29,7 @@ public class CmdOwner extends FCommand { } if (!Conf.ownedAreasEnabled) { - fme.msg("Sorry, but owned areas are disabled on this server."); - return; + fme.msg("Sorry, but owned areas are disabled on this server."); return; } if (!hasBypass && Conf.ownedAreasLimitPerFaction > 0 && myFaction.getCountOfClaimsWithOwners() >= Conf.ownedAreasLimitPerFaction) { @@ -49,40 +43,33 @@ public class CmdOwner extends FCommand { FLocation flocation = new FLocation(fme); - Faction factionHere = Board.getFactionAt(flocation); - if (factionHere != myFaction) { + Faction factionHere = Board.getFactionAt(flocation); if (factionHere != myFaction) { if (!hasBypass) { - fme.msg("This land is not claimed by your faction, so you can't set ownership of it."); - return; + fme.msg("This land is not claimed by your faction, so you can't set ownership of it."); return; } if (!factionHere.isNormal()) { - fme.msg("This land is not claimed by a faction. Ownership is not possible."); - return; + fme.msg("This land is not claimed by a faction. Ownership is not possible."); return; } } - FPlayer target = this.argAsBestFPlayerMatch(0, fme); - if (target == null) { return; } + FPlayer target = this.argAsBestFPlayerMatch(0, fme); if (target == null) { return; } String playerName = target.getName(); if (target.getFaction() != myFaction) { - fme.msg("%s is not a member of this faction.", playerName); - return; + fme.msg("%s is not a member of this faction.", playerName); return; } // if no player name was passed, and this claim does already have owners set, clear them if (args.isEmpty() && myFaction.doesLocationHaveOwnersSet(flocation)) { - myFaction.clearClaimOwnership(flocation); - fme.msg("You have cleared ownership for this claimed area."); + myFaction.clearClaimOwnership(flocation); fme.msg("You have cleared ownership for this claimed area."); return; } if (myFaction.isPlayerInOwnerList(target, flocation)) { myFaction.removePlayerAsOwner(target, flocation); - fme.msg("You have removed ownership of this claimed land from %s.", playerName); - return; + fme.msg("You have removed ownership of this claimed land from %s.", playerName); return; } // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java b/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java index a749453b..29ec4512 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java @@ -9,19 +9,14 @@ import com.massivecraft.factions.struct.Permission; public class CmdOwnerList extends FCommand { public CmdOwnerList() { - super(); - this.aliases.add("ownerlist"); + super(); this.aliases.add("ownerlist"); //this.requiredArgs.add(""); //this.optionalArgs.put("", ""); - this.permission = Permission.OWNERLIST.node; - this.disableOnLock = false; + this.permission = Permission.OWNERLIST.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override @@ -33,30 +28,25 @@ public class CmdOwnerList extends FCommand { } if (!Conf.ownedAreasEnabled) { - fme.msg("Owned areas are disabled on this server."); - return; + fme.msg("Owned areas are disabled on this server."); return; } FLocation flocation = new FLocation(fme); if (Board.getFactionAt(flocation) != myFaction) { if (!hasBypass) { - fme.msg("This land is not claimed by your faction."); - return; + fme.msg("This land is not claimed by your faction."); return; } - myFaction = Board.getFactionAt(flocation); - if (!myFaction.isNormal()) { - fme.msg("This land is not claimed by any faction, thus no owners."); - return; + myFaction = Board.getFactionAt(flocation); if (!myFaction.isNormal()) { + fme.msg("This land is not claimed by any faction, thus no owners."); return; } } String owners = myFaction.getOwnerListString(flocation); if (owners == null || owners.isEmpty()) { - fme.msg("No owners are set here; everyone in the faction has access."); - return; + fme.msg("No owners are set here; everyone in the faction has access."); return; } fme.msg("Current owner(s) of this land: %s", owners); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java b/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java index 202351a7..9da31f68 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java @@ -8,42 +8,32 @@ import com.massivecraft.factions.struct.Permission; public class CmdPeaceful extends FCommand { public CmdPeaceful() { - super(); - this.aliases.add("peaceful"); + super(); this.aliases.add("peaceful"); this.requiredArgs.add("faction tag"); //this.optionalArgs.put("", ""); - this.permission = Permission.SET_PEACEFUL.node; - this.disableOnLock = true; + this.permission = Permission.SET_PEACEFUL.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - Faction faction = this.argAsFaction(0); - if (faction == null) { return; } + Faction faction = this.argAsFaction(0); if (faction == null) { return; } - String change; - if (faction.isPeaceful()) { - change = "removed peaceful status from"; - faction.setPeaceful(false); - } - else { - change = "granted peaceful status to"; - faction.setPeaceful(true); + String change; if (faction.isPeaceful()) { + change = "removed peaceful status from"; faction.setPeaceful(false); + } else { + change = "granted peaceful status to"; faction.setPeaceful(true); } // Inform all players for (FPlayer fplayer : FPlayers.i.getOnline()) { if (fplayer.getFaction() == faction) { fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " has " + change + " your faction."); - } - else { + } else { fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " has " + change + " the faction \"" + faction.getTag(fplayer) + "\"."); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java b/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java index 3d0a2fa4..2fd80d25 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java @@ -9,34 +9,25 @@ import com.massivecraft.factions.struct.Permission; public class CmdPermanent extends FCommand { public CmdPermanent() { - super(); - this.aliases.add("permanent"); + super(); this.aliases.add("permanent"); this.requiredArgs.add("faction tag"); //this.optionalArgs.put("", ""); - this.permission = Permission.SET_PERMANENT.node; - this.disableOnLock = true; + this.permission = Permission.SET_PERMANENT.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - Faction faction = this.argAsFaction(0); - if (faction == null) { return; } + Faction faction = this.argAsFaction(0); if (faction == null) { return; } - String change; - if (faction.isPermanent()) { - change = "removed permanent status from"; - faction.setPermanent(false); - } - else { - change = "added permanent status to"; - faction.setPermanent(true); + String change; if (faction.isPermanent()) { + change = "removed permanent status from"; faction.setPermanent(false); + } else { + change = "added permanent status to"; faction.setPermanent(true); } P.p.log((fme == null ? "A server admin" : fme.getName()) + " " + change + " the faction \"" + faction.getTag() + "\"."); @@ -45,8 +36,7 @@ public class CmdPermanent extends FCommand { for (FPlayer fplayer : FPlayers.i.getOnline()) { if (fplayer.getFaction() == faction) { fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " " + change + " your faction."); - } - else { + } else { fplayer.msg((fme == null ? "A server admin" : fme.describeTo(fplayer, true)) + " " + change + " the faction \"" + faction.getTag(fplayer) + "\"."); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java b/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java index dd95b4e3..488f3870 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java @@ -6,32 +6,25 @@ import com.massivecraft.factions.struct.Permission; public class CmdPermanentPower extends FCommand { public CmdPermanentPower() { - super(); - this.aliases.add("permanentpower"); + super(); this.aliases.add("permanentpower"); - this.requiredArgs.add("faction"); - this.optionalArgs.put("power", "reset"); + this.requiredArgs.add("faction"); this.optionalArgs.put("power", "reset"); - this.permission = Permission.SET_PERMANENTPOWER.node; - this.disableOnLock = true; + this.permission = Permission.SET_PERMANENTPOWER.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - Faction targetFaction = this.argAsFaction(0); - if (targetFaction == null) { return; } + Faction targetFaction = this.argAsFaction(0); if (targetFaction == null) { return; } Integer targetPower = this.argAsInt(1); targetFaction.setPermanentPower(targetPower); - String change = "removed permanentpower status from"; - if (targetFaction.hasPermanentPower()) { + String change = "removed permanentpower status from"; if (targetFaction.hasPermanentPower()) { change = "added permanentpower status to"; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPower.java b/src/main/java/com/massivecraft/factions/cmd/CmdPower.java index 4ec19b42..e2db209b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPower.java @@ -7,26 +7,20 @@ import com.massivecraft.factions.struct.Permission; public class CmdPower extends FCommand { public CmdPower() { - super(); - this.aliases.add("power"); - this.aliases.add("pow"); + super(); this.aliases.add("power"); this.aliases.add("pow"); //this.requiredArgs.add("faction tag"); this.optionalArgs.put("player name", "you"); - this.permission = Permission.POWER.node; - this.disableOnLock = false; + this.permission = Permission.POWER.node; this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - FPlayer target = this.argAsBestFPlayerMatch(0, fme); - if (target == null) { return; } + FPlayer target = this.argAsBestFPlayerMatch(0, fme); if (target == null) { return; } if (target != fme && !Permission.POWER_ANY.has(sender, true)) { return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java b/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java index a887690e..8e4a0cf1 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java @@ -7,54 +7,38 @@ import com.massivecraft.factions.struct.Permission; public class CmdPowerBoost extends FCommand { public CmdPowerBoost() { - super(); - this.aliases.add("powerboost"); + super(); this.aliases.add("powerboost"); - this.requiredArgs.add("p|f|player|faction"); - this.requiredArgs.add("name"); - this.requiredArgs.add("#"); + this.requiredArgs.add("p|f|player|faction"); this.requiredArgs.add("name"); this.requiredArgs.add("#"); - this.permission = Permission.POWERBOOST.node; - this.disableOnLock = true; + this.permission = Permission.POWERBOOST.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - String type = this.argAsString(0).toLowerCase(); - boolean doPlayer = true; + String type = this.argAsString(0).toLowerCase(); boolean doPlayer = true; if (type.equals("f") || type.equals("faction")) { doPlayer = false; - } - else if (!type.equals("p") && !type.equals("player")) { + } else if (!type.equals("p") && !type.equals("player")) { msg("You must specify \"p\" or \"player\" to target a player or \"f\" or \"faction\" to target a faction."); - msg("ex. /f powerboost p SomePlayer 0.5 -or- /f powerboost f SomeFaction -5"); - return; + msg("ex. /f powerboost p SomePlayer 0.5 -or- /f powerboost f SomeFaction -5"); return; } - Double targetPower = this.argAsDouble(2); - if (targetPower == null) { - msg("You must specify a valid numeric value for the power bonus/penalty amount."); - return; + Double targetPower = this.argAsDouble(2); if (targetPower == null) { + msg("You must specify a valid numeric value for the power bonus/penalty amount."); return; } String target; if (doPlayer) { - FPlayer targetPlayer = this.argAsBestFPlayerMatch(1); - if (targetPlayer == null) { return; } - targetPlayer.setPowerBoost(targetPower); - target = "Player \"" + targetPlayer.getName() + "\""; - } - else { - Faction targetFaction = this.argAsFaction(1); - if (targetFaction == null) { return; } - targetFaction.setPowerBoost(targetPower); - target = "Faction \"" + targetFaction.getTag() + "\""; + FPlayer targetPlayer = this.argAsBestFPlayerMatch(1); if (targetPlayer == null) { return; } + targetPlayer.setPowerBoost(targetPower); target = "Player \"" + targetPlayer.getName() + "\""; + } else { + Faction targetFaction = this.argAsFaction(1); if (targetFaction == null) { return; } + targetFaction.setPowerBoost(targetPower); target = "Faction \"" + targetFaction.getTag() + "\""; } msg("" + target + " now has a power bonus/penalty of " + targetPower + " to min and max power levels."); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java index fa597730..fab47ed3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java @@ -4,7 +4,6 @@ import com.massivecraft.factions.struct.Relation; public class CmdRelationAlly extends FRelationCommand { public CmdRelationAlly() { - aliases.add("ally"); - targetRelation = Relation.ALLY; + aliases.add("ally"); targetRelation = Relation.ALLY; } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java index 4a22aa00..aa5edbd9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java @@ -4,7 +4,6 @@ import com.massivecraft.factions.struct.Relation; public class CmdRelationEnemy extends FRelationCommand { public CmdRelationEnemy() { - aliases.add("enemy"); - targetRelation = Relation.ENEMY; + aliases.add("enemy"); targetRelation = Relation.ENEMY; } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java index db340ed6..d78afcce 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java @@ -4,7 +4,6 @@ import com.massivecraft.factions.struct.Relation; public class CmdRelationNeutral extends FRelationCommand { public CmdRelationNeutral() { - aliases.add("neutral"); - targetRelation = Relation.NEUTRAL; + aliases.add("neutral"); targetRelation = Relation.NEUTRAL; } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdReload.java b/src/main/java/com/massivecraft/factions/cmd/CmdReload.java index 422c91b6..b6ef9073 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdReload.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdReload.java @@ -6,55 +6,36 @@ import com.massivecraft.factions.struct.Permission; public class CmdReload extends FCommand { public CmdReload() { - super(); - this.aliases.add("reload"); + super(); this.aliases.add("reload"); //this.requiredArgs.add(""); this.optionalArgs.put("file", "all"); - this.permission = Permission.RELOAD.node; - this.disableOnLock = false; + this.permission = Permission.RELOAD.node; this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - long timeInitStart = System.currentTimeMillis(); - String file = this.argAsString(0, "all").toLowerCase(); + long timeInitStart = System.currentTimeMillis(); String file = this.argAsString(0, "all").toLowerCase(); String fileName; if (file.startsWith("c")) { - Conf.load(); - fileName = "conf.json"; - } - else if (file.startsWith("b")) { - Board.load(); - fileName = "board.json"; - } - else if (file.startsWith("f")) { - Factions.i.loadFromDisc(); - fileName = "factions.json"; - } - else if (file.startsWith("p")) { - FPlayers.i.loadFromDisc(); - fileName = "players.json"; - } - else if (file.startsWith("a")) { - fileName = "all"; - Conf.load(); - FPlayers.i.loadFromDisc(); - Factions.i.loadFromDisc(); - Board.load(); - } - else { + Conf.load(); fileName = "conf.json"; + } else if (file.startsWith("b")) { + Board.load(); fileName = "board.json"; + } else if (file.startsWith("f")) { + Factions.i.loadFromDisc(); fileName = "factions.json"; + } else if (file.startsWith("p")) { + FPlayers.i.loadFromDisc(); fileName = "players.json"; + } else if (file.startsWith("a")) { + fileName = "all"; Conf.load(); FPlayers.i.loadFromDisc(); Factions.i.loadFromDisc(); Board.load(); + } else { P.p.log("RELOAD CANCELLED - SPECIFIED FILE INVALID"); - msg("Invalid file specified. Valid files: all, conf, board, factions, players"); - return; + msg("Invalid file specified. Valid files: all, conf, board, factions, players"); return; } long timeReload = (System.currentTimeMillis() - timeInitStart); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java index 9ab3eed3..cd5a56a4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java @@ -9,18 +9,14 @@ import com.massivecraft.factions.struct.Permission; public class CmdSafeunclaimall extends FCommand { public CmdSafeunclaimall() { - this.aliases.add("safeunclaimall"); - this.aliases.add("safedeclaimall"); + this.aliases.add("safeunclaimall"); this.aliases.add("safedeclaimall"); //this.requiredArgs.add(""); //this.optionalArgs.put("radius", "0"); - this.permission = Permission.MANAGE_SAFE_ZONE.node; - this.disableOnLock = true; + this.permission = Permission.MANAGE_SAFE_ZONE.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; this.setHelpShort("Unclaim all safezone land"); @@ -28,8 +24,7 @@ public class CmdSafeunclaimall extends FCommand { @Override public void perform() { - Board.unclaimAll(Factions.i.getSafeZone().getId()); - msg("You unclaimed ALL safe zone land."); + Board.unclaimAll(Factions.i.getSafeZone().getId()); msg("You unclaimed ALL safe zone land."); if (Conf.logLandUnclaims) { P.p.log(fme.getName() + " unclaimed all safe zones."); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java b/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java index 1316f969..b69cea0d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java @@ -9,29 +9,20 @@ import com.massivecraft.factions.struct.Permission; public class CmdSaveAll extends FCommand { public CmdSaveAll() { - super(); - this.aliases.add("saveall"); - this.aliases.add("save"); + super(); this.aliases.add("saveall"); this.aliases.add("save"); //this.requiredArgs.add(""); //this.optionalArgs.put("", ""); - this.permission = Permission.SAVE.node; - this.disableOnLock = false; + this.permission = Permission.SAVE.node; this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - FPlayers.i.saveToDisc(); - Factions.i.saveToDisc(); - Board.save(); - Conf.save(); - msg("Factions saved to disk!"); + FPlayers.i.saveToDisc(); Factions.i.saveToDisc(); Board.save(); Conf.save(); msg("Factions saved to disk!"); } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java b/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java index 13768da2..7aef6164 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java @@ -14,44 +14,31 @@ public class CmdSethome extends FCommand { //this.requiredArgs.add(""); this.optionalArgs.put("faction tag", "mine"); - this.permission = Permission.SETHOME.node; - this.disableOnLock = true; + this.permission = Permission.SETHOME.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { if (!Conf.homesEnabled) { - fme.msg("Sorry, Faction homes are disabled on this server."); - return; + fme.msg("Sorry, Faction homes are disabled on this server."); return; } - Faction faction = this.argAsFaction(0, myFaction); - if (faction == null) { return; } + Faction faction = this.argAsFaction(0, myFaction); if (faction == null) { return; } // Can the player set the home for this faction? if (faction == myFaction) { if (!Permission.SETHOME_ANY.has(sender) && !assertMinRole(Role.MODERATOR)) { return; } - } - else { + } else { if (!Permission.SETHOME_ANY.has(sender, true)) { return; } } // Can the player set the faction home HERE? - if - ( - !Permission.BYPASS.has(me) - && - Conf.homesMustBeInClaimedTerritory - && - Board.getFactionAt(new FLocation(me)) != faction - ) { - fme.msg("Sorry, your faction home can only be set inside your own claimed territory."); - return; + if (!Permission.BYPASS.has(me) && + Conf.homesMustBeInClaimedTerritory && + Board.getFactionAt(new FLocation(me)) != faction) { + fme.msg("Sorry, your faction home can only be set inside your own claimed territory."); return; } // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay @@ -60,8 +47,7 @@ public class CmdSethome extends FCommand { faction.setHome(me.getLocation()); faction.msg("%s set the home for your faction. You can now use:", fme.describeTo(myFaction, true)); - faction.sendMessage(p.cmdBase.cmdHome.getUseageTemplate()); - if (faction != myFaction) { + faction.sendMessage(p.cmdBase.cmdHome.getUseageTemplate()); if (faction != myFaction) { fme.msg("You have set the home for the " + faction.getTag(fme) + " faction."); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdShow.java b/src/main/java/com/massivecraft/factions/cmd/CmdShow.java index 468cad6f..a53f2442 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdShow.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdShow.java @@ -14,27 +14,20 @@ import java.util.Collection; public class CmdShow extends FCommand { public CmdShow() { - this.aliases.add("show"); - this.aliases.add("who"); + this.aliases.add("show"); this.aliases.add("who"); //this.requiredArgs.add(""); this.optionalArgs.put("faction tag", "yours"); - this.permission = Permission.SHOW.node; - this.disableOnLock = false; + this.permission = Permission.SHOW.node; this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - Faction faction = myFaction; - if (this.argIsSet(0)) { - faction = this.argAsFaction(0); - if (faction == null) { return; } + Faction faction = myFaction; if (this.argIsSet(0)) { + faction = this.argAsFaction(0); if (faction == null) { return; } } // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay @@ -46,14 +39,12 @@ public class CmdShow extends FCommand { Collection mods = faction.getFPlayersWhereRole(Role.MODERATOR); Collection normals = faction.getFPlayersWhereRole(Role.NORMAL); - msg(p.txt.titleize(faction.getTag(fme))); - msg("Description: %s", faction.getDescription()); + msg(p.txt.titleize(faction.getTag(fme))); msg("Description: %s", faction.getDescription()); if (!faction.isNormal()) { return; } - String peaceStatus = ""; - if (faction.isPeaceful()) { + String peaceStatus = ""; if (faction.isPeaceful()) { peaceStatus = " " + Conf.colorNeutral + "This faction is Peaceful"; } @@ -70,8 +61,7 @@ public class CmdShow extends FCommand { // show the land value if (Econ.shouldBeUsed()) { double value = Econ.calculateTotalLandValue(faction.getLandRounded()); - double refund = value * Conf.econClaimRefundMultiplier; - if (value > 0) { + double refund = value * Conf.econClaimRefundMultiplier; if (value > 0) { String stringValue = Econ.moneyString(value); String stringRefund = (refund > 0.0) ? (" (" + Econ.moneyString(refund) + " depreciated)") : ""; msg("Total land value: " + stringValue + stringRefund); @@ -86,67 +76,53 @@ public class CmdShow extends FCommand { String listpart; // List relation - String allyList = p.txt.parse("Allies: "); - String enemyList = p.txt.parse("Enemies: "); + String allyList = p.txt.parse("Allies: "); String enemyList = p.txt.parse("Enemies: "); for (Faction otherFaction : Factions.i.get()) { if (otherFaction == faction) { continue; } - Relation rel = otherFaction.getRelationTo(faction); - if (!rel.isAlly() && !rel.isEnemy()) { + Relation rel = otherFaction.getRelationTo(faction); if (!rel.isAlly() && !rel.isEnemy()) { continue; // if not ally or enemy, drop out now so we're not wasting time on it; good performance boost } listpart = otherFaction.getTag(fme) + p.txt.parse("") + ", "; - if (rel.isAlly()) { allyList += listpart; } - else if (rel.isEnemy()) { enemyList += listpart; } - } - if (allyList.endsWith(", ")) { allyList = allyList.substring(0, allyList.length() - 2); } + if (rel.isAlly()) { allyList += listpart; } else if (rel.isEnemy()) { enemyList += listpart; } + } if (allyList.endsWith(", ")) { allyList = allyList.substring(0, allyList.length() - 2); } if (enemyList.endsWith(", ")) { enemyList = enemyList.substring(0, enemyList.length() - 2); } - sendMessage(allyList); - sendMessage(enemyList); + sendMessage(allyList); sendMessage(enemyList); // List the members... String onlineList = p.txt.parse("") + "Members online: "; - String offlineList = p.txt.parse("") + "Members offline: "; - for (FPlayer follower : admins) { + String offlineList = p.txt.parse("") + "Members offline: "; for (FPlayer follower : admins) { listpart = follower.getNameAndTitle(fme) + p.txt.parse("") + ", "; if (follower.isOnlineAndVisibleTo(me)) { onlineList += listpart; - } - else { + } else { offlineList += listpart; } - } - for (FPlayer follower : mods) { - listpart = follower.getNameAndTitle(fme) + p.txt.parse("") + ", "; - if - (follower.isOnlineAndVisibleTo(me)) { - onlineList += listpart; - } - else { - offlineList += listpart; - } - } - for (FPlayer follower : normals) { + } for (FPlayer follower : mods) { listpart = follower.getNameAndTitle(fme) + p.txt.parse("") + ", "; if (follower.isOnlineAndVisibleTo(me)) { onlineList += listpart; + } else { + offlineList += listpart; } - else { + } for (FPlayer follower : normals) { + listpart = follower.getNameAndTitle(fme) + p.txt.parse("") + ", "; + if (follower.isOnlineAndVisibleTo(me)) { + onlineList += listpart; + } else { offlineList += listpart; } } if (onlineList.endsWith(", ")) { onlineList = onlineList.substring(0, onlineList.length() - 2); - } - if (offlineList.endsWith(", ")) { + } if (offlineList.endsWith(", ")) { offlineList = offlineList.substring(0, offlineList.length() - 2); } - sendMessage(onlineList); - sendMessage(offlineList); + sendMessage(onlineList); sendMessage(offlineList); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java index ba10f671..98b191d0 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java @@ -18,13 +18,9 @@ public class CmdTag extends FCommand { this.requiredArgs.add("faction tag"); //this.optionalArgs.put("", ""); - this.permission = Permission.TAG.node; - this.disableOnLock = true; + this.permission = Permission.TAG.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override @@ -33,15 +29,12 @@ public class CmdTag extends FCommand { // TODO does not first test cover selfcase? if (Factions.i.isTagTaken(tag) && !MiscUtil.getComparisonString(tag).equals(myFaction.getComparisonTag())) { - msg("That tag is already taken"); - return; + msg("That tag is already taken"); return; } - ArrayList errors = new ArrayList(); - errors.addAll(Factions.validateTag(tag)); + ArrayList errors = new ArrayList(); errors.addAll(Factions.validateTag(tag)); if (errors.size() > 0) { - sendMessage(errors); - return; + 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 @@ -49,14 +42,12 @@ public class CmdTag extends FCommand { // trigger the faction rename event (cancellable) FactionRenameEvent renameEvent = new FactionRenameEvent(fme, tag); - Bukkit.getServer().getPluginManager().callEvent(renameEvent); - if (renameEvent.isCancelled()) { return; } + Bukkit.getServer().getPluginManager().callEvent(renameEvent); if (renameEvent.isCancelled()) { return; } // then make 'em pay (if applicable) if (!payForCommand(Conf.econCostTag, "to change the faction tag", "for changing the faction tag")) { return; } - String oldtag = myFaction.getTag(); - myFaction.setTag(tag); + String oldtag = myFaction.getTag(); myFaction.setTag(tag); // Inform myFaction.msg("%s changed your faction tag to %s", fme.describeTo(myFaction, true), myFaction.getTag(myFaction)); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java b/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java index 7b63646c..cf30fbd6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java @@ -9,25 +9,18 @@ public class CmdTitle extends FCommand { public CmdTitle() { this.aliases.add("title"); - this.requiredArgs.add("player name"); - this.optionalArgs.put("title", ""); + this.requiredArgs.add("player name"); this.optionalArgs.put("title", ""); - this.permission = Permission.TITLE.node; - this.disableOnLock = true; + this.permission = Permission.TITLE.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) { return; } + FPlayer you = this.argAsBestFPlayerMatch(0); if (you == null) { return; } - args.remove(0); - String title = TextUtil.implode(args, " "); + args.remove(0); String title = TextUtil.implode(args, " "); if (!canIAdministerYou(fme, you)) { return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java index 96aae58e..5c367381 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java @@ -9,53 +9,40 @@ import org.bukkit.Bukkit; public class CmdUnclaim extends FCommand { public CmdUnclaim() { - this.aliases.add("unclaim"); - this.aliases.add("declaim"); + this.aliases.add("unclaim"); this.aliases.add("declaim"); //this.requiredArgs.add(""); //this.optionalArgs.put("", ""); - this.permission = Permission.UNCLAIM.node; - this.disableOnLock = true; + this.permission = Permission.UNCLAIM.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void perform() { - FLocation flocation = new FLocation(fme); - Faction otherFaction = Board.getFactionAt(flocation); + FLocation flocation = new FLocation(fme); Faction otherFaction = Board.getFactionAt(flocation); if (otherFaction.isSafeZone()) { if (Permission.MANAGE_SAFE_ZONE.has(sender)) { - Board.removeAt(flocation); - msg("Safe zone was unclaimed."); + Board.removeAt(flocation); msg("Safe zone was unclaimed."); if (Conf.logLandUnclaims) { P.p.log(fme.getName() + " unclaimed land at (" + flocation.getCoordString() + ") from the faction: " + otherFaction.getTag()); } - } - else { + } else { msg("This is a safe zone. You lack permissions to unclaim."); - } - return; - } - else if (otherFaction.isWarZone()) { + } return; + } else if (otherFaction.isWarZone()) { if (Permission.MANAGE_WAR_ZONE.has(sender)) { - Board.removeAt(flocation); - msg("War zone was unclaimed."); + Board.removeAt(flocation); msg("War zone was unclaimed."); if (Conf.logLandUnclaims) { P.p.log(fme.getName() + " unclaimed land at (" + flocation.getCoordString() + ") from the faction: " + otherFaction.getTag()); } - } - else { + } else { msg("This is a war zone. You lack permissions to unclaim."); - } - return; + } return; } if (fme.isAdminBypassing()) { @@ -81,13 +68,11 @@ public class CmdUnclaim extends FCommand { if (myFaction != otherFaction) { - msg("You don't own this land."); - return; + msg("You don't own this land."); return; } LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(flocation, otherFaction, fme); - Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); - if (unclaimEvent.isCancelled()) { return; } + Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); if (unclaimEvent.isCancelled()) { return; } if (Econ.shouldBeUsed()) { double refund = Econ.calculateClaimRefund(myFaction.getLandRounded()); @@ -96,14 +81,12 @@ public class CmdUnclaim extends FCommand { if (!Econ.modifyMoney(myFaction, refund, "to unclaim this land", "for unclaiming this land")) { return; } - } - else { + } else { if (!Econ.modifyMoney(fme, refund, "to unclaim this land", "for unclaiming this land")) { return; } } } - Board.removeAt(flocation); - myFaction.msg("%s unclaimed some land.", fme.describeTo(myFaction, true)); + Board.removeAt(flocation); myFaction.msg("%s unclaimed some land.", fme.describeTo(myFaction, true)); if (Conf.logLandUnclaims) { P.p.log(fme.getName() + " unclaimed land at (" + flocation.getCoordString() + ") from the faction: " + otherFaction.getTag()); diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java index 96ed5c16..1505b840 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java @@ -10,19 +10,14 @@ import org.bukkit.Bukkit; public class CmdUnclaimall extends FCommand { public CmdUnclaimall() { - this.aliases.add("unclaimall"); - this.aliases.add("declaimall"); + this.aliases.add("unclaimall"); this.aliases.add("declaimall"); //this.requiredArgs.add(""); //this.optionalArgs.put("", ""); - this.permission = Permission.UNCLAIM_ALL.node; - this.disableOnLock = true; + this.permission = Permission.UNCLAIM_ALL.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override @@ -33,8 +28,7 @@ public class CmdUnclaimall extends FCommand { if (!Econ.modifyMoney(myFaction, refund, "to unclaim all faction land", "for unclaiming all faction land")) { return; } - } - else { + } else { if (!Econ.modifyMoney(fme, refund, "to unclaim all faction land", "for unclaiming all faction land")) { return; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java b/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java index c1cdc8e6..bdbbf2e4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java @@ -11,12 +11,9 @@ public class CmdVersion extends FCommand { //this.requiredArgs.add(""); //this.optionalArgs.put("", ""); - this.permission = Permission.VERSION.node; - this.disableOnLock = false; + this.permission = Permission.VERSION.node; this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java index 084bd2fc..134bd698 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java @@ -9,18 +9,14 @@ import com.massivecraft.factions.struct.Permission; public class CmdWarunclaimall extends FCommand { public CmdWarunclaimall() { - this.aliases.add("warunclaimall"); - this.aliases.add("wardeclaimall"); + this.aliases.add("warunclaimall"); this.aliases.add("wardeclaimall"); //this.requiredArgs.add(""); //this.optionalArgs.put("", ""); - this.permission = Permission.MANAGE_WAR_ZONE.node; - this.disableOnLock = true; + this.permission = Permission.MANAGE_WAR_ZONE.node; this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; this.setHelpShort("unclaim all warzone land"); @@ -28,8 +24,7 @@ public class CmdWarunclaimall extends FCommand { @Override public void perform() { - Board.unclaimAll(Factions.i.getWarZone().getId()); - msg("You unclaimed ALL war zone land."); + Board.unclaimAll(Factions.i.getWarZone().getId()); msg("You unclaimed ALL war zone land."); if (Conf.logLandUnclaims) { P.p.log(fme.getName() + " unclaimed all war zones."); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java b/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java index a26c06a8..92ceb363 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java @@ -52,17 +52,14 @@ public class FCmdRoot extends FCommand { public CmdWarunclaimall cmdWarunclaimall = new CmdWarunclaimall(); public FCmdRoot() { - super(); - this.aliases.addAll(Conf.baseCommandAliases); + super(); this.aliases.addAll(Conf.baseCommandAliases); this.aliases.removeAll(Collections.singletonList(null)); // remove any nulls from extra commas this.allowNoSlashAccess = Conf.allowNoSlashCommand; //this.requiredArgs.add(""); //this.optionalArgs.put("","") - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = false; senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; this.disableOnLock = false; @@ -72,57 +69,29 @@ public class FCmdRoot extends FCommand { //this.subCommands.add(p.cmdHelp); - this.addSubCommand(this.cmdAdmin); - this.addSubCommand(this.cmdAutoClaim); - this.addSubCommand(this.cmdBoom); - this.addSubCommand(this.cmdBypass); - this.addSubCommand(this.cmdChat); - 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.cmdReload); - this.addSubCommand(this.cmdSafeunclaimall); - this.addSubCommand(this.cmdSaveAll); - this.addSubCommand(this.cmdSethome); - this.addSubCommand(this.cmdShow); - this.addSubCommand(this.cmdTag); - this.addSubCommand(this.cmdTitle); - this.addSubCommand(this.cmdUnclaim); - this.addSubCommand(this.cmdUnclaimall); - this.addSubCommand(this.cmdVersion); + this.addSubCommand(this.cmdAdmin); this.addSubCommand(this.cmdAutoClaim); this.addSubCommand(this.cmdBoom); + this.addSubCommand(this.cmdBypass); this.addSubCommand(this.cmdChat); 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.cmdReload); this.addSubCommand(this.cmdSafeunclaimall); + this.addSubCommand(this.cmdSaveAll); this.addSubCommand(this.cmdSethome); this.addSubCommand(this.cmdShow); + this.addSubCommand(this.cmdTag); this.addSubCommand(this.cmdTitle); this.addSubCommand(this.cmdUnclaim); + this.addSubCommand(this.cmdUnclaimall); this.addSubCommand(this.cmdVersion); this.addSubCommand(this.cmdWarunclaimall); } @Override public void perform() { - this.commandChain.add(this); - this.cmdHelp.execute(this.sender, this.args, this.commandChain); + this.commandChain.add(this); this.cmdHelp.execute(this.sender, this.args, this.commandChain); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FCommand.java b/src/main/java/com/massivecraft/factions/cmd/FCommand.java index a914a798..8b4f7cc0 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCommand.java @@ -32,39 +32,30 @@ public abstract class FCommand extends MCommand

{ // The money commands must be disabled if money should not be used. isMoneyCommand = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBeMember = false; senderMustBeModerator = false; senderMustBeAdmin = false; } @Override public void execute(CommandSender sender, List args, List> commandChain) { if (sender instanceof Player) { - this.fme = FPlayers.i.get((Player) sender); - this.myFaction = this.fme.getFaction(); - } - else { - this.fme = null; - this.myFaction = null; - } - super.execute(sender, args, commandChain); + this.fme = FPlayers.i.get((Player) sender); this.myFaction = this.fme.getFaction(); + } else { + this.fme = null; this.myFaction = null; + } super.execute(sender, args, commandChain); } @Override public boolean isEnabled() { if (p.getLocked() && this.disableOnLock) { - msg("Factions was locked by an admin. Please try again later."); - return false; + msg("Factions was locked by an admin. Please try again later."); return false; } if (this.isMoneyCommand && !Conf.econEnabled) { - msg("Faction economy features are disabled on this server."); - return false; + msg("Faction economy features are disabled on this server."); return false; } if (this.isMoneyCommand && !Conf.bankEnabled) { - msg("The faction bank system is disabled on this server."); - return false; + msg("The faction bank system is disabled on this server."); return false; } return true; @@ -72,8 +63,7 @@ public abstract class FCommand extends MCommand

{ @Override public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) { - boolean superValid = super.validSenderType(sender, informSenderIfNot); - if (!superValid) { return false; } + boolean superValid = super.validSenderType(sender, informSenderIfNot); if (!superValid) { return false; } if (!(this.senderMustBeMember || this.senderMustBeModerator || this.senderMustBeAdmin)) { return true; } @@ -82,18 +72,15 @@ public abstract class FCommand extends MCommand

{ FPlayer fplayer = FPlayers.i.get((Player) sender); if (!fplayer.hasFaction()) { - sender.sendMessage(p.txt.parse("You are not member of any faction.")); - return false; + sender.sendMessage(p.txt.parse("You are not member of any faction.")); return false; } if (this.senderMustBeModerator && !fplayer.getRole().isAtLeast(Role.MODERATOR)) { - sender.sendMessage(p.txt.parse("Only faction moderators can %s.", this.getHelpShort())); - return false; + sender.sendMessage(p.txt.parse("Only faction moderators can %s.", this.getHelpShort())); return false; } if (this.senderMustBeAdmin && !fplayer.getRole().isAtLeast(Role.ADMIN)) { - sender.sendMessage(p.txt.parse("Only faction admins can %s.", this.getHelpShort())); - return false; + sender.sendMessage(p.txt.parse("Only faction admins can %s.", this.getHelpShort())); return false; } return true; @@ -107,20 +94,16 @@ public abstract class FCommand extends MCommand

{ if (me == null) { return true; } if (!fme.hasFaction()) { - sendMessage("You are not member of any faction."); - return false; - } - return true; + sendMessage("You are not member of any faction."); return false; + } return true; } public boolean assertMinRole(Role role) { if (me == null) { return true; } if (fme.getRole().value < role.value) { - msg("You must be " + role + " to " + this.getHelpShort() + "."); - return false; - } - return true; + msg("You must be " + role + " to " + this.getHelpShort() + "."); return false; + } return true; } // -------------------------------------------- // @@ -132,8 +115,7 @@ public abstract class FCommand extends MCommand

{ FPlayer ret = def; if (name != null) { - OfflinePlayer player = Bukkit.getOfflinePlayer(name); - FPlayer fplayer = FPlayers.i.get(player); + OfflinePlayer player = Bukkit.getOfflinePlayer(name); FPlayer fplayer = FPlayers.i.get(player); if (fplayer != null) { ret = fplayer; } @@ -194,8 +176,7 @@ public abstract class FCommand extends MCommand

{ // Next we match player names if (faction == null) { - OfflinePlayer player = Bukkit.getOfflinePlayer(name); - FPlayer fplayer = FPlayers.i.get(player); + OfflinePlayer player = Bukkit.getOfflinePlayer(name); FPlayer fplayer = FPlayers.i.get(player); if (fplayer != null) { faction = fplayer.getFaction(); } @@ -241,16 +222,13 @@ public abstract class FCommand extends MCommand

{ if (you.getRole().equals(Role.ADMIN)) { i.sendMessage(p.txt.parse("Only the faction admin can do that.")); - } - else if (i.getRole().equals(Role.MODERATOR)) { + } else if (i.getRole().equals(Role.MODERATOR)) { if (i == you) { return true; //Moderators can control themselves - } - else { + } else { i.sendMessage(p.txt.parse("Moderators can't control each other...")); } - } - else { + } else { i.sendMessage(p.txt.parse("You must be a faction moderator to do that.")); } @@ -263,8 +241,7 @@ public abstract class FCommand extends MCommand

{ if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) { return Econ.modifyMoney(myFaction, -cost, toDoThis, forDoingThis); - } - else { return Econ.modifyMoney(fme, -cost, toDoThis, forDoingThis); } + } else { return Econ.modifyMoney(fme, -cost, toDoThis, forDoingThis); } } // like above, but just make sure they can pay; returns true unless person can't afford the cost @@ -273,7 +250,6 @@ public abstract class FCommand extends MCommand

{ if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) { return Econ.hasAtLeast(myFaction, cost, toDoThis); - } - else { return Econ.hasAtLeast(fme, cost, toDoThis); } + } else { return Econ.hasAtLeast(fme, cost, toDoThis); } } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java b/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java index 1ae9a7df..59feeff6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java @@ -12,37 +12,28 @@ public abstract class FRelationCommand extends FCommand { public Relation targetRelation; public FRelationCommand() { - super(); - this.requiredArgs.add("faction tag"); + super(); this.requiredArgs.add("faction tag"); //this.optionalArgs.put("player name", "you"); - this.permission = Permission.RELATION.node; - this.disableOnLock = true; + this.permission = Permission.RELATION.node; this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; senderMustBeMember = false; senderMustBeModerator = true; senderMustBeAdmin = false; } @Override public void perform() { - Faction them = this.argAsFaction(0); - if (them == null) { return; } + Faction them = this.argAsFaction(0); if (them == null) { return; } if (!them.isNormal()) { - msg("Nope! You can't."); - return; + msg("Nope! You can't."); return; } if (them == myFaction) { - msg("Nope! You can't declare a relation to yourself :)"); - return; + msg("Nope! You can't declare a relation to yourself :)"); return; } if (myFaction.getRelationWish(them) == targetRelation) { - msg("You already have that relation wish set with %s.", them.getTag()); - return; + msg("You already have that relation wish set with %s.", them.getTag()); return; } // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay @@ -51,8 +42,7 @@ public abstract class FRelationCommand extends FCommand { } // try to set the new relation - Relation oldRelation = myFaction.getRelationTo(them, true); - myFaction.setRelationWish(them, targetRelation); + Relation oldRelation = myFaction.getRelationTo(them, true); myFaction.setRelationWish(them, targetRelation); Relation currentRelation = myFaction.getRelationTo(them, true); ChatColor currentRelationColor = currentRelation.getColor(); diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java index 433eb380..7f7679aa 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java @@ -19,9 +19,7 @@ public class FPlayerJoinEvent extends Event implements Cancellable { } public FPlayerJoinEvent(FPlayer fp, Faction f, PlayerJoinReason r) { - fplayer = fp; - faction = f; - reason = r; + fplayer = fp; faction = f; reason = r; } public FPlayer getFPlayer() { diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java index 805ec745..16cf9373 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java @@ -18,9 +18,7 @@ public class FPlayerLeaveEvent extends Event implements Cancellable { } public FPlayerLeaveEvent(FPlayer p, Faction f, PlayerLeaveReason r) { - FPlayer = p; - Faction = f; - reason = r; + FPlayer = p; Faction = f; reason = r; } public HandlerList getHandlers() { @@ -51,9 +49,7 @@ public class FPlayerLeaveEvent extends Event implements Cancellable { @Override public void setCancelled(boolean c) { if (reason == PlayerLeaveReason.DISBAND || reason == PlayerLeaveReason.RESET) { - cancelled = false; - return; - } - cancelled = c; + cancelled = false; return; + } cancelled = c; } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java b/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java index 1f18d39a..65e84392 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java @@ -16,9 +16,7 @@ public class FactionCreateEvent extends Event implements Cancellable { private boolean cancelled; public FactionCreateEvent(Player sender, String tag) { - this.factionTag = tag; - this.sender = sender; - this.cancelled = false; + this.factionTag = tag; this.sender = sender; this.cancelled = false; } public FPlayer getFPlayer() { diff --git a/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java b/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java index b7f767ae..6b88469e 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java @@ -17,9 +17,7 @@ public class FactionDisbandEvent extends Event implements Cancellable { private Player sender; public FactionDisbandEvent(Player sender, String factionId) { - cancelled = false; - this.sender = sender; - this.id = factionId; + cancelled = false; this.sender = sender; this.id = factionId; } public HandlerList getHandlers() { diff --git a/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java b/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java index 05f0d344..33aacc61 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java @@ -15,10 +15,7 @@ public class FactionRelationEvent extends Event { private Relation frel; public FactionRelationEvent(Faction sender, Faction target, Relation oldrel, Relation rel) { - fsender = sender; - ftarget = target; - foldrel = oldrel; - frel = rel; + fsender = sender; ftarget = target; foldrel = oldrel; frel = rel; } public HandlerList getHandlers() { diff --git a/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java b/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java index d8862526..40f285b7 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java @@ -16,10 +16,7 @@ public class FactionRenameEvent extends Event implements Cancellable { private String tag; public FactionRenameEvent(FPlayer sender, String newTag) { - fplayer = sender; - faction = sender.getFaction(); - tag = newTag; - this.cancelled = false; + fplayer = sender; faction = sender.getFaction(); tag = newTag; this.cancelled = false; } public Faction getFaction() { diff --git a/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java b/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java index 55ff0eef..e0f38359 100644 --- a/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java @@ -17,10 +17,7 @@ public class LandClaimEvent extends Event implements Cancellable { private FPlayer fplayer; public LandClaimEvent(FLocation loc, Faction f, FPlayer p) { - cancelled = false; - location = loc; - faction = f; - fplayer = p; + cancelled = false; location = loc; faction = f; fplayer = p; } public HandlerList getHandlers() { diff --git a/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java b/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java index 0e705778..9f3dc913 100644 --- a/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java @@ -13,8 +13,7 @@ public class LandUnclaimAllEvent extends Event { private FPlayer fplayer; public LandUnclaimAllEvent(Faction f, FPlayer p) { - faction = f; - fplayer = p; + faction = f; fplayer = p; } public HandlerList getHandlers() { diff --git a/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java b/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java index 436f58cb..a5d8a637 100644 --- a/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java @@ -17,10 +17,7 @@ public class LandUnclaimEvent extends Event implements Cancellable { private FPlayer fplayer; public LandUnclaimEvent(FLocation loc, Faction f, FPlayer p) { - cancelled = false; - location = loc; - faction = f; - fplayer = p; + cancelled = false; location = loc; faction = f; fplayer = p; } public HandlerList getHandlers() { diff --git a/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java b/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java index cd64dc0e..03c8d5b9 100644 --- a/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java +++ b/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java @@ -17,9 +17,7 @@ public class PowerLossEvent extends Event implements Cancellable { private String message; public PowerLossEvent(Faction f, FPlayer p) { - cancelled = false; - faction = f; - fplayer = p; + cancelled = false; faction = f; fplayer = p; } @Override diff --git a/src/main/java/com/massivecraft/factions/integration/Econ.java b/src/main/java/com/massivecraft/factions/integration/Econ.java index 0e1008e4..e313a248 100644 --- a/src/main/java/com/massivecraft/factions/integration/Econ.java +++ b/src/main/java/com/massivecraft/factions/integration/Econ.java @@ -24,16 +24,13 @@ public class Econ { String integrationFail = "Economy integration is " + (Conf.econEnabled ? "enabled, but" : "disabled, and") + " the plugin \"Vault\" "; if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { - P.p.log(integrationFail + "is not installed."); - return; + P.p.log(integrationFail + "is not installed."); return; } RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { - P.p.log(integrationFail + "is not hooked into an economy plugin."); - return; - } - econ = rsp.getProvider(); + P.p.log(integrationFail + "is not hooked into an economy plugin."); return; + } econ = rsp.getProvider(); P.p.log("Economy integration through Vault plugin successful."); @@ -58,8 +55,7 @@ public class Econ { public static void modifyUniverseMoney(double delta) { if (!shouldBeUsed()) { return; } - if (Conf.econUniverseAccount == null) { return; } - if (Conf.econUniverseAccount.length() == 0) { return; } + if (Conf.econUniverseAccount == null) { return; } if (Conf.econUniverseAccount.length() == 0) { return; } if (!econ.hasAccount(Conf.econUniverseAccount)) { return; } modifyBalance(Conf.econUniverseAccount, delta); @@ -67,15 +63,13 @@ public class Econ { public static void sendBalanceInfo(FPlayer to, EconomyParticipator about) { if (!shouldBeUsed()) { - P.p.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); - return; + P.p.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); return; } to.msg("%s's balance is %s.", about.describeTo(to, true), Econ.moneyString(econ.getBalance(about.getAccountId()))); } public static boolean canIControllYou(EconomyParticipator i, EconomyParticipator you) { - Faction fI = RelationUtil.getFaction(i); - Faction fYou = RelationUtil.getFaction(you); + Faction fI = RelationUtil.getFaction(i); Faction fYou = RelationUtil.getFaction(you); // This is a system invoker. Accept it. if (fI == null) { return true; } @@ -114,10 +108,7 @@ public class Econ { // 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; + amount *= -1; EconomyParticipator temp = from; from = to; to = temp; } // Check the rights @@ -137,12 +128,9 @@ public class Econ { EconomyResponse erw = econ.withdrawPlayer(from.getAccountId(), amount); if (erw.transactionSuccess()) { - EconomyResponse erd = econ.depositPlayer(to.getAccountId(), amount); - if (erd.transactionSuccess()) { - if (notify) { sendTransferInfo(invoker, from, to, amount); } - return true; - } - else { + EconomyResponse erd = econ.depositPlayer(to.getAccountId(), amount); if (erd.transactionSuccess()) { + if (notify) { sendTransferInfo(invoker, from, to, amount); } return true; + } else { // transaction failed, refund account econ.depositPlayer(from.getAccountId(), amount); } @@ -161,11 +149,9 @@ public class Econ { if (ep == null) { // Add nothing - } - else if (ep instanceof FPlayer) { + } else if (ep instanceof FPlayer) { fplayers.add((FPlayer) ep); - } - else if (ep instanceof Faction) { + } else if (ep instanceof Faction) { fplayers.addAll(((Faction) ep).getFPlayers()); } @@ -173,27 +159,22 @@ public class Econ { } 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)); + 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 transfered from %s to %s.", moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); } - } - else if (invoker == from) { + } 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) { + } 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 { + } else { for (FPlayer recipient : recipients) { recipient.msg("%s transfered %s from %s to %s.", invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); } @@ -206,17 +187,14 @@ public class Econ { if (!econ.has(ep.getAccountId(), delta)) { if (toDoThis != null && !toDoThis.isEmpty()) { ep.msg("%s can't afford %s %s.", ep.describeTo(ep, true), moneyString(delta), toDoThis); - } - return false; - } - return true; + } return false; + } return true; } public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) { if (!shouldBeUsed()) { return false; } - String acc = ep.getAccountId(); - String You = ep.describeTo(ep, true); + String acc = ep.getAccountId(); String You = ep.describeTo(ep, true); if (delta == 0) { // no money actually transferred? @@ -227,40 +205,30 @@ public class Econ { 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()) { + 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 { + } 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; + } return false; } - } - else { + } 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()) { + modifyUniverseMoney(-delta); if (forDoingThis != null && !forDoingThis.isEmpty()) { ep.msg("%s lost %s %s.", You, moneyString(-delta), forDoingThis); - } - return true; - } - else { + } 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; + } return false; } } } @@ -275,8 +243,7 @@ public class Econ { for (Faction faction : Factions.i.get()) { if (faction.money > 0) { - econ.depositPlayer(faction.getAccountId(), faction.money); - faction.money = 0; + econ.depositPlayer(faction.getAccountId(), faction.money); faction.money = 0; } } } @@ -288,9 +255,7 @@ public class Econ { } // 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); + return Conf.econCostClaimWilderness + (Conf.econCostClaimWilderness * Conf.econClaimAdditionalMultiplier * ownedLand) - (takingFromAnotherFaction ? Conf.econCostClaimFromFactionBonus : 0); } // calculate refund amount for unclaiming land @@ -300,11 +265,9 @@ public class Econ { // calculate value of all owned land public static double calculateTotalLandValue(int ownedLand) { - double amount = 0; - for (int x = 0; x < ownedLand; x++) { + double amount = 0; for (int x = 0; x < ownedLand; x++) { amount += calculateClaimCost(x, false); - } - return amount; + } return amount; } // calculate refund amount for all owned land @@ -327,13 +290,15 @@ public class Econ { 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(); } + 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(); } + if (amount < 0) { return econ.withdrawPlayer(account, -amount).transactionSuccess(); } else { + return econ.depositPlayer(account, amount).transactionSuccess(); + } } public static boolean deposit(String account, double amount) { diff --git a/src/main/java/com/massivecraft/factions/integration/Essentials.java b/src/main/java/com/massivecraft/factions/integration/Essentials.java index 356d6121..43403f12 100644 --- a/src/main/java/com/massivecraft/factions/integration/Essentials.java +++ b/src/main/java/com/massivecraft/factions/integration/Essentials.java @@ -15,8 +15,7 @@ public class Essentials { private static IEssentials essentials; public static void setup() { - Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials"); - if (ess != null) { + Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials"); if (ess != null) { essentials = (IEssentials) ess; } } @@ -26,12 +25,10 @@ public class Essentials { if (!Conf.homesTeleportCommandEssentialsIntegration || essentials == null) { return false; } Teleport teleport = (Teleport) essentials.getUser(player).getTeleport(); - Trade trade = new Trade(Conf.econCostHome, essentials); - try { + Trade trade = new Trade(Conf.econCostHome, essentials); try { teleport.teleport(loc, trade); } catch (Exception e) { player.sendMessage(ChatColor.RED.toString() + e.getMessage()); - } - return true; + } return true; } } diff --git a/src/main/java/com/massivecraft/factions/integration/Worldguard.java b/src/main/java/com/massivecraft/factions/integration/Worldguard.java index 9e6ecd58..f23f73c0 100644 --- a/src/main/java/com/massivecraft/factions/integration/Worldguard.java +++ b/src/main/java/com/massivecraft/factions/integration/Worldguard.java @@ -33,14 +33,9 @@ public class Worldguard { public static void init(Plugin plugin) { Plugin wgplug = plugin.getServer().getPluginManager().getPlugin("WorldGuard"); if (wgplug == null || !(wgplug instanceof WorldGuardPlugin)) { - enabled = false; - wg = null; - P.p.log("Could not hook to WorldGuard. WorldGuard checks are disabled."); - } - else { - wg = (WorldGuardPlugin) wgplug; - enabled = true; - P.p.log("Successfully hooked to WorldGuard."); + enabled = false; wg = null; P.p.log("Could not hook to WorldGuard. WorldGuard checks are disabled."); + } else { + wg = (WorldGuardPlugin) wgplug; enabled = true; P.p.log("Successfully hooked to WorldGuard."); } } @@ -58,13 +53,10 @@ public class Worldguard { 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); + ApplicableRegionSet set = regionManager.getApplicableRegions(pt); return set.allows(DefaultFlag.PVP); } // Check if player can build at location by worldguards rules. @@ -77,8 +69,7 @@ public class Worldguard { return false; } - World world = loc.getWorld(); - Vector pt = toVector(loc); + World world = loc.getWorld(); Vector pt = toVector(loc); if (wg.getRegionManager(world).getApplicableRegions(pt).size() > 0) { return wg.canBuild(player, loc); } return false; @@ -94,12 +85,8 @@ public class Worldguard { return false; } - World world = loc.getWorld(); - Chunk chunk = world.getChunkAt(loc); - int minChunkX = chunk.getX() << 4; - int minChunkZ = chunk.getZ() << 4; - int maxChunkX = minChunkX + 15; - int maxChunkZ = minChunkZ + 15; + World world = loc.getWorld(); Chunk chunk = world.getChunkAt(loc); 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 @@ -110,15 +97,12 @@ public class Worldguard { ProtectedCuboidRegion region = new ProtectedCuboidRegion("wgfactionoverlapcheck", minChunk, maxChunk); Map allregions = regionManager.getRegions(); List allregionslist = new ArrayList(allregions.values()); - List overlaps; - boolean foundregions = false; + List overlaps; boolean foundregions = false; try { - overlaps = region.getIntersectingRegions(allregionslist); - if (overlaps == null || overlaps.isEmpty()) { + overlaps = region.getIntersectingRegions(allregionslist); if (overlaps == null || overlaps.isEmpty()) { foundregions = false; - } - else { + } else { foundregions = true; } } catch (Exception e) { diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java index f83f83ca..d2274eb7 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java @@ -23,8 +23,7 @@ public class FactionsBlockListener implements Listener { @EventHandler(priority = EventPriority.NORMAL) public void onBlockPlace(BlockPlaceEvent event) { - if (event.isCancelled()) { return; } - if (!event.canBuild()) { return; } + if (event.isCancelled()) { return; } if (!event.canBuild()) { return; } // special case for flint&steel, which should only be prevented by DenyUsage list if (event.getBlockPlaced().getType() == Material.FIRE) { @@ -56,8 +55,7 @@ public class FactionsBlockListener implements Listener { @EventHandler(priority = EventPriority.NORMAL) public void onBlockPistonExtend(BlockPistonExtendEvent event) { - if (event.isCancelled()) { return; } - if (!Conf.pistonProtectionThroughDenyBuild) { return; } + if (event.isCancelled()) { return; } if (!Conf.pistonProtectionThroughDenyBuild) { return; } Faction pistonFaction = Board.getFactionAt(new FLocation(event.getBlock())); @@ -66,8 +64,7 @@ public class FactionsBlockListener implements Listener { // 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); - return; + event.setCancelled(true); return; } /* @@ -94,8 +91,7 @@ public class FactionsBlockListener implements Listener { Faction pistonFaction = Board.getFactionAt(new FLocation(event.getBlock())); if (!canPistonMoveBlock(pistonFaction, targetLoc)) { - event.setCancelled(true); - return; + event.setCancelled(true); return; } } @@ -111,13 +107,11 @@ public class FactionsBlockListener implements Listener { } return false; - } - else if (otherFaction.isSafeZone()) { + } else if (otherFaction.isSafeZone()) { if (!Conf.safeZoneDenyBuild) { return true; } return false; - } - else if (otherFaction.isWarZone()) { + } else if (otherFaction.isWarZone()) { if (!Conf.warZoneDenyBuild) { return true; } return false; @@ -131,14 +125,11 @@ public class FactionsBlockListener implements Listener { } public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) { - String name = player.getName(); - if (Conf.playersWhoBypassAllProtection.contains(name)) { return true; } + String name = player.getName(); if (Conf.playersWhoBypassAllProtection.contains(name)) { return true; } - FPlayer me = FPlayers.i.get(player.getUniqueId().toString()); - if (me.isAdminBypassing()) { return true; } + FPlayer me = FPlayers.i.get(player.getUniqueId().toString()); if (me.isAdminBypassing()) { return true; } - FLocation loc = new FLocation(location); - Faction otherFaction = Board.getFactionAt(loc); + FLocation loc = new FLocation(location); Faction otherFaction = Board.getFactionAt(loc); if (otherFaction.isNone()) { if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) { return true; } @@ -150,8 +141,7 @@ public class FactionsBlockListener implements Listener { if (!justCheck) { me.msg("You can't " + action + " in the wilderness."); } return false; - } - else if (otherFaction.isSafeZone()) { + } else if (otherFaction.isSafeZone()) { if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) { return true; } if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) { return true; } @@ -159,8 +149,7 @@ public class FactionsBlockListener implements Listener { if (!justCheck) { me.msg("You can't " + action + " in a safe zone."); } return false; - } - else if (otherFaction.isWarZone()) { + } else if (otherFaction.isWarZone()) { if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) { return true; } if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) { return true; } @@ -170,10 +159,8 @@ public class FactionsBlockListener implements Listener { return false; } - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); - boolean online = otherFaction.hasPlayersOnline(); - boolean pain = !justCheck && rel.confPainBuild(online); + Faction myFaction = me.getFaction(); Relation rel = myFaction.getRelationTo(otherFaction); + boolean online = otherFaction.hasPlayersOnline(); boolean pain = !justCheck && rel.confPainBuild(online); boolean deny = rel.confDenyBuild(online); // hurt the player for building/destroying in other territory? @@ -202,8 +189,7 @@ public class FactionsBlockListener implements Listener { if (!Conf.ownedAreaDenyBuild) { me.msg("It is painful to try to " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); } - } - if (Conf.ownedAreaDenyBuild) { + } if (Conf.ownedAreaDenyBuild) { if (!justCheck) { me.msg("You can't " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java index 7ed0f19d..bb2b200a 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java @@ -27,18 +27,14 @@ public class FactionsChatListener implements Listener { public void onPlayerEarlyChat(PlayerChatEvent event) { if (event.isCancelled()) { return; } - Player talkingPlayer = event.getPlayer(); - String msg = event.getMessage(); - FPlayer me = FPlayers.i.get(talkingPlayer); - ChatMode chat = me.getChatMode(); + Player talkingPlayer = event.getPlayer(); String msg = event.getMessage(); + FPlayer me = FPlayers.i.get(talkingPlayer); ChatMode chat = me.getChatMode(); // slashless factions commands need to be handled here if the user isn't in public chat mode if (chat != ChatMode.PUBLIC && p.handleCommand(talkingPlayer, msg, false, true)) { if (Conf.logPlayerCommands) { Bukkit.getLogger().log(Level.INFO, "[PLAYER_COMMAND] " + talkingPlayer.getName() + ": " + msg); - } - event.setCancelled(true); - return; + } event.setCancelled(true); return; } // Is it a faction chat message? @@ -57,10 +53,8 @@ public class FactionsChatListener implements Listener { } } - event.setCancelled(true); - return; - } - else if (chat == ChatMode.ALLIANCE) { + event.setCancelled(true); return; + } else if (chat == ChatMode.ALLIANCE) { Faction myFaction = me.getFaction(); String message = String.format(Conf.allianceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); @@ -78,8 +72,7 @@ public class FactionsChatListener implements Listener { Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("AllianceChat: " + message)); - event.setCancelled(true); - return; + event.setCancelled(true); return; } } @@ -92,35 +85,26 @@ public class FactionsChatListener implements Listener { // 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.i.get(talkingPlayer); - int InsertIndex; + Player talkingPlayer = event.getPlayer(); String msg = event.getMessage(); + String eventFormat = event.getFormat(); FPlayer me = FPlayers.i.get(talkingPlayer); int InsertIndex; if (!Conf.chatTagReplaceString.isEmpty() && eventFormat.contains(Conf.chatTagReplaceString)) { // we're using the "replace" method of inserting the faction tags // if they stuck "[FACTION_TITLE]" in there, go ahead and do it too 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; + } 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)) { + } 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)) { + } else if (!Conf.chatTagInsertBeforeString.isEmpty() && eventFormat.contains(Conf.chatTagInsertBeforeString)) { // we're using the "insert before string" method InsertIndex = eventFormat.indexOf(Conf.chatTagInsertBeforeString); - } - else { + } else { // we'll fall back to using the index place method - InsertIndex = Conf.chatTagInsertIndex; - if (InsertIndex > eventFormat.length()) { return; } + InsertIndex = Conf.chatTagInsertIndex; if (InsertIndex > eventFormat.length()) { return; } } String formatStart = eventFormat.substring(0, InsertIndex) + ((Conf.chatTagPadBefore && !me.getChatTag().isEmpty()) ? " " : ""); @@ -136,12 +120,10 @@ public class FactionsChatListener implements Listener { for (Player listeningPlayer : event.getRecipients()) { FPlayer you = FPlayers.i.get(listeningPlayer); - String yourFormat = formatStart + me.getChatTag(you).trim() + formatEnd; - try { + String yourFormat = formatStart + me.getChatTag(you).trim() + formatEnd; try { listeningPlayer.sendMessage(String.format(yourFormat, talkingPlayer.getDisplayName(), msg)); } catch (UnknownFormatConversionException ex) { - Conf.chatTagInsertIndex = 0; - P.p.log(Level.SEVERE, "Critical error in chat message formatting!"); + Conf.chatTagInsertIndex = 0; P.p.log(Level.SEVERE, "Critical error in chat message formatting!"); P.p.log(Level.SEVERE, "NOTE: This has been automatically fixed right now by setting chatTagInsertIndex to 0."); P.p.log(Level.SEVERE, "For a more proper fix, please read this regarding chat configuration: http://massivecraft.com/plugins/factions/config#Chat_configuration"); return; @@ -151,8 +133,7 @@ public class FactionsChatListener implements Listener { // Write to the log... We will write the non colored message. String nonColoredMsg = ChatColor.stripColor(String.format(nonColoredMsgFormat, talkingPlayer.getDisplayName(), msg)); Bukkit.getLogger().log(Level.INFO, nonColoredMsg); - } - else { + } else { // No relation color. event.setFormat(nonColoredMsgFormat); } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java index 114b92aa..faa2dee1 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java @@ -34,13 +34,11 @@ public class FactionsEntityListener implements Listener { @EventHandler(priority = EventPriority.NORMAL) public void onEntityDeath(EntityDeathEvent event) { - Entity entity = event.getEntity(); - if (!(entity instanceof Player)) { + Entity entity = event.getEntity(); if (!(entity instanceof Player)) { return; } - Player player = (Player) entity; - FPlayer fplayer = FPlayers.i.get(player); + Player player = (Player) entity; FPlayer fplayer = FPlayers.i.get(player); Faction faction = Board.getFactionAt(new FLocation(player.getLocation())); PowerLossEvent powerLossEvent = new PowerLossEvent(faction, fplayer); @@ -50,24 +48,19 @@ public class FactionsEntityListener implements Listener { if (!Conf.warZonePowerLoss) { powerLossEvent.setMessage("You didn't lose any power since you were in a war zone."); powerLossEvent.setCancelled(true); - } - if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { + } if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { powerLossEvent.setMessage("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"); } - } - else if (faction.isNone() && !Conf.wildernessPowerLoss && !Conf.worldsNoWildernessProtection.contains(player.getWorld().getName())) { + } else if (faction.isNone() && !Conf.wildernessPowerLoss && !Conf.worldsNoWildernessProtection.contains(player.getWorld().getName())) { powerLossEvent.setMessage("You didn't lose any power since you were in the wilderness."); powerLossEvent.setCancelled(true); - } - else if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { + } else if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { powerLossEvent.setMessage("You didn't lose any power due to the world you died in."); powerLossEvent.setCancelled(true); - } - else if (Conf.peacefulMembersDisablePowerLoss && fplayer.hasFaction() && fplayer.getFaction().isPeaceful()) { + } else if (Conf.peacefulMembersDisablePowerLoss && fplayer.hasFaction() && fplayer.getFaction().isPeaceful()) { powerLossEvent.setMessage("You didn't lose any power since you are in a peaceful faction."); powerLossEvent.setCancelled(true); - } - else { + } else { powerLossEvent.setMessage("Your power is now %d / %d"); } @@ -79,8 +72,7 @@ public class FactionsEntityListener implements Listener { fplayer.onDeath(); } // Send the message from the powerLossEvent - final String msg = powerLossEvent.getMessage(); - if (msg != null && !msg.isEmpty()) { + final String msg = powerLossEvent.getMessage(); if (msg != null && !msg.isEmpty()) { fplayer.msg(msg, fplayer.getPowerRounded(), fplayer.getPowerMaxRounded()); } } @@ -98,8 +90,7 @@ public class FactionsEntityListener implements Listener { if (!this.canDamagerHurtDamagee(sub, true)) { event.setCancelled(true); } - } - else if (Conf.safeZonePreventAllDamageToPlayers && isPlayerInSafeZone(event.getEntity())) { + } else if (Conf.safeZonePreventAllDamageToPlayers && isPlayerInSafeZone(event.getEntity())) { // Players can not take any damage in a Safe Zone event.setCancelled(true); } @@ -109,86 +100,47 @@ public class FactionsEntityListener implements Listener { public void onEntityExplode(EntityExplodeEvent event) { if (event.isCancelled()) { return; } - Location loc = event.getLocation(); - Entity boomer = event.getEntity(); + Location loc = event.getLocation(); Entity boomer = event.getEntity(); Faction faction = Board.getFactionAt(new FLocation(loc)); if (faction.noExplosionsInTerritory()) { // faction is peaceful and has explosions set to disabled - event.setCancelled(true); - return; + event.setCancelled(true); return; } boolean online = faction.hasPlayersOnline(); //TODO: :( - if - ( - boomer instanceof Creeper - && - ( - (faction.isNone() && Conf.wildernessBlockCreepers && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) - || - (faction.isNormal() && (online ? Conf.territoryBlockCreepers : Conf.territoryBlockCreepersWhenOffline)) - || - (faction.isWarZone() && Conf.warZoneBlockCreepers) - || - faction.isSafeZone() - ) - ) { + if (boomer instanceof Creeper && ((faction.isNone() && Conf.wildernessBlockCreepers && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) || + (faction.isNormal() && (online ? Conf.territoryBlockCreepers : Conf.territoryBlockCreepersWhenOffline)) || + (faction.isWarZone() && Conf.warZoneBlockCreepers) || + faction.isSafeZone())) { // creeper which needs prevention event.setCancelled(true); - } - else if - ( + } else if ( // it's a bit crude just using fireball protection for Wither boss too, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever - (boomer instanceof Fireball || boomer instanceof WitherSkull || boomer instanceof Wither) - && - ( - (faction.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) - || - (faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) - || - (faction.isWarZone() && Conf.warZoneBlockFireballs) - || - faction.isSafeZone() - ) - ) { + (boomer instanceof Fireball || boomer instanceof WitherSkull || boomer instanceof Wither) && ((faction.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) || + (faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) || + (faction.isWarZone() && Conf.warZoneBlockFireballs) || + faction.isSafeZone())) { // ghast fireball which needs prevention event.setCancelled(true); - } - else if - ( - (boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) - && - ( - (faction.isNone() && Conf.wildernessBlockTNT && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) - || - (faction.isNormal() && (online ? Conf.territoryBlockTNT : Conf.territoryBlockTNTWhenOffline)) - || - (faction.isWarZone() && Conf.warZoneBlockTNT) - || - (faction.isSafeZone() && Conf.safeZoneBlockTNT) - ) - ) { + } else if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && ((faction.isNone() && Conf.wildernessBlockTNT && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) || + (faction.isNormal() && (online ? Conf.territoryBlockTNT : Conf.territoryBlockTNTWhenOffline)) || + (faction.isWarZone() && Conf.warZoneBlockTNT) || + (faction.isSafeZone() && Conf.safeZoneBlockTNT))) { // TNT which needs prevention event.setCancelled(true); - } - else if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && Conf.handleExploitTNTWaterlog) { + } else if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && Conf.handleExploitTNTWaterlog) { // TNT in water/lava doesn't normally destroy any surrounding blocks, which is usually desired behavior, but... // this change below provides workaround for waterwalling providing perfect protection, // and makes cheap (non-obsidian) TNT cannons require minor maintenance between shots - Block center = loc.getBlock(); - if (center.isLiquid()) { + Block center = loc.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) { + 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) { int id = target.getTypeId(); // ignore air, bedrock, water, lava, obsidian, enchanting table, etc.... too bad we can't get a blast resistance value through Bukkit yet if (id != 0 && (id < 7 || id > 11) && id != 49 && id != 90 && id != 116 && id != 119 && id != 120 && id != 130) { @@ -205,55 +157,42 @@ public class FactionsEntityListener implements Listener { if (event.isCancelled()) { return; } EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE, 0); - if (!this.canDamagerHurtDamagee(sub, false)) { event.setCancelled(true); } - sub = null; + if (!this.canDamagerHurtDamagee(sub, false)) { event.setCancelled(true); } sub = null; } - 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 onPotionSplashEvent(PotionSplashEvent event) { if (event.isCancelled()) { return; } // see if the potion has a harmful effect - boolean badjuju = false; - for (PotionEffect effect : event.getPotion().getEffects()) { + boolean badjuju = false; for (PotionEffect effect : event.getPotion().getEffects()) { if (badPotionEffects.contains(effect.getType())) { - badjuju = true; - break; + badjuju = true; break; } - } - if (!badjuju) { return; } + } if (!badjuju) { return; } - ProjectileSource thrower = event.getPotion().getShooter(); - if (!(thrower instanceof Entity)) { + ProjectileSource thrower = event.getPotion().getShooter(); if (!(thrower instanceof Entity)) { return; } // scan through affected entities to make sure they're all valid targets - Iterator iter = event.getAffectedEntities().iterator(); - while (iter.hasNext()) { + Iterator iter = event.getAffectedEntities().iterator(); while (iter.hasNext()) { LivingEntity target = iter.next(); 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 - } - sub = null; + } sub = null; } } public boolean isPlayerInSafeZone(Entity damagee) { if (!(damagee instanceof Player)) { return false; - } - if (Board.getFactionAt(new FLocation(damagee.getLocation())).isSafeZone()) { + } if (Board.getFactionAt(new FLocation(damagee.getLocation())).isSafeZone()) { return true; - } - return false; + } return false; } public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { @@ -261,9 +200,7 @@ public class FactionsEntityListener implements Listener { } public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) { - Entity damager = sub.getDamager(); - Entity damagee = sub.getEntity(); - double damage = sub.getDamage(); + Entity damager = sub.getDamager(); Entity damagee = sub.getEntity(); double damage = sub.getDamage(); if (!(damagee instanceof Player)) { return true; } @@ -288,10 +225,8 @@ public class FactionsEntityListener implements Listener { if (notify) { FPlayer attacker = FPlayers.i.get((Player) damager); attacker.msg("You can't hurt other players in " + (defLocFaction.isSafeZone() ? "a SafeZone." : "peaceful territory.")); - } - return false; - } - return !defLocFaction.noMonstersInTerritory(); + } return false; + } return !defLocFaction.noMonstersInTerritory(); } if (!(damager instanceof Player)) { return true; } @@ -305,8 +240,7 @@ public class FactionsEntityListener implements Listener { if (attacker.hasLoginPvpDisabled()) { if (notify) { attacker.msg("You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in."); - } - return false; + } return false; } Faction locFaction = Board.getFactionAt(new FLocation(attacker)); @@ -315,37 +249,30 @@ public class FactionsEntityListener implements Listener { if (locFaction.noPvPInTerritory()) { if (notify) { attacker.msg("You can't hurt other players while you are in " + (locFaction.isSafeZone() ? "a SafeZone." : "peaceful territory.")); - } - return false; + } return false; } if (locFaction.isWarZone() && Conf.warZoneFriendlyFire) { return true; } if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) { return true; } - Faction defendFaction = defender.getFaction(); - Faction attackFaction = attacker.getFaction(); + Faction defendFaction = defender.getFaction(); Faction attackFaction = attacker.getFaction(); if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers) { - if (notify) { attacker.msg("You can't hurt other players until you join a faction."); } - return false; - } - else if (defendFaction.isNone()) { + if (notify) { attacker.msg("You can't hurt other players until you join a faction."); } return false; + } else if (defendFaction.isNone()) { if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) { // Allow PVP vs. Factionless in attacker's faction territory return true; - } - else if (Conf.disablePVPForFactionlessPlayers) { + } else if (Conf.disablePVPForFactionlessPlayers) { if (notify) { attacker.msg("You can't hurt players who are not currently in a faction."); } return false; } } if (defendFaction.isPeaceful()) { - if (notify) { attacker.msg("You can't hurt players who are in a peaceful faction."); } - return false; - } - else if (attackFaction.isPeaceful()) { + if (notify) { attacker.msg("You can't hurt players who are in a peaceful faction."); } return false; + } else if (attackFaction.isPeaceful()) { if (notify) { attacker.msg("You can't hurt players while you are in a peaceful faction."); } return false; } @@ -354,8 +281,7 @@ public class FactionsEntityListener implements Listener { // You can not hurt neutral factions if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) { - if (notify) { attacker.msg("You can't hurt neutral factions. Declare them as an enemy."); } - return false; + if (notify) { attacker.msg("You can't hurt neutral factions. Declare them as an enemy."); } return false; } // Players without faction may be hurt anywhere @@ -363,8 +289,7 @@ public class FactionsEntityListener implements Listener { // You can never hurt faction members or allies if (relation.isMember() || relation.isAlly()) { - if (notify) { attacker.msg("You can't hurt %s.", defender.describeTo(attacker)); } - return false; + if (notify) { attacker.msg("You can't hurt %s.", defender.describeTo(attacker)); } return false; } boolean ownTerritory = defender.isInOwnTerritory(); @@ -374,14 +299,12 @@ public class FactionsEntityListener implements Listener { if (notify) { attacker.msg("You can't hurt %s in their own territory unless you declare them as an enemy.", defender.describeTo(attacker)); defender.msg("%s tried to hurt you.", attacker.describeTo(defender, true)); - } - return false; + } return false; } // Damage will be dealt. However check if the damage should be reduced. if (damage > 0.0 && ownTerritory && Conf.territoryShieldFactor > 0) { - int newDamage = (int) Math.ceil(damage * (1D - Conf.territoryShieldFactor)); - sub.setDamage(newDamage); + int newDamage = (int) Math.ceil(damage * (1D - Conf.territoryShieldFactor)); sub.setDamage(newDamage); // Send message if (notify) { @@ -409,8 +332,7 @@ public class FactionsEntityListener implements Listener { if (event.isCancelled()) { return; } // if there is a target - Entity target = event.getTarget(); - if (target == null) { + Entity target = event.getTarget(); if (target == null) { return; } @@ -427,42 +349,19 @@ public class FactionsEntityListener implements Listener { @EventHandler(priority = EventPriority.NORMAL) public void onPaintingBreak(HangingBreakEvent event) { - if (event.isCancelled()) { return; } - if (event.getCause() == RemoveCause.EXPLOSION) { - Location loc = event.getEntity().getLocation(); - Faction faction = Board.getFactionAt(new FLocation(loc)); + if (event.isCancelled()) { return; } if (event.getCause() == RemoveCause.EXPLOSION) { + Location loc = event.getEntity().getLocation(); Faction faction = Board.getFactionAt(new FLocation(loc)); if (faction.noExplosionsInTerritory()) { // faction is peaceful and has explosions set to disabled - event.setCancelled(true); - return; + event.setCancelled(true); return; } boolean online = faction.hasPlayersOnline(); - if - ( - ( - faction.isNone() - && !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() - ) { + if ((faction.isNone() && !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); } @@ -472,8 +371,7 @@ public class FactionsEntityListener implements Listener { return; } - Entity breaker = ((HangingBreakByEntityEvent) event).getRemover(); - if (!(breaker instanceof Player)) { + Entity breaker = ((HangingBreakByEntityEvent) event).getRemover(); if (!(breaker instanceof Player)) { return; } @@ -504,20 +402,13 @@ public class FactionsEntityListener implements Listener { if (entity instanceof Enderman) { if (stopEndermanBlockManipulation(loc)) { event.setCancelled(true); } - } - else if (entity instanceof Wither) { + } else if (entity instanceof Wither) { Faction faction = Board.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.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) - || - (faction.isNormal() && (faction.hasPlayersOnline() ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) - || - (faction.isWarZone() && Conf.warZoneBlockFireballs) - || - faction.isSafeZone() - ) { event.setCancelled(true); } + if ((faction.isNone() && 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); } } } @@ -526,34 +417,23 @@ public class FactionsEntityListener implements Listener { 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 - ) { + if (Conf.wildernessDenyEndermanBlocks && + Conf.territoryDenyEndermanBlocks && + Conf.territoryDenyEndermanBlocksWhenOffline && + Conf.safeZoneDenyEndermanBlocks && + Conf.warZoneDenyEndermanBlocks) { return true; } - FLocation fLoc = new FLocation(loc); - Faction claimFaction = Board.getFactionAt(fLoc); + FLocation fLoc = new FLocation(loc); Faction claimFaction = Board.getFactionAt(fLoc); if (claimFaction.isNone()) { return Conf.wildernessDenyEndermanBlocks; - } - else if (claimFaction.isNormal()) { + } else if (claimFaction.isNormal()) { return claimFaction.hasPlayersOnline() ? Conf.territoryDenyEndermanBlocks : Conf.territoryDenyEndermanBlocksWhenOffline; - } - else if (claimFaction.isSafeZone()) { + } else if (claimFaction.isSafeZone()) { return Conf.safeZoneDenyEndermanBlocks; - } - else if (claimFaction.isWarZone()) { + } else if (claimFaction.isWarZone()) { return Conf.warZoneDenyEndermanBlocks; } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java index a02e97b7..faeb8ac0 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java @@ -17,9 +17,7 @@ public class FactionsExploitListener implements Listener { if (event.isCancelled() == true || !Conf.handleExploitObsidianGenerators) { return; } // thanks to ObGenBlocker and WorldGuard for this method - Block block = event.getToBlock(); - int source = event.getBlock().getTypeId(); - int target = block.getTypeId(); + Block block = event.getToBlock(); int source = event.getBlock().getTypeId(); int target = block.getTypeId(); if ((target == 55 || target == 132) && (source == 0 || source == 10 || source == 11)) { block.setTypeId(0); } } @@ -30,33 +28,20 @@ public class FactionsExploitListener implements Listener { 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(); + 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 == Material.THIN_GLASS || mat == Material.IRON_FENCE) && clippingThrough(target, from, 0.65)) - || ((mat == Material.FENCE || mat == Material.NETHER_FENCE) && clippingThrough(target, from, 0.45)) - ) { - event.setTo(from); - return; + if (((mat == Material.THIN_GLASS || mat == Material.IRON_FENCE) && clippingThrough(target, from, 0.65)) || ((mat == Material.FENCE || mat == Material.NETHER_FENCE) && clippingThrough(target, from, 0.45))) { + event.setTo(from); return; } // simple fix otherwise: ender pearl target locations are standardized to be in the center (X/Z) of the target block, not at the edges - target.setX(target.getBlockX() + 0.5); - target.setZ(target.getBlockZ() + 0.5); - event.setTo(target); + target.setX(target.getBlockX() + 0.5); target.setZ(target.getBlockZ() + 0.5); event.setTo(target); } 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)) - ); + 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))); } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java index feed3d14..a88285ab 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java @@ -49,8 +49,7 @@ public class FactionsPlayerListener implements Listener { // and update their last login time to point to when the logged off, for auto-remove routine me.setLastLoginTime(System.currentTimeMillis()); - Faction myFaction = me.getFaction(); - if (myFaction != null) { + Faction myFaction = me.getFaction(); if (myFaction != null) { myFaction.memberLoggedOff(); } } @@ -60,16 +59,14 @@ public class FactionsPlayerListener implements Listener { if (event.isCancelled()) { 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; } + if (event.getFrom().getBlockX() >> 4 == event.getTo().getBlockX() >> 4 && event.getFrom().getBlockZ() >> 4 == event.getTo().getBlockZ() >> 4 && event.getFrom().getWorld() == event.getTo().getWorld()) { + return; + } - Player player = event.getPlayer(); - FPlayer me = FPlayers.i.get(player); + Player player = event.getPlayer(); FPlayer me = FPlayers.i.get(player); // Did we change coord? - FLocation from = me.getLastStoodAt(); - FLocation to = new FLocation(event.getTo()); + FLocation from = me.getLastStoodAt(); FLocation to = new FLocation(event.getTo()); if (from.equals(to)) { return; @@ -80,8 +77,7 @@ public class FactionsPlayerListener implements Listener { me.setLastStoodAt(to); // Did we change "host"(faction)? - Faction factionFrom = Board.getFactionAt(from); - Faction factionTo = Board.getFactionAt(to); + Faction factionFrom = Board.getFactionAt(from); Faction factionTo = Board.getFactionAt(to); boolean changedFaction = (factionFrom != factionTo); /* Was used for displaying on Spout but we removed Spout compatibility. @@ -91,48 +87,40 @@ public class FactionsPlayerListener implements Listener { if (me.isMapAutoUpdating()) { me.sendMessage(Board.getMap(me.getFaction(), to, player.getLocation().getYaw())); - } - else { - Faction myFaction = me.getFaction(); - String ownersTo = myFaction.getOwnerListString(to); + } else { + Faction myFaction = me.getFaction(); String ownersTo = myFaction.getOwnerListString(to); if (changedFaction) { me.sendFactionHereMessage(); if (Conf.ownedAreasEnabled && Conf.ownedMessageOnBorder && myFaction == factionTo && !ownersTo.isEmpty()) { me.sendMessage(Conf.ownedLandMessage + ownersTo); } - } - else if (Conf.ownedAreasEnabled && Conf.ownedMessageInsideTerritory && factionFrom == factionTo && myFaction == factionTo) { + } else if (Conf.ownedAreasEnabled && Conf.ownedMessageInsideTerritory && factionFrom == factionTo && myFaction == factionTo) { String ownersFrom = myFaction.getOwnerListString(from); if (Conf.ownedMessageByChunk || !ownersFrom.equals(ownersTo)) { - if (!ownersTo.isEmpty()) { me.sendMessage(Conf.ownedLandMessage + ownersTo); } - else if (!Conf.publicLandMessage.isEmpty()) { me.sendMessage(Conf.publicLandMessage); } + if (!ownersTo.isEmpty()) { + me.sendMessage(Conf.ownedLandMessage + ownersTo); + } else if (!Conf.publicLandMessage.isEmpty()) { me.sendMessage(Conf.publicLandMessage); } } } } if (me.getAutoClaimFor() != null) { me.attemptClaim(me.getAutoClaimFor(), event.getTo(), true); - } - else if (me.isAutoSafeClaimEnabled()) { + } else if (me.isAutoSafeClaimEnabled()) { if (!Permission.MANAGE_SAFE_ZONE.has(player)) { me.setIsAutoSafeClaimEnabled(false); - } - else { + } else { if (!Board.getFactionAt(to).isSafeZone()) { - Board.setFactionAt(Factions.i.getSafeZone(), to); - me.msg("This land is now a safe zone."); + Board.setFactionAt(Factions.i.getSafeZone(), to); me.msg("This land is now a safe zone."); } } - } - else if (me.isAutoWarClaimEnabled()) { + } else if (me.isAutoWarClaimEnabled()) { if (!Permission.MANAGE_WAR_ZONE.has(player)) { me.setIsAutoWarClaimEnabled(false); - } - else { + } else { if (!Board.getFactionAt(to).isWarZone()) { - Board.setFactionAt(Factions.i.getWarZone(), to); - me.msg("This land is now a war zone."); + Board.setFactionAt(Factions.i.getWarZone(), to); me.msg("This land is now a war zone."); } } } @@ -144,30 +132,23 @@ public class FactionsPlayerListener implements Listener { // only need to check right-clicks and physical as of MC 1.4+; good performance boost if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) { return; } - Block block = event.getClickedBlock(); - Player player = event.getPlayer(); + Block block = event.getClickedBlock(); Player player = event.getPlayer(); if (block == null) { return; // clicked in air, apparently } if (!canPlayerUseBlock(player, block, false)) { - event.setCancelled(true); - if (Conf.handleExploitInteractionSpam) { - String name = player.getName(); - InteractAttemptSpam attempt = interactSpammers.get(name); + event.setCancelled(true); if (Conf.handleExploitInteractionSpam) { + String name = player.getName(); InteractAttemptSpam attempt = interactSpammers.get(name); if (attempt == null) { - attempt = new InteractAttemptSpam(); - interactSpammers.put(name, attempt); - } - int count = attempt.increment(); - if (count >= 10) { + attempt = new InteractAttemptSpam(); interactSpammers.put(name, attempt); + } int count = attempt.increment(); if (count >= 10) { FPlayer me = FPlayers.i.get(name); me.msg("Ouch, that is starting to hurt. You should give it a rest."); player.damage(NumberConversions.floor((double) count / 10)); } - } - return; + } return; } if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { @@ -175,8 +156,7 @@ public class FactionsPlayerListener implements Listener { } if (!playerCanUseItemHere(player, block.getLocation(), event.getMaterial(), false)) { - event.setCancelled(true); - return; + event.setCancelled(true); return; } } @@ -190,31 +170,24 @@ public class FactionsPlayerListener implements Listener { // returns the current attempt count public int increment() { - long Now = System.currentTimeMillis(); - if (Now > lastAttempt + 2000) { attempts = 1; } - else { attempts++; } - lastAttempt = Now; - return attempts; + long Now = System.currentTimeMillis(); if (Now > lastAttempt + 2000) { attempts = 1; } else { attempts++; } + lastAttempt = Now; return attempts; } } public static boolean playerCanUseItemHere(Player player, Location location, Material material, boolean justCheck) { - String name = player.getName(); - if (Conf.playersWhoBypassAllProtection.contains(name)) { return true; } + String name = player.getName(); if (Conf.playersWhoBypassAllProtection.contains(name)) { return true; } - FPlayer me = FPlayers.i.get(player); - if (me.isAdminBypassing()) { return true; } + FPlayer me = FPlayers.i.get(player); if (me.isAdminBypassing()) { return true; } - FLocation loc = new FLocation(location); - Faction otherFaction = Board.getFactionAt(loc); + FLocation loc = new FLocation(location); Faction otherFaction = Board.getFactionAt(loc); if (otherFaction.hasPlayersOnline()) { if (!Conf.territoryDenyUseageMaterials.contains(material)) { return true; // Item isn't one we're preventing for online factions. } - } - else { + } else { if (!Conf.territoryDenyUseageMaterialsWhenOffline.contains(material)) { return true; // Item isn't one we're preventing for offline factions. } @@ -230,15 +203,13 @@ public class FactionsPlayerListener implements Listener { } return false; - } - else if (otherFaction.isSafeZone()) { + } else if (otherFaction.isSafeZone()) { if (!Conf.safeZoneDenyUseage || Permission.MANAGE_SAFE_ZONE.has(player)) { return true; } if (!justCheck) { me.msg("You can't use %s in a safe zone.", TextUtil.getMaterialName(material)); } return false; - } - else if (otherFaction.isWarZone()) { + } else if (otherFaction.isWarZone()) { if (!Conf.warZoneDenyUseage || Permission.MANAGE_WAR_ZONE.has(player)) { return true; } if (!justCheck) { me.msg("You can't use %s in a war zone.", TextUtil.getMaterialName(material)); } @@ -246,8 +217,7 @@ public class FactionsPlayerListener implements Listener { return false; } - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); + Faction myFaction = me.getFaction(); Relation rel = myFaction.getRelationTo(otherFaction); // Cancel if we are not in our own territory if (rel.confDenyUseage()) { @@ -273,11 +243,9 @@ public class FactionsPlayerListener implements Listener { public static boolean canPlayerUseBlock(Player player, Block block, boolean justCheck) { if (Conf.playersWhoBypassAllProtection.contains(player.getName())) { return true; } - FPlayer me = FPlayers.i.get(player); - if (me.isAdminBypassing()) { return true; } + FPlayer me = FPlayers.i.get(player); if (me.isAdminBypassing()) { return true; } - Material material = block.getType(); - FLocation loc = new FLocation(block); + Material material = block.getType(); FLocation loc = new FLocation(block); Faction otherFaction = Board.getFactionAt(loc); // no door/chest/whatever protection in wilderness, war zones, or safe zones @@ -286,13 +254,11 @@ public class FactionsPlayerListener implements Listener { // We only care about some material types. if (otherFaction.hasPlayersOnline()) { if (!Conf.territoryProtectedMaterials.contains(material)) { return true; } - } - else { + } else { if (!Conf.territoryProtectedMaterialsWhenOffline.contains(material)) { return true; } } - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); + Faction myFaction = me.getFaction(); Relation rel = myFaction.getRelationTo(otherFaction); // You may use any block unless it is another faction's territory... if (rel.isNeutral() || (rel.isEnemy() && Conf.territoryEnemyProtectMaterials) || (rel.isAlly() && Conf.territoryAllyProtectMaterials)) { @@ -321,21 +287,10 @@ public class FactionsPlayerListener implements Listener { 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()) - ) - ) { + Location home = me.getFaction().getHome(); if (Conf.homesEnabled && + Conf.homesTeleportToOnDeath && + home != null && + (Conf.homesRespawnFromNoPowerLossWorlds || !Conf.worldsNoPowerLoss.contains(event.getPlayer().getWorld().getName()))) { event.setRespawnLocation(home); } } @@ -346,12 +301,10 @@ public class FactionsPlayerListener implements Listener { public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { if (event.isCancelled()) { return; } - Block block = event.getBlockClicked(); - Player player = event.getPlayer(); + Block block = event.getBlockClicked(); Player player = event.getPlayer(); if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { - event.setCancelled(true); - return; + event.setCancelled(true); return; } } @@ -359,12 +312,10 @@ public class FactionsPlayerListener implements Listener { public void onPlayerBucketFill(PlayerBucketFillEvent event) { if (event.isCancelled()) { return; } - Block block = event.getBlockClicked(); - Player player = event.getPlayer(); + Block block = event.getBlockClicked(); Player player = event.getPlayer(); if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { - event.setCancelled(true); - return; + event.setCancelled(true); return; } } @@ -378,24 +329,15 @@ public class FactionsPlayerListener implements Listener { FPlayer me = FPlayers.i.get(player); String shortCmd; // command without the slash at the beginning - if (fullCmd.startsWith("/")) { shortCmd = fullCmd.substring(1); } - else { - shortCmd = fullCmd; - fullCmd = "/" + fullCmd; + 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()) - ) { + if (me.hasFaction() && + !me.isAdminBypassing() && + !Conf.permanentFactionMemberDenyCommands.isEmpty() && + me.getFaction().isPermanent() && + isCommandInList(fullCmd, shortCmd, Conf.permanentFactionMemberDenyCommands.iterator())) { me.msg("You can't use the command \"" + fullCmd + "\" because you are in a permanent faction."); return true; } @@ -404,45 +346,37 @@ public class FactionsPlayerListener implements Listener { return false; } - Relation rel = me.getRelationToLocation(); - if (rel.isAtLeast(Relation.ALLY)) { + Relation rel = me.getRelationToLocation(); if (rel.isAtLeast(Relation.ALLY)) { return false; } if (rel.isNeutral() && !Conf.territoryNeutralDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.territoryNeutralDenyCommands.iterator())) { - me.msg("You can't use the command \"" + fullCmd + "\" in neutral territory."); - return true; + me.msg("You can't use the command \"" + fullCmd + "\" in neutral territory."); return true; } if (rel.isEnemy() && !Conf.territoryEnemyDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.territoryEnemyDenyCommands.iterator())) { - me.msg("You can't use the command \"" + fullCmd + "\" in enemy territory."); - return true; + me.msg("You can't use the command \"" + fullCmd + "\" in enemy territory."); 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; + 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; + } return false; } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerKick(PlayerKickEvent event) { if (event.isCancelled()) { return; } - FPlayer badGuy = FPlayers.i.get(event.getPlayer()); - if (badGuy == null) { + FPlayer badGuy = FPlayers.i.get(event.getPlayer()); if (badGuy == null) { return; } @@ -450,8 +384,7 @@ public class FactionsPlayerListener implements Listener { if (Conf.removePlayerDataWhenBanned && event.getReason().equals("Banned by admin.")) { if (badGuy.getRole() == Role.ADMIN) { badGuy.getFaction().promoteNewLeader(); } - badGuy.leave(false); - badGuy.detach(); + badGuy.leave(false); badGuy.detach(); } } } diff --git a/src/main/java/com/massivecraft/factions/struct/ChatMode.java b/src/main/java/com/massivecraft/factions/struct/ChatMode.java index 80456c16..46c05024 100644 --- a/src/main/java/com/massivecraft/factions/struct/ChatMode.java +++ b/src/main/java/com/massivecraft/factions/struct/ChatMode.java @@ -9,8 +9,7 @@ public enum ChatMode { public final String nicename; private ChatMode(final int value, final String nicename) { - this.value = value; - this.nicename = nicename; + this.value = value; this.nicename = nicename; } public boolean isAtLeast(ChatMode role) { @@ -27,8 +26,6 @@ public enum ChatMode { } public ChatMode getNext() { - if (this == PUBLIC) { return ALLIANCE; } - if (this == ALLIANCE) { return FACTION; } - return PUBLIC; + if (this == PUBLIC) { return ALLIANCE; } if (this == ALLIANCE) { return FACTION; } return PUBLIC; } } diff --git a/src/main/java/com/massivecraft/factions/struct/Relation.java b/src/main/java/com/massivecraft/factions/struct/Relation.java index 08df93fb..18180373 100644 --- a/src/main/java/com/massivecraft/factions/struct/Relation.java +++ b/src/main/java/com/massivecraft/factions/struct/Relation.java @@ -14,8 +14,7 @@ public enum Relation { public final String nicename; private Relation(final int value, final String nicename) { - this.value = value; - this.nicename = nicename; + this.value = value; this.nicename = nicename; } @Override @@ -48,10 +47,9 @@ public enum Relation { } public ChatColor getColor() { - if (this == MEMBER) { return Conf.colorMember; } - else if (this == ALLY) { return Conf.colorAlly; } - else if (this == NEUTRAL) { return Conf.colorNeutral; } - else { return Conf.colorEnemy; } + if (this == MEMBER) { return Conf.colorMember; } else if (this == ALLY) { + return Conf.colorAlly; + } else if (this == NEUTRAL) { return Conf.colorNeutral; } else { return Conf.colorEnemy; } } // return appropriate Conf setting for DenyBuild based on this relation and their online status @@ -59,14 +57,13 @@ public enum Relation { if (isMember()) { return false; } if (online) { - if (isEnemy()) { return Conf.territoryEnemyDenyBuild; } - else if (isAlly()) { return Conf.territoryAllyDenyBuild; } - else { return Conf.territoryDenyBuild; } - } - else { - if (isEnemy()) { return Conf.territoryEnemyDenyBuildWhenOffline; } - else if (isAlly()) { return Conf.territoryAllyDenyBuildWhenOffline; } - else { return Conf.territoryDenyBuildWhenOffline; } + if (isEnemy()) { return Conf.territoryEnemyDenyBuild; } else if (isAlly()) { + return Conf.territoryAllyDenyBuild; + } else { return Conf.territoryDenyBuild; } + } else { + if (isEnemy()) { return Conf.territoryEnemyDenyBuildWhenOffline; } else if (isAlly()) { + return Conf.territoryAllyDenyBuildWhenOffline; + } else { return Conf.territoryDenyBuildWhenOffline; } } } @@ -75,28 +72,26 @@ public enum Relation { if (isMember()) { return false; } if (online) { - if (isEnemy()) { return Conf.territoryEnemyPainBuild; } - else if (isAlly()) { return Conf.territoryAllyPainBuild; } - else { return Conf.territoryPainBuild; } - } - else { - if (isEnemy()) { return Conf.territoryEnemyPainBuildWhenOffline; } - else if (isAlly()) { return Conf.territoryAllyPainBuildWhenOffline; } - else { return Conf.territoryPainBuildWhenOffline; } + if (isEnemy()) { return Conf.territoryEnemyPainBuild; } else if (isAlly()) { + return Conf.territoryAllyPainBuild; + } else { return Conf.territoryPainBuild; } + } else { + if (isEnemy()) { return Conf.territoryEnemyPainBuildWhenOffline; } else if (isAlly()) { + return Conf.territoryAllyPainBuildWhenOffline; + } 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 { return Conf.territoryDenyUseage; } + if (isMember()) { return false; } else if (isEnemy()) { + return Conf.territoryEnemyDenyUseage; + } else if (isAlly()) { return Conf.territoryAllyDenyUseage; } else { return Conf.territoryDenyUseage; } } public double getRelationCost() { - if (isEnemy()) { return Conf.econCostEnemy; } - else if (isAlly()) { return Conf.econCostAlly; } - else { return Conf.econCostNeutral; } + if (isEnemy()) { return Conf.econCostEnemy; } else if (isAlly()) { return Conf.econCostAlly; } else { + return Conf.econCostNeutral; + } } } diff --git a/src/main/java/com/massivecraft/factions/struct/Role.java b/src/main/java/com/massivecraft/factions/struct/Role.java index 4ce4e69d..7036352b 100644 --- a/src/main/java/com/massivecraft/factions/struct/Role.java +++ b/src/main/java/com/massivecraft/factions/struct/Role.java @@ -11,8 +11,7 @@ public enum Role { public final String nicename; private Role(final int value, final String nicename) { - this.value = value; - this.nicename = nicename; + this.value = value; this.nicename = nicename; } public boolean isAtLeast(Role role) { diff --git a/src/main/java/com/massivecraft/factions/util/AsciiCompass.java b/src/main/java/com/massivecraft/factions/util/AsciiCompass.java index 7d167d40..968ee4ae 100644 --- a/src/main/java/com/massivecraft/factions/util/AsciiCompass.java +++ b/src/main/java/com/massivecraft/factions/util/AsciiCompass.java @@ -32,42 +32,40 @@ public class AsciiCompass { } public static AsciiCompass.Point getCompassPointForDirection(double inDegrees) { - double degrees = (inDegrees - 180) % 360; - if (degrees < 0) { degrees += 360; } + double degrees = (inDegrees - 180) % 360; if (degrees < 0) { degrees += 360; } - if (0 <= degrees && degrees < 22.5) { return AsciiCompass.Point.N; } - else if (22.5 <= degrees && degrees < 67.5) { return AsciiCompass.Point.NE; } - else if (67.5 <= degrees && degrees < 112.5) { return AsciiCompass.Point.E; } - else if (112.5 <= degrees && degrees < 157.5) { return AsciiCompass.Point.SE; } - else if (157.5 <= degrees && degrees < 202.5) { return AsciiCompass.Point.S; } - else if (202.5 <= degrees && degrees < 247.5) { return AsciiCompass.Point.SW; } - else if (247.5 <= degrees && degrees < 292.5) { return AsciiCompass.Point.W; } - else if (292.5 <= degrees && degrees < 337.5) { return AsciiCompass.Point.NW; } - else if (337.5 <= degrees && degrees < 360.0) { return AsciiCompass.Point.N; } - else { return null; } + if (0 <= degrees && degrees < 22.5) { + return AsciiCompass.Point.N; + } else if (22.5 <= degrees && degrees < 67.5) { + return AsciiCompass.Point.NE; + } else if (67.5 <= degrees && degrees < 112.5) { + return AsciiCompass.Point.E; + } else if (112.5 <= degrees && degrees < 157.5) { + return AsciiCompass.Point.SE; + } else if (157.5 <= degrees && degrees < 202.5) { + return AsciiCompass.Point.S; + } else if (202.5 <= degrees && degrees < 247.5) { + return AsciiCompass.Point.SW; + } else if (247.5 <= degrees && degrees < 292.5) { + return AsciiCompass.Point.W; + } else if (292.5 <= degrees && degrees < 337.5) { + return AsciiCompass.Point.NW; + } else if (337.5 <= degrees && degrees < 360.0) { return AsciiCompass.Point.N; } else { return null; } } public static ArrayList getAsciiCompass(Point point, ChatColor colorActive, String colorDefault) { - ArrayList ret = new ArrayList(); - String row; + ArrayList ret = new ArrayList(); String row; - row = ""; - row += Point.NW.toString(Point.NW == point, colorActive, colorDefault); + 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 += 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 = ""; 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 += Point.SE.toString(Point.SE == point, colorActive, colorDefault); ret.add(row); return ret; } diff --git a/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java b/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java index 4c4bd352..a68bd534 100644 --- a/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java +++ b/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java @@ -14,17 +14,14 @@ public class AutoLeaveProcessTask extends BukkitRunnable { private transient double toleranceMillis; public AutoLeaveProcessTask() { - ArrayList fplayers = new ArrayList(FPlayers.i.get()); - this.iterator = fplayers.listIterator(); - this.toleranceMillis = Conf.autoLeaveAfterDaysOfInactivity * 24 * 60 * 60 * 1000; - this.readyToGo = true; + ArrayList fplayers = new ArrayList(FPlayers.i.get()); 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; + this.stop(); return; } if (!readyToGo) { return; } @@ -38,8 +35,7 @@ public class AutoLeaveProcessTask extends BukkitRunnable { // 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; + readyToGo = true; return; } FPlayer fplayer = iterator.next(); @@ -54,8 +50,7 @@ public class AutoLeaveProcessTask extends BukkitRunnable { if (faction != null) { fplayer.getFaction().promoteNewLeader(); } } - fplayer.leave(false); - iterator.remove(); // go ahead and remove this list's link to the FPlayer object + fplayer.leave(false); iterator.remove(); // go ahead and remove this list's link to the FPlayer object fplayer.detach(); } } @@ -66,8 +61,7 @@ public class AutoLeaveProcessTask extends BukkitRunnable { // we're done, shut down public void stop() { - readyToGo = false; - finished = true; + readyToGo = false; finished = true; this.cancel(); } diff --git a/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java b/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java index f85a0629..797ba0ee 100644 --- a/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java +++ b/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java @@ -14,8 +14,7 @@ public class AutoLeaveTask implements Runnable { public synchronized void run() { if (task != null && !task.isFinished()) { return; } - task = new AutoLeaveProcessTask(); - task.runTaskTimer(P.p, 1, 1); + task = new AutoLeaveProcessTask(); task.runTaskTimer(P.p, 1, 1); // maybe setting has been changed? if so, restart this task at new rate if (this.rate != Conf.autoLeaveRoutineRunsEveryXMinutes) { P.p.startAutoLeaveTask(true); } diff --git a/src/main/java/com/massivecraft/factions/util/LazyLocation.java b/src/main/java/com/massivecraft/factions/util/LazyLocation.java index 1b6dcd0f..a1c46512 100644 --- a/src/main/java/com/massivecraft/factions/util/LazyLocation.java +++ b/src/main/java/com/massivecraft/factions/util/LazyLocation.java @@ -27,30 +27,19 @@ public class LazyLocation { } 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.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; + 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(); + 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(); } @@ -60,8 +49,7 @@ public class LazyLocation { if (location != null) { return; } // get World; hopefully it's initialized at this point - World world = Bukkit.getWorld(worldName); - if (world == null) { return; } + 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); diff --git a/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java index 5fd7ee85..5b7f0946 100644 --- a/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java @@ -19,27 +19,20 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { - JsonObject obj = json.getAsJsonObject(); - if (obj == null) { + JsonObject obj = json.getAsJsonObject(); if (obj == null) { return null; } Map> locationMap = new ConcurrentHashMap>(); - Set nameSet; - Iterator iter; - String worldName; - String[] coords; - int x, z; + 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]); + coords = entry2.getKey().trim().split("[,\\s]+"); x = Integer.parseInt(coords[0]); z = Integer.parseInt(coords[1]); - nameSet = new HashSet(); - iter = entry2.getValue().getAsJsonArray().iterator(); + nameSet = new HashSet(); iter = entry2.getValue().getAsJsonArray().iterator(); while (iter.hasNext()) { nameSet.add(iter.next().getAsString()); } @@ -63,27 +56,18 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer nameSet; - Iterator iter; - JsonArray nameArray; + 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(); + 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); + nameArray = new JsonArray(); iter = nameSet.iterator(); while (iter.hasNext()) { + nameElement = new JsonPrimitive(iter.next()); nameArray.add(nameElement); } if (!obj.has(locWorld)) { @@ -92,8 +76,7 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer x86_64 @@ -276,12 +263,9 @@ public final class Metrics { osarch = "x86_64"; } - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); + appendJSONPair(json, "osname", osname); appendJSONPair(json, "osarch", osarch); + appendJSONPair(json, "osversion", osversion); appendJSONPair(json, "cores", Integer.toString(coreCount)); + appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); appendJSONPair(json, "java_version", java_version); // If we're pinging, append it if (isPing) { @@ -301,14 +285,12 @@ public final class Metrics { // It does not reroute POST requests so we need to go around it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); - } - else { + } else { connection = url.openConnection(); } - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); + byte[] uncompressed = json.toString().getBytes(); byte[] compressed = gzip(json.toString()); // Headers connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); @@ -325,23 +307,19 @@ public final class Metrics { } // Write the data - OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); + OutputStream os = connection.getOutputStream(); os.write(compressed); os.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String response = reader.readLine(); // close resources - os.close(); - reader.close(); + os.close(); reader.close(); if (response == null || response.startsWith("ERR") || response.startsWith("7")) { if (response == null) { response = "null"; - } - else if (response.startsWith("7")) { + } else if (response.startsWith("7")) { response = response.substring(response.startsWith("7,") ? 2 : 1); } @@ -357,12 +335,10 @@ public final class Metrics { * @return */ public static byte[] gzip(String input) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = null; try { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); + gzos = new GZIPOutputStream(baos); gzos.write(input.getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } finally { @@ -384,8 +360,7 @@ public final class Metrics { */ private boolean isMineshafterPresent() { try { - Class.forName("mineshafter.MineServer"); - return true; + Class.forName("mineshafter.MineServer"); return true; } catch (Exception e) { return false; } @@ -405,8 +380,7 @@ public final class Metrics { try { if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; + Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; @@ -416,13 +390,11 @@ public final class Metrics { json.append(','); } - json.append(escapeJSON(key)); - json.append(':'); + json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); - } - else { + } else { json.append(escapeJSON(value)); } } @@ -437,40 +409,21 @@ public final class Metrics { private static String escapeJSON(String text) { StringBuilder builder = new StringBuilder(); - builder.append('"'); - for (int index = 0; index < text.length(); index++) { + builder.append('"'); for (int index = 0; index < text.length(); index++) { char chr = text.charAt(index); switch (chr) { - case '"': - case '\\': - builder.append('\\'); + case '"': case '\\': builder.append('\\'); builder.append(chr); break; + case '\b': builder.append("\\b"); break; case '\t': builder.append("\\t"); break; + case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; + default: if (chr < ' ') { + String t = "000" + Integer.toHexString(chr); + builder.append("\\u").append(t.substring(t.length() - 4)); + } else { builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u").append(t.substring(t.length() - 4)); - } - else { - builder.append(chr); - } - break; + } break; } - } - builder.append('"'); + } builder.append('"'); return builder.toString(); } diff --git a/src/main/java/com/massivecraft/factions/util/MiscUtil.java b/src/main/java/com/massivecraft/factions/util/MiscUtil.java index 0cd63695..75226be7 100644 --- a/src/main/java/com/massivecraft/factions/util/MiscUtil.java +++ b/src/main/java/com/massivecraft/factions/util/MiscUtil.java @@ -14,8 +14,7 @@ public class MiscUtil { 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); } @@ -25,9 +24,7 @@ public class MiscUtil { long[] values = new long[(int) Math.abs(end - start) + 1]; if (end < start) { - long oldstart = start; - start = end; - end = oldstart; + long oldstart = start; start = end; end = oldstart; } for (long i = start; i <= end; i++) { @@ -38,25 +35,18 @@ public class MiscUtil { } /// TODO create tag whitelist!! - public static HashSet substanceChars = new HashSet(Arrays.asList(new String[]{ - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", - "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", - "s", "t", "u", "v", "w", "x", "y", "z" - })); + public static HashSet substanceChars = new HashSet(Arrays.asList(new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"})); public static String getComparisonString(String str) { String ret = ""; - 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 += c; } - } - return ret.toLowerCase(); + } return ret.toLowerCase(); } } diff --git a/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java index e7792378..05090a65 100644 --- a/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java @@ -20,18 +20,14 @@ public class MyLocationTypeAdapter implements JsonDeserializer, Js 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); } catch (Exception ex) { - ex.printStackTrace(); - P.p.log(Level.WARNING, "Error encountered while deserializing a LazyLocation."); + ex.printStackTrace(); P.p.log(Level.WARNING, "Error encountered while deserializing a LazyLocation."); return null; } } @@ -41,17 +37,12 @@ public class MyLocationTypeAdapter implements JsonDeserializer, Js 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()); + 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(); - P.p.log(Level.WARNING, "Error encountered while serializing a LazyLocation."); + ex.printStackTrace(); P.p.log(Level.WARNING, "Error encountered while serializing a LazyLocation."); return obj; } } diff --git a/src/main/java/com/massivecraft/factions/util/RelationUtil.java b/src/main/java/com/massivecraft/factions/util/RelationUtil.java index e2299708..75843a78 100644 --- a/src/main/java/com/massivecraft/factions/util/RelationUtil.java +++ b/src/main/java/com/massivecraft/factions/util/RelationUtil.java @@ -12,8 +12,7 @@ public class RelationUtil { public static String describeThatToMe(RelationParticipator that, RelationParticipator me, boolean ucfirst) { String ret = ""; - Faction thatFaction = getFaction(that); - if (thatFaction == null) { + Faction thatFaction = getFaction(that); if (thatFaction == null) { return "ERROR"; // ERROR } @@ -23,20 +22,15 @@ public class RelationUtil { if (that instanceof Faction) { if (me instanceof FPlayer && myFaction == thatFaction) { ret = "your faction"; - } - else { + } else { ret = thatFaction.getTag(); } - } - else if (that instanceof FPlayer) { - FPlayer fplayerthat = (FPlayer) that; - if (that == me) { + } else if (that instanceof FPlayer) { + FPlayer fplayerthat = (FPlayer) that; if (that == me) { ret = "you"; - } - else if (thatFaction == myFaction) { + } else if (thatFaction == myFaction) { ret = fplayerthat.getNameAndTitle(); - } - else { + } else { ret = fplayerthat.getNameAndTag(); } } @@ -57,13 +51,11 @@ public class RelationUtil { } public static Relation getRelationTo(RelationParticipator me, RelationParticipator that, boolean ignorePeaceful) { - Faction fthat = getFaction(that); - if (fthat == null) { + Faction fthat = getFaction(that); if (fthat == null) { return Relation.NEUTRAL; // ERROR } - Faction fme = getFaction(me); - if (fme == null) { + Faction fme = getFaction(me); if (fme == null) { return Relation.NEUTRAL; // ERROR } @@ -100,8 +92,7 @@ public class RelationUtil { } public static ChatColor getColorOfThatToMe(RelationParticipator that, RelationParticipator me) { - Faction thatFaction = getFaction(that); - if (thatFaction != null) { + Faction thatFaction = getFaction(that); if (thatFaction != null) { if (thatFaction.isPeaceful() && thatFaction != getFaction(me)) { return Conf.colorPeaceful; } diff --git a/src/main/java/com/massivecraft/factions/util/SpiralTask.java b/src/main/java/com/massivecraft/factions/util/SpiralTask.java index e5c8ef6b..03d6e40a 100644 --- a/src/main/java/com/massivecraft/factions/util/SpiralTask.java +++ b/src/main/java/com/massivecraft/factions/util/SpiralTask.java @@ -42,15 +42,11 @@ public abstract class SpiralTask implements Runnable { // 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) { - P.p.log(Level.WARNING, "[SpiralTask] A valid world must be specified!"); - this.stop(); - return; + this.world = Bukkit.getWorld(fLocation.getWorldName()); if (this.world == null) { + P.p.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; @@ -98,8 +94,7 @@ public abstract class SpiralTask implements Runnable { */ public final void setTaskID(int ID) { - if (ID == -1) { this.stop(); } - taskID = ID; + if (ID == -1) { this.stop(); } taskID = ID; } public final void run() { @@ -118,8 +113,7 @@ public abstract class SpiralTask implements Runnable { while (now() < loopStartTime + 20) { // run the primary task on the current X/Z coordinates if (!this.work()) { - this.finish(); - return; + this.finish(); return; } // move on to next chunk in spiral @@ -140,28 +134,22 @@ public abstract class SpiralTask implements Runnable { // 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; + } 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++; + isNeg ^= true; length++; } } // move one chunk further in the appropriate direction - if (isZLeg) { z += (isNeg) ? -1 : 1; } - else { x += (isNeg) ? -1 : 1; } + if (isZLeg) { z += (isNeg) ? -1 : 1; } else { x += (isNeg) ? -1 : 1; } return true; } public final boolean insideRadius() { - boolean inside = current < limit; - if (!inside) { this.finish(); } - return inside; + boolean inside = current < limit; if (!inside) { this.finish(); } return inside; } // for successful completion @@ -174,9 +162,7 @@ public abstract class SpiralTask implements Runnable { 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? diff --git a/src/main/java/com/massivecraft/factions/zcore/FCommandHandler.java b/src/main/java/com/massivecraft/factions/zcore/FCommandHandler.java index e12ffa69..df8996e4 100644 --- a/src/main/java/com/massivecraft/factions/zcore/FCommandHandler.java +++ b/src/main/java/com/massivecraft/factions/zcore/FCommandHandler.java @@ -14,7 +14,6 @@ public class FCommandHandler implements CommandExecutor { if (P.p.logPlayerCommands()) { Bukkit.getLogger().info("[PLAYER_COMMAND] " + sender.getName() + ": " + cmd.getName() + args); } - } - return false; + } return false; } } diff --git a/src/main/java/com/massivecraft/factions/zcore/MCommand.java b/src/main/java/com/massivecraft/factions/zcore/MCommand.java index 6b54c6cb..f16aaa27 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MCommand.java +++ b/src/main/java/com/massivecraft/factions/zcore/MCommand.java @@ -18,8 +18,7 @@ public abstract class MCommand { public List> subCommands; public void addSubCommand(MCommand subCommand) { - subCommand.commandChain.addAll(this.commandChain); - subCommand.commandChain.add(this); + subCommand.commandChain.addAll(this.commandChain); subCommand.commandChain.add(this); this.subCommands.add(subCommand); } @@ -43,13 +42,10 @@ public abstract class MCommand { public String getHelpShort() { if (this.helpShort == null) { - String pdesc = p.perm.getPermissionDescription(this.permission); - if (pdesc != null) { + String pdesc = p.perm.getPermissionDescription(this.permission); if (pdesc != null) { return pdesc; - } - return "*info unavailable*"; - } - return this.helpShort; + } return "*info unavailable*"; + } return this.helpShort; } public List helpLong; @@ -73,40 +69,27 @@ public abstract class MCommand { this.allowNoSlashAccess = false; - 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; } // 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 - this.sender = sender; - if (sender instanceof Player) { - this.me = (Player) sender; - this.senderIsConsole = false; - } - else { - this.me = null; - this.senderIsConsole = true; - } - this.args = args; - this.commandChain = commandChain; + this.sender = sender; if (sender instanceof Player) { + this.me = (Player) sender; this.senderIsConsole = false; + } else { + this.me = null; this.senderIsConsole = true; + } 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))) { - args.remove(0); - commandChain.add(this); - subCommand.execute(sender, args, commandChain); - return; + args.remove(0); commandChain.add(this); subCommand.execute(sender, args, commandChain); return; } } } @@ -158,24 +141,19 @@ public abstract class MCommand { if (this.senderMustBePlayer && !(sender instanceof Player)) { if (informSenderIfNot) { msg(Lang.commandSenderMustBePlayer); - } - return false; - } - return true; + } return false; + } return true; } public boolean validSenderPermissions(CommandSender sender, boolean informSenderIfNot) { - if (this.permission == null) { return true; } - return p.perm.has(sender, this.permission, informSenderIfNot); + if (this.permission == null) { return true; } return p.perm.has(sender, this.permission, informSenderIfNot); } public boolean validArgs(List args, CommandSender sender) { if (args.size() < this.requiredArgs.size()) { if (sender != null) { - msg(Lang.commandToFewArgs); - sender.sendMessage(this.getUseageTemplate()); - } - return false; + msg(Lang.commandToFewArgs); sender.sendMessage(this.getUseageTemplate()); + } return false; } if (args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.errorOnToManyArgs) { @@ -184,10 +162,8 @@ public abstract class MCommand { List theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size()); msg(Lang.commandToManyArgs, TextUtil.implode(theToMany, " ")); sender.sendMessage(this.getUseageTemplate()); - } - return false; - } - return true; + } return false; + } return true; } public boolean validArgs(List args) { @@ -199,13 +175,10 @@ public abstract class MCommand { // -------------------------------------------- // public String getUseageTemplate(List> commandChain, boolean addShortHelp) { - StringBuilder ret = new StringBuilder(); - ret.append(p.txt.parseTags("")); - ret.append('/'); + 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(mc.aliases, ",")); ret.append(' '); } ret.append(TextUtil.implode(this.aliases, ",")); @@ -217,24 +190,19 @@ public abstract class MCommand { } for (Entry optionalArg : this.optionalArgs.entrySet()) { - String val = optionalArg.getValue(); - if (val == null) { + String val = optionalArg.getValue(); if (val == null) { val = ""; - } - else { + } else { val = "=" + val; - } - args.add("[" + optionalArg.getKey() + val + "]"); + } args.add("[" + optionalArg.getKey() + val + "]"); } if (args.size() > 0) { - ret.append(p.txt.parseTags("

")); - ret.append(TextUtil.implode(args, " ")); + ret.append(p.txt.parseTags("

")); ret.append(TextUtil.implode(args, " ")); } if (addShortHelp) { - ret.append(p.txt.parseTags(" ")); - ret.append(this.getHelpShort()); + ret.append(p.txt.parseTags(" ")); ret.append(this.getHelpShort()); } return ret.toString(); @@ -274,16 +242,14 @@ public abstract class MCommand { public boolean argIsSet(int idx) { if (this.args.size() < idx + 1) { return false; - } - return true; + } return true; } // STRING ====================== public String argAsString(int idx, String def) { if (this.args.size() < idx + 1) { return def; - } - return this.args.get(idx); + } return this.args.get(idx); } public String argAsString(int idx) { @@ -292,10 +258,8 @@ public abstract class MCommand { // INT ====================== public Integer strAsInt(String str, Integer def) { - if (str == null) { return def; } - try { - Integer ret = Integer.parseInt(str); - return ret; + if (str == null) { return def; } try { + Integer ret = Integer.parseInt(str); return ret; } catch (Exception e) { return def; } @@ -311,10 +275,8 @@ public abstract class MCommand { // Double ====================== public Double strAsDouble(String str, Double def) { - if (str == null) { return def; } - try { - Double ret = Double.parseDouble(str); - return ret; + if (str == null) { return def; } try { + Double ret = Double.parseDouble(str); return ret; } catch (Exception e) { return def; } @@ -334,13 +296,11 @@ public abstract class MCommand { str = str.toLowerCase(); if (str.startsWith("y") || str.startsWith("t") || str.startsWith("on") || str.startsWith("+") || str.startsWith("1")) { return true; - } - return false; + } return false; } public Boolean argAsBool(int idx, boolean def) { - String str = this.argAsString(idx); - if (str == null) { return def; } + String str = this.argAsString(idx); if (str == null) { return def; } return strAsBool(str); } @@ -354,8 +314,7 @@ public abstract class MCommand { Player ret = def; if (name != null) { - Player player = Bukkit.getServer().getPlayer(name); - if (player != null) { + Player player = Bukkit.getServer().getPlayer(name); if (player != null) { ret = player; } } @@ -384,8 +343,7 @@ public abstract class MCommand { Player ret = def; if (name != null) { - List players = Bukkit.getServer().matchPlayer(name); - if (players.size() > 0) { + List players = Bukkit.getServer().matchPlayer(name); if (players.size() > 0) { ret = players.get(0); } } diff --git a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java index aecbc57b..17f1628a 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java @@ -63,12 +63,10 @@ public abstract class MPlugin extends JavaPlugin { private long timeEnableStart; public boolean preEnable() { - log("=== ENABLE START ==="); - timeEnableStart = System.currentTimeMillis(); + log("=== ENABLE START ==="); timeEnableStart = System.currentTimeMillis(); try { - Metrics metrics = new Metrics(this); - metrics.start(); + Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { // Failed to submit the stats :-( } @@ -76,15 +74,13 @@ public abstract class MPlugin extends JavaPlugin { this.getDataFolder().mkdirs(); // Create Utility Instances - this.perm = new PermUtil(this); - this.persist = new Persist(this); + this.perm = new PermUtil(this); this.persist = new Persist(this); // GSON 2.1 is now embedded in CraftBukkit, used by the auto-updater: https://github.com/Bukkit/CraftBukkit/commit/0ed1d1fdbb1e0bc09a70bc7bfdf40c1de8411665 // if ( ! lib.require("gson.jar", "http://search.maven.org/remotecontent?filepath=com/google/code/gson/gson/2.1/gson-2.1.jar")) return false; this.gson = this.getGsonBuilder().create(); - 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 @@ -110,8 +106,7 @@ public abstract class MPlugin extends JavaPlugin { loadLang(); - loadSuccessful = true; - return true; + loadSuccessful = true; return true; } public void postEnable() { @@ -119,24 +114,16 @@ public abstract class MPlugin extends JavaPlugin { } private void loadLang() { - File lang = new File(getDataFolder(), "lang.yml"); - OutputStream out = null; - InputStream defLangStream = this.getResource("lang.yml"); - if (!lang.exists()) { + 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]; + getDataFolder().mkdir(); lang.createNewFile(); if (defLangStream != null) { + out = new FileOutputStream(lang); int read; byte[] bytes = new byte[1024]; while ((read = defLangStream.read(bytes)) != -1) { out.write(bytes, 0, read); - } - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defLangStream); - TL.setFile(defConfig); - return; + } YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defLangStream); + TL.setFile(defConfig); return; } } catch (IOException e) { e.printStackTrace(); // So they notice @@ -150,8 +137,7 @@ public abstract class MPlugin extends JavaPlugin { } catch (IOException e) { e.printStackTrace(); } - } - if (out != null) { + } if (out != null) { try { out.close(); } catch (IOException e) { @@ -162,36 +148,30 @@ public abstract class MPlugin extends JavaPlugin { } } - YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); - for (TL item : TL.values()) { + YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); for (TL item : TL.values()) { if (conf.getString(item.getPath()) == null) { conf.set(item.getPath(), item.getDefault()); } } - TL.setFile(conf); - try { + 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 drtshock."); - e.printStackTrace(); + getLogger().log(Level.WARNING, "Factions: Report this stack trace to drtshock."); e.printStackTrace(); } } public void onDisable() { if (saveTask != null) { - this.getServer().getScheduler().cancelTask(saveTask); - saveTask = null; + this.getServer().getScheduler().cancelTask(saveTask); saveTask = null; } // only save data if plugin actually loaded successfully - if (loadSuccessful) { EM.saveAllToDisc(); } - log("Disabled"); + if (loadSuccessful) { EM.saveAllToDisc(); } log("Disabled"); } public void suicide() { - log("Now I suicide!"); - this.getServer().getPluginManager().disablePlugin(this); + log("Now I suicide!"); this.getServer().getPluginManager().disablePlugin(this); } // -------------------------------------------- // @@ -201,11 +181,7 @@ public abstract class MPlugin extends JavaPlugin { // -------------------------------------------- // public GsonBuilder getGsonBuilder() { - return new GsonBuilder() - .setPrettyPrinting() - .disableHtmlEscaping() - .serializeNulls() - .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE); + return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE); } // -------------------------------------------- // @@ -231,12 +207,10 @@ public abstract class MPlugin extends JavaPlugin { public void initTXT() { this.addRawTags(); - Type type = new TypeToken>() { - }.getType(); + Type type = new TypeToken>() {}.getType(); Map tagsFromFile = this.persist.load(type, "tags"); - if (tagsFromFile != null) { this.rawTags.putAll(tagsFromFile); } - this.persist.save(this.rawTags, "tags"); + 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())); @@ -257,10 +231,8 @@ public abstract class MPlugin extends JavaPlugin { } public boolean handleCommand(final CommandSender sender, String commandString, boolean testOnly, boolean async) { - boolean noSlash = true; - if (commandString.startsWith("/")) { - noSlash = false; - commandString = commandString.substring(1); + boolean noSlash = true; if (commandString.startsWith("/")) { + noSlash = false; commandString = commandString.substring(1); } for (final MCommand command : this.getBaseCommands()) { @@ -283,14 +255,12 @@ public abstract class MPlugin extends JavaPlugin { command.execute(sender, args); } }); - } - else { command.execute(sender, args); } + } else { command.execute(sender, args); } return true; } } - } - return false; + } return false; } public boolean handleCommand(CommandSender sender, String commandString) { diff --git a/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java b/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java index 87275147..7190caea 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java @@ -28,8 +28,7 @@ public class MPluginSecretPlayerListener implements Listener { if (p.handleCommand(event.getPlayer(), event.getMessage())) { if (p.logPlayerCommands()) { Bukkit.getLogger().info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": " + event.getMessage()); - } - event.setCancelled(true); + } event.setCancelled(true); } } @@ -38,12 +37,10 @@ public class MPluginSecretPlayerListener implements Listener { 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); + } event.setCancelled(true); } - Player speaker = event.getPlayer(); - String format = event.getFormat(); + Player speaker = event.getPlayer(); String format = event.getFormat(); format = format.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTag(speaker)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(speaker)); event.setFormat(format); } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/EntityCollection.java b/src/main/java/com/massivecraft/factions/zcore/persist/EntityCollection.java index 99a315a3..23dd39d7 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/EntityCollection.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/EntityCollection.java @@ -71,13 +71,8 @@ public abstract class EntityCollection { // -------------------------------------------- // public EntityCollection(Class entityClass, Collection entities, Map id2entity, File file, Gson gson, boolean creative) { - this.entityClass = entityClass; - this.entities = entities; - this.id2entity = id2entity; - this.file = file; - this.gson = gson; - this.creative = creative; - this.nextId = 1; + this.entityClass = entityClass; this.entities = entities; this.id2entity = id2entity; this.file = file; + this.gson = gson; this.creative = creative; this.nextId = 1; EM.setEntitiesCollectionForEntityClass(this.entityClass, this); } @@ -99,24 +94,19 @@ public abstract class EntityCollection { } public E get(String id) { - if (this.creative) { return this.getCreative(id); } - return id2entity.get(id); + if (this.creative) { return this.getCreative(id); } return id2entity.get(id); } public E getCreative(String id) { - E e = id2entity.get(id); - if (e != null) { return e; } - return this.create(id); + E e = id2entity.get(id); if (e != null) { return e; } return this.create(id); } public boolean exists(String id) { - if (id == null) { return false; } - return id2entity.get(id) != null; + if (id == null) { return false; } return id2entity.get(id) != null; } public E getBestIdMatch(String pattern) { - String id = TextUtil.getBestStartWithCI(this.id2entity.keySet(), pattern); - if (id == null) { return null; } + String id = TextUtil.getBestStartWithCI(this.id2entity.keySet(), pattern); if (id == null) { return null; } return this.id2entity.get(id); } @@ -131,18 +121,13 @@ public abstract class EntityCollection { public synchronized E create(String id) { if (!this.isIdFree(id)) { return null; } - E e = null; - try { + E e = null; try { e = this.entityClass.newInstance(); } catch (Exception ignored) { ignored.printStackTrace(); } - e.setId(id); - this.entities.add(e); - this.id2entity.put(e.getId(), e); - this.updateNextIdForId(id); - return e; + e.setId(id); this.entities.add(e); this.id2entity.put(e.getId(), e); this.updateNextIdForId(id); return e; } // -------------------------------------------- // @@ -150,23 +135,16 @@ public abstract class EntityCollection { // -------------------------------------------- // public void attach(E entity) { - if (entity.getId() != null) { return; } - entity.setId(this.getNextId()); - this.entities.add(entity); + if (entity.getId() != null) { return; } entity.setId(this.getNextId()); this.entities.add(entity); this.id2entity.put(entity.getId(), entity); } public void detach(E entity) { - entity.preDetach(); - this.entities.remove(entity); - this.id2entity.remove(entity.getId()); - entity.postDetach(); + entity.preDetach(); this.entities.remove(entity); this.id2entity.remove(entity.getId()); entity.postDetach(); } public void detach(String id) { - E entity = this.id2entity.get(id); - if (entity == null) { return; } - this.detach(entity); + E entity = this.id2entity.get(id); if (entity == null) { return; } this.detach(entity); } public boolean attached(E entity) { @@ -185,18 +163,15 @@ public abstract class EntityCollection { private boolean saveIsRunning = false; public boolean saveToDisc() { - if (saveIsRunning) { return true; } - saveIsRunning = true; + if (saveIsRunning) { return true; } saveIsRunning = true; - Map entitiesThatShouldBeSaved = new HashMap(); - for (E entity : this.entities) { + Map entitiesThatShouldBeSaved = new HashMap(); for (E entity : this.entities) { if (entity.shouldBeSaved()) { entitiesThatShouldBeSaved.put(entity.getId(), entity); } } - saveIsRunning = false; - return this.saveCore(this.file, entitiesThatShouldBeSaved); + saveIsRunning = false; return this.saveCore(this.file, entitiesThatShouldBeSaved); } private boolean saveCore(File target, Map entities) { @@ -204,14 +179,9 @@ public abstract class EntityCollection { } public boolean loadFromDisc() { - Map id2entity = this.loadCore(); - if (id2entity == null) { return false; } - this.entities.clear(); - this.entities.addAll(id2entity.values()); - this.id2entity.clear(); - this.id2entity.putAll(id2entity); - this.fillIds(); - return true; + Map id2entity = this.loadCore(); if (id2entity == null) { return false; } this.entities.clear(); + this.entities.addAll(id2entity.values()); this.id2entity.clear(); this.id2entity.putAll(id2entity); + this.fillIds(); return true; } private Map loadCore() { @@ -219,45 +189,37 @@ public abstract class EntityCollection { return new HashMap(); } - String content = DiscUtil.readCatch(this.file); - if (content == null) { + String content = DiscUtil.readCatch(this.file); if (content == null) { return null; } - Type type = this.getMapType(); - if (type.toString().contains("FPlayer")) { + Type type = this.getMapType(); if (type.toString().contains("FPlayer")) { Map data = this.gson.fromJson(content, type); Set list = whichKeysNeedMigration(data.keySet()); - Set invalidList = whichKeysAreInvalid(list); - list.removeAll(invalidList); + Set invalidList = whichKeysAreInvalid(list); list.removeAll(invalidList); 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 file = new File(this.file.getParentFile(), "players.json.old"); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); - } - saveCore(file, (Map) data); + } saveCore(file, (Map) data); 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) { + 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 (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(); @@ -265,8 +227,7 @@ public abstract class EntityCollection { if (player == null) { // The player never existed here, and shouldn't persist - invalidList.add(value); - continue; + invalidList.add(value); continue; } player.setId(id); // Update the object so it knows @@ -276,29 +237,23 @@ public abstract class EntityCollection { } } catch (Exception e) { e.printStackTrace(); - } - if (invalidList.size() > 0) { + } 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, (Map) data); // Update the flatfile + } saveCore(this.file, (Map) data); // Update the flatfile Bukkit.getLogger().log(Level.INFO, "Done converting players.json to UUID."); - } - return (Map) data; - } - else { + } return (Map) data; + } else { Map data = this.gson.fromJson(content, type); // Do we have any names that need updating in claims or invites? - int needsUpdate = 0; - for (String string : data.keySet()) { - Faction f = data.get(string); - needsUpdate += whichKeysNeedMigration(f.getInvites()).size(); + int needsUpdate = 0; for (String string : data.keySet()) { + Faction f = data.get(string); needsUpdate += whichKeysNeedMigration(f.getInvites()).size(); Map> claims = f.getClaimOwnership(); for (FLocation key : f.getClaimOwnership().keySet()) { needsUpdate += whichKeysNeedMigration(claims.get(key)).size(); @@ -310,13 +265,11 @@ public abstract class EntityCollection { 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 file = new File(this.file.getParentFile(), "factions.json.old"); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); - } - saveCore(file, (Map) data); + } saveCore(file, (Map) data); 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."); @@ -324,18 +277,15 @@ public abstract class EntityCollection { // Update claim ownership for (String string : data.keySet()) { - Faction f = data.get(string); - Map> claims = f.getClaimOwnership(); + Faction f = data.get(string); Map> claims = f.getClaimOwnership(); for (FLocation key : claims.keySet()) { Set set = claims.get(key); Set list = whichKeysNeedMigration(set); if (list.size() > 0) { - UUIDFetcher fetcher = new UUIDFetcher(new ArrayList(list)); - try { - Map response = fetcher.call(); - for (String value : response.keySet()) { + 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... @@ -343,8 +293,7 @@ public abstract class EntityCollection { } } catch (Exception e) { e.printStackTrace(); - } - claims.put(key, set); // Update + } claims.put(key, set); // Update } } } @@ -352,15 +301,12 @@ public abstract class EntityCollection { // Update invites for (String string : data.keySet()) { - Faction f = data.get(string); - Set invites = f.getInvites(); + 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()) { + 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... @@ -374,14 +320,12 @@ public abstract class EntityCollection { saveCore(this.file, (Map) data); // Update the flatfile Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID."); - } - return (Map) data; + } return (Map) data; } } private Set whichKeysNeedMigration(Set keys) { - HashSet list = new HashSet(); - for (String value : 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}")) { @@ -389,19 +333,16 @@ public abstract class EntityCollection { list.add(value); } } - } - return list; + } return list; } private Set whichKeysAreInvalid(Set keys) { - Set list = new HashSet(); - for (String value : keys) { + Set list = new HashSet(); for (String value : keys) { if (!value.matches("[a-zA-Z0-9_]{2,16}")) { // Not a valid player name.. go ahead and mark it for removal list.add(value); } - } - return list; + } return list; } // -------------------------------------------- // @@ -411,8 +352,7 @@ public abstract class EntityCollection { public String getNextId() { while (!isIdFree(this.nextId)) { this.nextId += 1; - } - return Integer.toString(this.nextId); + } return Integer.toString(this.nextId); } public boolean isIdFree(String id) { @@ -424,12 +364,8 @@ public abstract class EntityCollection { } protected synchronized void fillIds() { - this.nextId = 1; - for (Entry entry : this.id2entity.entrySet()) { - String id = entry.getKey(); - E entity = entry.getValue(); - entity.id = id; - this.updateNextIdForId(id); + this.nextId = 1; for (Entry entry : this.id2entity.entrySet()) { + String id = entry.getKey(); E entity = entry.getValue(); entity.id = id; this.updateNextIdForId(id); } } @@ -441,8 +377,7 @@ public abstract class EntityCollection { protected void updateNextIdForId(String id) { try { - int idAsInt = Integer.parseInt(id); - this.updateNextIdForId(idAsInt); + int idAsInt = Integer.parseInt(id); this.updateNextIdForId(idAsInt); } catch (Exception ignored) { } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntity.java b/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntity.java index cbe00c6e..3e2724a9 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntity.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntity.java @@ -9,8 +9,7 @@ public class PlayerEntity extends Entity { public Player getPlayer() { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getUniqueId().toString().equals(this.getId())) { return player; } - } - return null; + } return null; } public boolean isOnline() { @@ -19,8 +18,7 @@ public class PlayerEntity extends Entity { // 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); + Player target = this.getPlayer(); return target != null && player.canSee(target); } public boolean isOffline() { @@ -32,9 +30,7 @@ public class PlayerEntity extends Entity { // -------------------------------------------- // public void sendMessage(String msg) { - Player player = this.getPlayer(); - if (player == null) { return; } - player.sendMessage(msg); + Player player = this.getPlayer(); if (player == null) { return; } player.sendMessage(msg); } public void sendMessage(List msgs) { diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntityCollection.java b/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntityCollection.java index 3945469f..f61d351e 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntityCollection.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/PlayerEntityCollection.java @@ -34,10 +34,8 @@ public abstract class PlayerEntityCollection extends EntityCol } public Set getOnline() { - Set entities = new HashSet(); - for (Player player : Bukkit.getServer().getOnlinePlayers()) { + Set entities = new HashSet(); for (Player player : Bukkit.getServer().getOnlinePlayers()) { entities.add(this.get(player)); - } - return entities; + } return entities; } } 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 c18fe83d..5d2f989d 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java @@ -12,11 +12,7 @@ public class SaveTask implements Runnable { } public void run() { - if (!p.getAutoSave() || running) { return; } - running = true; - p.preAutoSave(); - EM.saveAllToDisc(); - p.postAutoSave(); - running = false; + if (!p.getAutoSave() || running) { return; } running = true; p.preAutoSave(); EM.saveAllToDisc(); + p.postAutoSave(); running = false; } } 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 de989f05..a2b8135e 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java @@ -14,21 +14,14 @@ public class DiscUtil { // -------------------------------------------- // 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) { + 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; + } in.close(); return output; } public static void writeBytes(File file, byte[] bytes) throws IOException { - FileOutputStream out = new FileOutputStream(file); - out.write(bytes); - out.close(); + FileOutputStream out = new FileOutputStream(file); out.write(bytes); out.close(); } // -------------------------------------------- // @@ -49,8 +42,7 @@ public class DiscUtil { public static boolean writeCatch(File file, String content) { try { - write(file, content); - return true; + write(file, content); return true; } catch (Exception e) { return false; } @@ -72,8 +64,7 @@ public class DiscUtil { try { return string.getBytes(UTF8); } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return null; + e.printStackTrace(); return null; } } @@ -81,8 +72,7 @@ public class DiscUtil { try { return new String(bytes, UTF8); } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return null; + e.printStackTrace(); return null; } } 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 c322b5f1..f47d28be 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java @@ -17,8 +17,7 @@ public class PermUtil { protected MPlugin p; public PermUtil(MPlugin p) { - this.p = p; - this.setup(); + this.p = p; this.setup(); } public String getForbiddenMessage(String perm) { @@ -36,11 +35,9 @@ public class PermUtil { } public String getPermissionDescription(String perm) { - String desc = permissionDescriptions.get(perm); - if (desc == null) { + String desc = permissionDescriptions.get(perm); if (desc == null) { return Lang.permDoThat; - } - return desc; + } return desc; } /** @@ -59,20 +56,16 @@ public class PermUtil { public boolean has(CommandSender me, String perm, boolean informSenderIfNot) { if (has(me, perm)) { return true; - } - else if (informSenderIfNot && me != null) { + } else if (informSenderIfNot && me != null) { me.sendMessage(this.getForbiddenMessage(perm)); - } - return false; + } return false; } public T pickFirstVal(CommandSender me, Map perm2val) { - if (perm2val == null) { return null; } - T ret = null; + if (perm2val == null) { return null; } T ret = null; for (Entry entry : perm2val.entrySet()) { - ret = entry.getValue(); - if (has(me, entry.getKey())) { break; } + ret = entry.getValue(); if (has(me, entry.getKey())) { break; } } 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 435fae7e..0c025ca1 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/Persist.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/Persist.java @@ -65,9 +65,7 @@ public class Persist { public T loadOrSaveDefault(T def, Class clazz, File file) { if (!file.exists()) { - p.log("Creating default: " + file); - this.save(def, file); - return def; + p.log("Creating default: " + file); this.save(def, file); return def; } T loaded = this.load(clazz, file); @@ -76,10 +74,8 @@ public class Persist { 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); + 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; } @@ -112,14 +108,12 @@ public class Persist { } public T load(Class clazz, File file) { - String content = DiscUtil.readCatch(file); - if (content == null) { + String content = DiscUtil.readCatch(file); if (content == null) { return null; } try { - T instance = p.gson.fromJson(content, clazz); - return instance; + T instance = p.gson.fromJson(content, clazz); return instance; } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely p.log(Level.WARNING, ex.getMessage()); } @@ -136,8 +130,7 @@ public class Persist { @SuppressWarnings("unchecked") public T load(Type typeOfT, File file) { - String content = DiscUtil.readCatch(file); - if (content == null) { + String content = DiscUtil.readCatch(file); if (content == 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 be586a53..c5b7c613 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java @@ -31,8 +31,7 @@ public class SmokeUtil { // Single ======== public static void spawnSingle(Location location, int direction) { - if (location == null) { return; } - location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); + if (location == null) { return; } location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); } public static void spawnSingle(Location location) { @@ -58,8 +57,7 @@ public class SmokeUtil { // Random Cloud ======== public static void spawnCloudRandom(Location location, float thickness) { - int singles = (int) Math.floor(thickness * 9); - for (int i = 0; i < singles; i++) { + int singles = (int) Math.floor(thickness * 9); for (int i = 0; i < singles; i++) { spawnSingleRandom(location.clone()); } } 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 22603317..a542f47c 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TL.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TL.java @@ -42,8 +42,7 @@ public enum TL { * @param start The default string. */ TL(String path, String start) { - this.path = path; - this.def = start; + this.path = path; this.def = start; } /** 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 ed0fdd98..cbc26a78 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java @@ -37,20 +37,13 @@ public class TextUtil { public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); 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) { + 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 { + } else { matcher.appendReplacement(ret, repl); } - } - matcher.appendTail(ret); - return ret.toString(); + } matcher.appendTail(ret); return ret.toString(); } // -------------------------------------------- // @@ -58,49 +51,20 @@ public class TextUtil { // -------------------------------------------- // public static String parseColor(String string) { - string = parseColorAmp(string); - string = parseColorAcc(string); - string = parseColorTags(string); - return string; + string = parseColorAmp(string); string = parseColorAcc(string); string = parseColorTags(string); 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; + string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2"); string = string.replace("&&", "&"); return string; } 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("`p", ChatColor.LIGHT_PURPLE.toString()).replace("`P", 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()); + 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("`p", ChatColor.LIGHT_PURPLE.toString()).replace("`P", 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"); + 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"); } // -------------------------------------------- // @@ -112,19 +76,15 @@ public class TextUtil { } public static String implode(List list, String glue) { - StringBuilder ret = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { + StringBuilder ret = new StringBuilder(); for (int i = 0; i < list.size(); i++) { if (i != 0) { ret.append(glue); - } - ret.append(list.get(i)); - } - return ret.toString(); + } ret.append(list.get(i)); + } return ret.toString(); } public static String repeat(String s, int times) { - if (times <= 0) { return ""; } - else { return s + repeat(s, times - 1); } + if (times <= 0) { return ""; } else { return s + repeat(s, times - 1); } } // -------------------------------------------- // @@ -148,37 +108,27 @@ public class TextUtil { public String titleize(String str) { String center = ".[ " + parseTags("") + str + parseTags("") + " ]."; - int centerlen = ChatColor.stripColor(center).length(); - int pivot = titleizeLine.length() / 2; - int eatLeft = (centerlen / 2) - titleizeBalance; - int eatRight = (centerlen - eatLeft) + titleizeBalance; + 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("") + titleizeLine.substring(0, pivot - eatLeft) + center + titleizeLine.substring(pivot + eatRight); - } - else { return parseTags("") + center; } + } else { return parseTags("") + center; } } public ArrayList getPage(List lines, int pageHumanBased, String title) { - ArrayList ret = new ArrayList(); - int pageZeroBased = pageHumanBased - 1; - int pageheight = 9; + ArrayList ret = new ArrayList(); int pageZeroBased = pageHumanBased - 1; int pageheight = 9; int pagecount = (lines.size() / pageheight) + 1; ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount)); if (pagecount == 0) { - ret.add(this.parseTags("Sorry. No Pages available.")); - return ret; - } - else if (pageZeroBased < 0 || pageHumanBased > pagecount) { - ret.add(this.parseTags("Invalid page. Must be between 1 and " + pagecount)); - return ret; + ret.add(this.parseTags("Sorry. No Pages available.")); return ret; + } else if (pageZeroBased < 0 || pageHumanBased > pagecount) { + ret.add(this.parseTags("Invalid page. Must be between 1 and " + pagecount)); return ret; } - int from = pageZeroBased * pageheight; - int to = from + pageheight; - if (to > lines.size()) { + int from = pageZeroBased * pageheight; int to = from + pageheight; if (to > lines.size()) { to = lines.size(); } @@ -188,25 +138,18 @@ public class TextUtil { } public static String getBestStartWithCI(Collection candidates, String start) { - String ret = null; - int best = 0; + String ret = null; int best = 0; - start = start.toLowerCase(); - int minlength = start.length(); - for (String candidate : candidates) { + 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) { + int lendiff = candidate.length() - minlength; if (lendiff == 0) { return candidate; + } if (lendiff < best || best == 0) { + best = lendiff; ret = candidate; } - if (lendiff < best || best == 0) { - best = lendiff; - ret = candidate; - } - } - return ret; + } return ret; } } 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 e41da56c..ceaeedef 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java @@ -25,8 +25,7 @@ public class UUIDFetcher implements Callable> { private final boolean rateLimiting; public UUIDFetcher(List names, boolean rateLimiting) { - this.names = ImmutableList.copyOf(names); - this.rateLimiting = rateLimiting; + this.names = ImmutableList.copyOf(names); this.rateLimiting = rateLimiting; } public UUIDFetcher(List names) { @@ -35,42 +34,30 @@ public class UUIDFetcher implements Callable> { 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++) { + 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); + 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) { + } if (rateLimiting && i != requests - 1) { Thread.sleep(100L); } - } - return uuidMap; + } return uuidMap; } private static void writeBody(HttpURLConnection connection, String body) throws Exception { - OutputStream stream = connection.getOutputStream(); - stream.write(body.getBytes()); - stream.flush(); + 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; + 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) { @@ -78,20 +65,15 @@ public class UUIDFetcher implements Callable> { } public static byte[] toBytes(UUID uuid) { - ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); - byteBuffer.putLong(uuid.getMostSignificantBits()); - byteBuffer.putLong(uuid.getLeastSignificantBits()); - return byteBuffer.array(); + 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); + } 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 {