From d2146b58750bc13d815e1585f1f992007cf3fa2c Mon Sep 17 00:00:00 2001 From: Joe Goett Date: Fri, 7 Nov 2014 23:37:28 -0500 Subject: [PATCH] Code cleanup --- src/main/java/mytown/MyTown.java | 8 +- .../java/mytown/api/events/TownEvent.java | 2 + .../api/interfaces/IBlockWhitelister.java | 2 - .../api/interfaces/IHasBlockWhitelists.java | 3 + .../mytown/api/interfaces/IHasBlocks.java | 1 + .../java/mytown/api/interfaces/IHasFlags.java | 2 - src/main/java/mytown/commands/Commands.java | 50 ++++---- .../java/mytown/commands/CommandsAdmin.java | 14 +-- .../mytown/commands/CommandsAssistant.java | 29 +++-- .../mytown/commands/CommandsEveryone.java | 15 ++- .../mytown/commands/CommandsOutsider.java | 40 +++---- src/main/java/mytown/config/FlagsConfig.java | 19 +-- src/main/java/mytown/config/RanksConfig.java | 2 +- .../java/mytown/config/WildPermsConfig.java | 18 +-- .../mytown/datasource/MyTownDatasource.java | 14 +-- .../datasource/MyTownDatasource_SQL.java | 80 +++++++------ .../mytown/datasource/MyTownUniverse.java | 17 ++- .../java/mytown/entities/BlockWhitelist.java | 6 +- src/main/java/mytown/entities/Plot.java | 22 ++-- src/main/java/mytown/entities/Resident.java | 27 +++-- src/main/java/mytown/entities/Town.java | 78 ++++++------ src/main/java/mytown/entities/Wild.java | 27 +++-- src/main/java/mytown/entities/flag/Flag.java | 7 +- .../java/mytown/entities/flag/FlagType.java | 51 +++++--- .../java/mytown/handlers/PlayerTracker.java | 22 ++-- .../protection/BloodMagicProtection.java | 44 +++---- .../mytown/protection/BotaniaProtection.java | 16 +-- .../BuildCraftFactoryProtection.java | 30 +++-- .../BuildCraftTransportProtection.java | 10 -- .../protection/ExtraUtilitiesProtection.java | 22 ++-- .../java/mytown/protection/IC2Protection.java | 18 +-- .../mytown/protection/MekanismProtection.java | 2 +- .../MinefactoryReloadedProtection.java | 26 ++-- .../java/mytown/protection/Protection.java | 53 ++++++--- .../java/mytown/protection/Protections.java | 111 +++++++++--------- .../protection/QuarryPlusProtection.java | 14 +-- .../ThermalExpansionProtection.java | 34 +++--- .../mytown/protection/VanillaProtection.java | 33 ++---- .../java/mytown/proxies/DatasourceProxy.java | 2 +- .../java/mytown/proxies/mod/ModProxies.java | 6 +- .../java/mytown/proxies/mod/ModProxy.java | 6 +- .../mytown/proxies/plugin/BukkitCompat.java | 10 +- .../java/mytown/proxies/plugin/PEXCompat.java | 37 +++--- src/main/java/mytown/util/BlockPos.java | 3 +- src/main/java/mytown/util/ChunkPos.java | 10 +- src/main/java/mytown/util/Constants.java | 4 - src/main/java/mytown/util/Formatter.java | 14 +-- src/main/java/mytown/util/Utils.java | 55 ++++----- 48 files changed, 556 insertions(+), 560 deletions(-) diff --git a/src/main/java/mytown/MyTown.java b/src/main/java/mytown/MyTown.java index 00a520a9..137c4f6c 100644 --- a/src/main/java/mytown/MyTown.java +++ b/src/main/java/mytown/MyTown.java @@ -68,9 +68,9 @@ public void preInit(FMLPreInitializationEvent ev) { // Register ICrashCallable's FMLCommonHandler.instance().registerCrashCallable(new DatasourceCrashCallable()); - if(ev.getSide() == Side.SERVER) { + if (ev.getSide() == Side.SERVER) { isCauldron = MinecraftServer.getServer().getServerModName().contains("cauldron") || MinecraftServer.getServer().getServerModName().contains("mcpc"); - if(isCauldron) + if (isCauldron) BukkitCompat.getInstance().loadPEX(ev.getSourceFile()); //MyTown.instance.log.info("Server is using cauldron or some implementation between forge and bukkit/spigot."); } @@ -118,7 +118,7 @@ public void serverStopping(FMLServerStoppingEvent ev) { private void registerCommands() { Method m = null; try { - if(isCauldron && BukkitCompat.getInstance().hasPlugin("PermissionsEx")) { + if (isCauldron && BukkitCompat.getInstance().hasPlugin("PermissionsEx")) { m = PEXCompat.class.getMethod("firstPermissionBreachPEX", String.class, ICommandSender.class); } else { m = Commands.class.getMethod("firstPermissionBreach", String.class, ICommandSender.class); @@ -130,7 +130,7 @@ private void registerCommands() { CommandManager.registerCommands(CommandsEveryone.class, m); CommandManager.registerCommands(CommandsAssistant.class, m); - if(Config.modifiableRanks) + if (Config.modifiableRanks) CommandManager.registerCommands(CommandsAssistant.ModifyRanks.class, m); CommandManager.registerCommands(CommandsAdmin.class); diff --git a/src/main/java/mytown/api/events/TownEvent.java b/src/main/java/mytown/api/events/TownEvent.java index 97c0383a..305c8f79 100644 --- a/src/main/java/mytown/api/events/TownEvent.java +++ b/src/main/java/mytown/api/events/TownEvent.java @@ -33,6 +33,7 @@ public TownDeleteEvent(Town town) { // TODO: Make them cancelable? public static class TownEnterEvent extends TownEvent { public Resident resident = null; + public TownEnterEvent(Town town, Resident resident) { super(town); this.resident = resident; @@ -41,6 +42,7 @@ public TownEnterEvent(Town town, Resident resident) { public static class TownEnterInRangeEvent extends TownEvent { public Resident resident = null; + public TownEnterInRangeEvent(Town town, Resident resident) { super(town); this.resident = resident; diff --git a/src/main/java/mytown/api/interfaces/IBlockWhitelister.java b/src/main/java/mytown/api/interfaces/IBlockWhitelister.java index 2dff99a0..4c968319 100644 --- a/src/main/java/mytown/api/interfaces/IBlockWhitelister.java +++ b/src/main/java/mytown/api/interfaces/IBlockWhitelister.java @@ -1,7 +1,5 @@ package mytown.api.interfaces; -import mytown.entities.Plot; -import mytown.entities.Town; import mytown.entities.flag.FlagType; /** diff --git a/src/main/java/mytown/api/interfaces/IHasBlockWhitelists.java b/src/main/java/mytown/api/interfaces/IHasBlockWhitelists.java index 9358c5cc..2499450f 100644 --- a/src/main/java/mytown/api/interfaces/IHasBlockWhitelists.java +++ b/src/main/java/mytown/api/interfaces/IHasBlockWhitelists.java @@ -12,11 +12,14 @@ public interface IHasBlockWhitelists { void addBlockWhitelist(BlockWhitelist bw); boolean hasBlockWhitelist(BlockWhitelist bw); + boolean hasBlockWhitelist(int dim, int x, int y, int z, FlagType flagType); void removeBlockWhitelist(BlockWhitelist bw); + void removeBlockWhitelist(int dim, int x, int y, int z, FlagType flagType); BlockWhitelist getBlockWhitelist(int dim, int x, int y, int z, FlagType flagType); + List getWhitelists(); } diff --git a/src/main/java/mytown/api/interfaces/IHasBlocks.java b/src/main/java/mytown/api/interfaces/IHasBlocks.java index 2c9d3f70..6f56dace 100644 --- a/src/main/java/mytown/api/interfaces/IHasBlocks.java +++ b/src/main/java/mytown/api/interfaces/IHasBlocks.java @@ -55,6 +55,7 @@ public interface IHasBlocks { /** * Sets the number of extra blocks it can have. + * * @param extra */ public void setExtraBlocks(int extra); diff --git a/src/main/java/mytown/api/interfaces/IHasFlags.java b/src/main/java/mytown/api/interfaces/IHasFlags.java index 9caf254f..36d9f4a1 100644 --- a/src/main/java/mytown/api/interfaces/IHasFlags.java +++ b/src/main/java/mytown/api/interfaces/IHasFlags.java @@ -4,8 +4,6 @@ import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; -import java.util.List; - /** * Created by AfterWind on 8/26/2014. * Why do we need interfaces for this? diff --git a/src/main/java/mytown/commands/Commands.java b/src/main/java/mytown/commands/Commands.java index b282d6d2..aa5d4466 100644 --- a/src/main/java/mytown/commands/Commands.java +++ b/src/main/java/mytown/commands/Commands.java @@ -18,7 +18,6 @@ import mytown.util.exceptions.MyTownCommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ChatComponentText; @@ -63,21 +62,21 @@ public static boolean callSubFunctions(ICommandSender sender, List args, public static void sendHelpMessage(ICommandSender sender, String permissionBase) { List scList = CommandManager.getSubCommandsList(permissionBase); String command = null; - for(String s = permissionBase; s != null; s = CommandManager.getParentPermNode(s)) { - if(command == null) + for (String s = permissionBase; s != null; s = CommandManager.getParentPermNode(s)) { + if (command == null) command = CommandManager.commandNames.get(s); else command = new StringBuilder(command).insert(0, CommandManager.commandNames.get(s) + " ").toString(); } sendMessageBackToSender(sender, "/" + command + ": "); - for(String s : scList) { + for (String s : scList) { sendMessageBackToSender(sender, " " + CommandManager.commandNames.get(s) + ": " + getLocal().getLocalization(s + ".help")); } } public static void sendHelpMessageWithArgs(ICommandSender sender, List args, String permBase) { String node; - if(args.size() < 1) { + if (args.size() < 1) { //If no arguments are provided then we check for the base permission node = permBase; } else { @@ -87,9 +86,9 @@ public static void sendHelpMessageWithArgs(ICommandSender sender, List a String command = "/" + CommandManager.commandNames.get(permBase); String prevNode = permBase; - for(String s : args) { + for (String s : args) { String t = CommandManager.getSubCommandNode(s, prevNode); - if(t != null) { + if (t != null) { command += " " + s; prevNode = t; } else @@ -98,7 +97,7 @@ public static void sendHelpMessageWithArgs(ICommandSender sender, List a sendMessageBackToSender(sender, command); List scList = CommandManager.getSubCommandsList(node); - if(scList == null || scList.size() == 0) { + if (scList == null || scList.size() == 0) { sendMessageBackToSender(sender, " " + getLocal().getLocalization(node + ".help")); } else { for (String s : scList) { @@ -108,13 +107,12 @@ public static void sendHelpMessageWithArgs(ICommandSender sender, List a } - public static boolean firstPermissionBreach(String permission, ICommandSender sender) { // Since everybody should have permission to /t if (permission.equals("mytown.cmd")) return true; - if(!(sender instanceof EntityPlayer)) + if (!(sender instanceof EntityPlayer)) return true; Resident res = getDatasource().getOrMakeResident(sender); @@ -201,21 +199,21 @@ public static ImmutableList getInvitesFromResident(Resident res) { public static Flag getFlagFromType(IHasFlags hasFlags, FlagType flagType) { Flag flag = hasFlags.getFlag(flagType); - if(flag == null) + if (flag == null) throw new MyTownCommandException("mytown.cmd.err.flagNotExists", flagType.toString()); return flag; } public static Flag getFlagFromName(IHasFlags hasFlags, String name) { Flag flag = hasFlags.getFlag(FlagType.valueOf(name)); - if(flag == null) + if (flag == null) throw new MyTownCommandException("mytown.cmd.err.flagNotExists", name); return flag; } public static TownBlock getBlockAtResident(Resident res) { TownBlock block = getDatasource().getBlock(res.getPlayer().dimension, res.getPlayer().chunkCoordX, res.getPlayer().chunkCoordZ); - if(block == null) + if (block == null) throw new MyTownCommandException("mytown.cmd.err.claim.notexist", res.getSelectedTown()); return block; } @@ -255,28 +253,28 @@ public static FlagType getFlagTypeFromName(String name) { } public static int getPaymentStack(ICommandSender sender, int minAmount) { - if(!(sender instanceof EntityPlayer)) + if (!(sender instanceof EntityPlayer)) throw new MyTownCommandException("The sender is not a player!"); - if(minAmount == 0) + if (minAmount == 0) return 0; - EntityPlayer player = (EntityPlayer)sender; + EntityPlayer player = (EntityPlayer) sender; int stackNumber = -1; - for(int i = 0; i < player.inventory.mainInventory.length; i++) { + for (int i = 0; i < player.inventory.mainInventory.length; i++) { ItemStack itemStack = player.inventory.mainInventory[i]; - if(itemStack == null) + if (itemStack == null) continue; - if(GameRegistry.findUniqueIdentifierFor(itemStack.getItem()).name.equals(Config.costItemName) && itemStack.stackSize >= minAmount) { + if (GameRegistry.findUniqueIdentifierFor(itemStack.getItem()).name.equals(Config.costItemName) && itemStack.stackSize >= minAmount) { stackNumber = i; break; } } - if(stackNumber == -1) + if (stackNumber == -1) throw new MyTownCommandException("mytown.cmd.err.cost", minAmount, Config.costItemName); return stackNumber; } public static void sendMessageBackToSender(ICommandSender sender, String message) { - if(sender instanceof EntityPlayer) { + if (sender instanceof EntityPlayer) { Resident res = getDatasource().getOrMakeResident(sender); res.sendMessage(message); } else { @@ -285,16 +283,16 @@ public static void sendMessageBackToSender(ICommandSender sender, String message } public static void returnPaymentStack(ICommandSender sender, int amount) { - if(sender instanceof EntityPlayer) { - EntityPlayer player = (EntityPlayer)sender; + if (sender instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) sender; String[] itemName = Config.costItemName.split(":"); Item item; - if(itemName.length > 1) { + if (itemName.length > 1) { item = GameRegistry.findItem(itemName[0], itemName[1]); } else { - item = (Item)Item.itemRegistry.getObject(Config.costItemName); + item = (Item) Item.itemRegistry.getObject(Config.costItemName); } - for(int left = amount; left > 0; left -= 64) { + for (int left = amount; left > 0; left -= 64) { ItemStack stack = new ItemStack(item, left > 64 ? 64 : left); //stack = addToInventory(player.inventory, stack); if (!player.inventory.addItemStackToInventory(stack)) { diff --git a/src/main/java/mytown/commands/CommandsAdmin.java b/src/main/java/mytown/commands/CommandsAdmin.java index c6c1d812..16c57bee 100644 --- a/src/main/java/mytown/commands/CommandsAdmin.java +++ b/src/main/java/mytown/commands/CommandsAdmin.java @@ -270,7 +270,7 @@ public static void permTownCommand(ICommandSender sender, List args, Lis nonPlayers = true, completionKeys = {"townCompletion"}) public static void permTownListCommand(ICommandSender sender, List args) { - if(args.size() < 1) { + if (args.size() < 1) { throw new MyTownWrongUsageException("mytown.adm.cmd.usage.perm.list"); } @@ -298,7 +298,7 @@ public static void permTownListCommand(ICommandSender sender, List args) nonPlayers = true, completionKeys = {"townCompletion", "flagCompletion"}) public static void permTownSetCommand(ICommandSender sender, List args) { - if(args.size() < 3) { + if (args.size() < 3) { throw new MyTownWrongUsageException("mytown.adm.cmd.usage.perm.town.set"); } @@ -320,14 +320,14 @@ public static void permTownSetCommand(ICommandSender sender, List args) parentName = "mytown.adm.cmd.perm.town", completionKeys = {"townCompletion", "flagCompletionWhitelist"}) public static void permTownWhitelistCommand(ICommandSender sender, List args, List subCommands) { - if(args.size() < 2) + if (args.size() < 2) throw new MyTownCommandException("mytown.cmd.usage.plot.whitelist.add"); Resident res = getDatasource().getOrMakeResident(sender); Town town = getTownFromName(args.get(0)); FlagType flagType = getFlagTypeFromName(args.get(1)); - if(flagType.isWhitelistable()) + if (flagType.isWhitelistable()) res.startBlockSelection(flagType, town.getName(), false); else throw new MyTownCommandException("mytown.cmd.err.flag.notForWhitelist"); @@ -358,7 +358,7 @@ public static void permWildListCommand(ICommandSender sender, List args) } formattedFlagList += flag; } - if(formattedFlagList != null) + if (formattedFlagList != null) sendMessageBackToSender(sender, formattedFlagList); else sendMessageBackToSender(sender, getLocal().getLocalization("mytown.cmd.err.flag.list")); @@ -371,7 +371,7 @@ public static void permWildListCommand(ICommandSender sender, List args) nonPlayers = true, completionKeys = {"flagCompletion"}) public static void permWildSetCommand(ICommandSender sender, List args) { - if(args.size() < 2) { + if (args.size() < 2) { throw new MyTownWrongUsageException("mytown.adm.cmd.usage.perm.wild.set"); } FlagType type = getFlagTypeFromName(args.get(0)); @@ -403,7 +403,7 @@ public static void claimCommand(ICommandSender sender, List args) { throw new MyTownCommandException("mytown.cmd.err.claim.already"); if (CommandsAssistant.checkNearby(player.dimension, player.chunkCoordX, player.chunkCoordZ, town)) // Checks if the player can claim far throw new MyTownCommandException("mytown.cmd.err.farClaim.unimplemented"); - //Assert.Perm(player, "mytown.cmd.assistant.claim.far"); + //Assert.Perm(player, "mytown.cmd.assistant.claim.far"); TownBlock block = getDatasource().newBlock(player.dimension, player.chunkCoordX, player.chunkCoordZ, town); if (block == null) throw new MyTownCommandException("Failed to create Block"); // TODO Localize diff --git a/src/main/java/mytown/commands/CommandsAssistant.java b/src/main/java/mytown/commands/CommandsAssistant.java index d124f39f..88089291 100644 --- a/src/main/java/mytown/commands/CommandsAssistant.java +++ b/src/main/java/mytown/commands/CommandsAssistant.java @@ -4,10 +4,10 @@ import mytown.core.ChatUtils; import mytown.core.utils.command.CommandManager; import mytown.core.utils.command.CommandNode; -import mytown.entities.TownBlock; import mytown.entities.Rank; import mytown.entities.Resident; import mytown.entities.Town; +import mytown.entities.TownBlock; import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; import mytown.util.exceptions.MyTownCommandException; @@ -164,7 +164,7 @@ public static void permTownWhitelistCommand(ICommandSender sender, List Town town = getTownFromResident(res); FlagType flagType = getFlagTypeFromName(args.get(1)); - if(flagType.isWhitelistable()) + if (flagType.isWhitelistable()) res.startBlockSelection(flagType, town.getName(), false); else throw new MyTownCommandException("mytown.cmd.err.flag.notForWhitelist"); @@ -336,17 +336,17 @@ public static void ranksPermListCommand(ICommandSender sender, List args parentName = "mytown.cmd", completionKeys = {"residentCompletion"}) public static void passCommand(ICommandSender sender, List args) { - if(args.size() < 1) + if (args.size() < 1) throw new MyTownCommandException("mytown.cmd.usage.leave.pass"); Resident res = getDatasource().getOrMakeResident(sender); Resident target = getResidentFromName(args.get(0)); Town town = getTownFromResident(res); - if(!town.hasResident(target)) { + if (!town.hasResident(target)) { throw new MyTownCommandException("mytown.cmd.err.resident.notsametown", target.getPlayerName(), town.getName()); } - if(town.getResidentRank(res).getName().equals(Rank.theMayorDefaultRank)) { + if (town.getResidentRank(res).getName().equals(Rank.theMayorDefaultRank)) { getDatasource().updateResidentToTownLink(target, town, town.getRank(Rank.theMayorDefaultRank)); target.sendMessage(getLocal().getLocalization("mytown.notification.town.mayorShip.passed")); getDatasource().updateResidentToTownLink(res, town, town.getDefaultRank()); @@ -357,11 +357,11 @@ public static void passCommand(ICommandSender sender, List args) { } @CommandNode( - name="limit", + name = "limit", permission = "mytown.cmd.assistant.plot.limit", parentName = "mytown.cmd.everyone.plot") public static void plotLimitCommand(ICommandSender sender, List args, List subCommands) { - if(args.size() < 1) { + if (args.size() < 1) { Resident res = getDatasource().getOrMakeResident(sender); Town town = getTownFromResident(res); res.sendMessage(getLocal().getLocalization("mytown.notification.town.plot.limit", town.getMaxPlots())); @@ -371,11 +371,11 @@ public static void plotLimitCommand(ICommandSender sender, List args, Li } @CommandNode( - name="set", + name = "set", permission = "mytown.cmd.assistant.plot.limit.set", parentName = "mytown.cmd.assistant.plot.limit") public static void plotLimitSetCommand(ICommandSender sender, List args) { - if(args.size() < 1) { + if (args.size() < 1) { throw new MyTownWrongUsageException("mytown.cmd.usage.plot.limit.set"); } try { @@ -391,21 +391,21 @@ public static void plotLimitSetCommand(ICommandSender sender, List args) } @CommandNode( - name="kick", + name = "kick", permission = "mytown.cmd.assistant.kick", parentName = "mytown.cmd", completionKeys = {"residentCompletion"}) public static void kickCommand(ICommandSender sender, List args) { - if(args.size() < 1) { + if (args.size() < 1) { throw new MyTownWrongUsageException("mytown.cmd.usage.kick"); } Resident res = getDatasource().getOrMakeResident(sender); Resident target = getResidentFromName(args.get(0)); Town town = getTownFromResident(res); - if(!target.getTowns().contains(town)) { + if (!target.getTowns().contains(town)) { throw new MyTownCommandException("mytown.cmd.err.resident.notsametown", args.get(0), town.getName()); } - if(target == res) { + if (target == res) { throw new MyTownCommandException("mytown.cmd.err.kick.self"); } @@ -422,7 +422,7 @@ public static void leaveDeleteCommand(ICommandSender sender, List args) Resident res = getDatasource().getOrMakeResident(sender); Town town = getTownFromResident(res); - if(town.getResidentRank(res).getName().equals(Rank.theMayorDefaultRank)) { + if (town.getResidentRank(res).getName().equals(Rank.theMayorDefaultRank)) { town.notifyEveryone(getLocal().getLocalization("mytown.notification.town.deleted", town.getName(), res.getPlayerName())); returnPaymentStack(sender, Config.costAmountClaim * town.getBlocks().size()); getDatasource().deleteTown(town); @@ -430,7 +430,6 @@ public static void leaveDeleteCommand(ICommandSender sender, List args) } - // Temporary here, might integrate in the methods protected static boolean checkNearby(int dim, int x, int z, Town town) { int[] dx = {1, 0, -1, 0}; diff --git a/src/main/java/mytown/commands/CommandsEveryone.java b/src/main/java/mytown/commands/CommandsEveryone.java index c9db494e..d9f12a3e 100644 --- a/src/main/java/mytown/commands/CommandsEveryone.java +++ b/src/main/java/mytown/commands/CommandsEveryone.java @@ -33,7 +33,7 @@ public static void townCommand(ICommandSender sender, List args, List args, List subCommands) { - if(args.size() > 0) + if (args.size() > 0) callSubFunctions(sender, args, subCommands, "mytown.cmd.everyone.leave"); else { Resident res = getDatasource().getOrMakeResident(sender); @@ -97,8 +97,8 @@ public static void blocksListCommand(ICommandSender sender, List args) { Town town = getTownFromResident(res); String s = null; - for(TownBlock block : town.getBlocks()) { - if(s == null) + for (TownBlock block : town.getBlocks()) { + if (s == null) s = block.toString(); else s += "\n" + block.toString(); @@ -200,11 +200,10 @@ public static void permPlotWhitelistCommand(ICommandSender sender, List Plot plot = getPlotAtResident(res); FlagType flagType = getFlagTypeFromName(args.get(0)); - if(flagType.isWhitelistable()) { + if (flagType.isWhitelistable()) { res.sendMessage(getLocal().getLocalization("mytown.notification.perm.whitelist.start")); res.startBlockSelection(flagType, plot.getTown().getName(), true); - } - else + } else throw new MyTownCommandException("mytown.cmd.err.flag.notForWhitelist"); } @@ -225,7 +224,7 @@ public static void plotMakeCommand(ICommandSender sender, List args) { Resident res = getDatasource().getOrMakeResident(sender); Town town = getTownFromResident(res); - if(!town.canResidentMakePlot(res)) { + if (!town.canResidentMakePlot(res)) { throw new MyTownCommandException("mytown.cmd.err.plot.limit", town.getMaxPlots()); } @@ -351,7 +350,7 @@ public static void plotAddOwnerCommand(ICommandSender sender, List args, Resident target = getResidentFromName(args.get(0)); Town town = getTownFromResident(res); - if(!town.canResidentMakePlot(target)) { + if (!town.canResidentMakePlot(target)) { throw new MyTownCommandException("mytown.cmd.err.plot.limit.toPlayer", target.getPlayerName()); } diff --git a/src/main/java/mytown/commands/CommandsOutsider.java b/src/main/java/mytown/commands/CommandsOutsider.java index 684cb5a0..bea88a91 100644 --- a/src/main/java/mytown/commands/CommandsOutsider.java +++ b/src/main/java/mytown/commands/CommandsOutsider.java @@ -31,8 +31,8 @@ public class CommandsOutsider extends Commands { public static void infoCommand(ICommandSender sender, List args) { List towns = new ArrayList(); - if(args.size() < 1) { - if(sender instanceof EntityPlayer) { + if (args.size() < 1) { + if (sender instanceof EntityPlayer) { Resident res = getDatasource().getOrMakeResident(sender); towns.add(getTownFromResident(res)); } else { @@ -100,15 +100,15 @@ public static void newTownCommand(ICommandSender sender, List args) { res.sendMessage(getLocal().getLocalization("mytown.notification.town.startedCreation", args.get(0))); - if(res.getTowns().size() >= Config.maxTowns) + if (res.getTowns().size() >= Config.maxTowns) throw new MyTownCommandException("mytown.cmd.err.resident.maxTowns"); if (getDatasource().hasTown(args.get(0))) // Is the town name already in use? throw new MyTownCommandException("mytown.cmd.err.newtown.nameinuse", args.get(0)); if (getDatasource().hasBlock(player.dimension, player.chunkCoordX, player.chunkCoordZ)) // Is the Block already claimed? throw new MyTownCommandException("mytown.cmd.err.newtown.positionError"); - for(int x = player.chunkCoordX - Config.distanceBetweenTowns; x <= player.chunkCoordX + Config.distanceBetweenTowns; x++) { - for(int z = player.chunkCoordZ - Config.distanceBetweenTowns; z <= player.chunkCoordZ + Config.distanceBetweenTowns; z++) { - if(Utils.getTownAtPosition(player.dimension, x, z) != null) + for (int x = player.chunkCoordX - Config.distanceBetweenTowns; x <= player.chunkCoordX + Config.distanceBetweenTowns; x++) { + for (int z = player.chunkCoordZ - Config.distanceBetweenTowns; z <= player.chunkCoordZ + Config.distanceBetweenTowns; z++) { + if (Utils.getTownAtPosition(player.dimension, x, z) != null) throw new MyTownCommandException("mytown.cmd.err.newtown.tooClose"); } } @@ -154,7 +154,7 @@ public static void acceptCommand(ICommandSender sender, List args) { if (!invites.contains(town)) throw new MyTownCommandException("mytown.cmd.err.invite.town.noinvitations"); } - if(res.getTowns().size() >= Config.maxTowns) + if (res.getTowns().size() >= Config.maxTowns) throw new MyTownCommandException("mytown.cmd.err.resident.maxTowns"); getDatasource().deleteTownInvite(res, town, true); @@ -202,8 +202,8 @@ public static void friendsListCommand(ICommandSender sender, List args) Resident res = getDatasource().getOrMakeResident(sender); String friends = null; - for(Resident friend : res.getFriends()) { - if(friends == null) + for (Resident friend : res.getFriends()) { + if (friends == null) friends = friend.getPlayerName(); else friends += ", " + friend.getPlayerName(); @@ -218,13 +218,13 @@ public static void friendsListCommand(ICommandSender sender, List args) parentName = "mytown.cmd.outsider.friends", completionKeys = {"residentCompletion"}) public static void friendsAddCommand(ICommandSender sender, List args) { - if(args.size() < 1) + if (args.size() < 1) throw new MyTownWrongUsageException("mytown.cmd.usage.friends.add"); Resident res = getDatasource().getOrMakeResident(sender); Resident toAdd = getResidentFromName(args.get(0)); - if(res == toAdd) + if (res == toAdd) throw new MyTownCommandException("mytown.cmd.err.friends.add.self"); - if(!getDatasource().saveFriendRequest(res, toAdd)) { + if (!getDatasource().saveFriendRequest(res, toAdd)) { throw new MyTownCommandException("mytown.cmd.err.friends.add.already"); } res.sendMessage(getLocal().getLocalization("mytown.notification.friends.invitationSent")); @@ -237,11 +237,11 @@ public static void friendsAddCommand(ICommandSender sender, List args) { parentName = "mytown.cmd.outsider.friends", completionKeys = {"residentCompletion"}) public static void friendsRemoveCommand(ICommandSender sender, List args) { - if(args.size() < 1) + if (args.size() < 1) throw new MyTownWrongUsageException("mytown.cmd.usage.friends.remove"); Resident res = getDatasource().getOrMakeResident(sender); Resident toAdd = getResidentFromName(args.get(0)); - if(!toAdd.removeFriend(res)) { + if (!toAdd.removeFriend(res)) { throw new MyTownCommandException("mytown.cmd.err.friends.remove"); } else { res.removeFriend(toAdd); @@ -256,7 +256,7 @@ public static void friendsRemoveCommand(ICommandSender sender, List args parentName = "mytown.cmd.outsider.friends", completionKeys = {"residentCompletion"}) public static void friendsAcceptCommand(ICommandSender sender, List args) { - if(args.size() < 1) + if (args.size() < 1) throw new MyTownCommandException("mytown.cmd.err.friends.accept"); Resident res = getDatasource().getOrMakeResident(sender); Resident toAdd = getResidentFromName(args.get(0)); @@ -272,7 +272,7 @@ public static void friendsAcceptCommand(ICommandSender sender, List args parentName = "mytown.cmd.outsider.friends", completionKeys = {"residentCompletion"}) public static void friendsRefuseCommand(ICommandSender sender, List args) { - if(args.size() < 1) + if (args.size() < 1) throw new MyTownCommandException("mytown.cmd.err.friends.refuse"); Resident res = getDatasource().getOrMakeResident(sender); Resident toAdd = getResidentFromName(args.get(0)); @@ -292,17 +292,17 @@ public static void helpCommand(ICommandSender sender, List args) { } @CommandNode( - name="invites", + name = "invites", permission = "mytown.cmd.outsider.invites", parentName = "mytown.cmd") public static void invitesCommand(ICommandSender sender, List args) { Resident res = getDatasource().getOrMakeResident(sender); - if(res.getInvites().size() == 0) + if (res.getInvites().size() == 0) res.sendMessage(getLocal().getLocalization("mytown.notification.resident.noInvites")); else { String formattedList = null; - for(Town town : res.getInvites()) - if(formattedList == null) + for (Town town : res.getInvites()) + if (formattedList == null) formattedList = EnumChatFormatting.GREEN + town.getName() + EnumChatFormatting.WHITE; else formattedList += ", " + EnumChatFormatting.GREEN + town.getName() + EnumChatFormatting.WHITE; diff --git a/src/main/java/mytown/config/FlagsConfig.java b/src/main/java/mytown/config/FlagsConfig.java index 3cc8bb79..5efd9c0c 100644 --- a/src/main/java/mytown/config/FlagsConfig.java +++ b/src/main/java/mytown/config/FlagsConfig.java @@ -17,7 +17,8 @@ */ public class FlagsConfig { - private Type type = new TypeToken>() {} .getType(); + private Type type = new TypeToken>() { + }.getType(); private String path; private Gson gson; @@ -25,7 +26,7 @@ public FlagsConfig(File file) { path = file.getAbsolutePath(); gson = new GsonBuilder().setPrettyPrinting().create(); - if(!file.exists() || file.isDirectory()) + if (!file.exists() || file.isDirectory()) writeFile(); else readFile(); @@ -34,7 +35,7 @@ public FlagsConfig(File file) { private void writeFile() { List wrappers = new ArrayList(); - for(FlagType type : FlagType.values()) { + for (FlagType type : FlagType.values()) { wrappers.add(new Wrapper(type, type.getDefaultValue(), type.isUsableForTowns())); } try { @@ -59,20 +60,20 @@ private void readFile() { // Checking boolean ok; - for(Wrapper w : wrappers) { + for (Wrapper w : wrappers) { ok = false; - for(FlagType type : FlagType.values()) { - if(type == w.flagType) + for (FlagType type : FlagType.values()) { + if (type == w.flagType) ok = true; } - if(!ok) { + if (!ok) { MyTown.instance.log.error("Flag config is missing a flagType! Make sure you add them all. If you have trouble you can delete the file to get a new one."); return; } } - for(Wrapper w : wrappers) { - if(w.flagType.getType().isAssignableFrom(w.defaultState.getClass())) { + for (Wrapper w : wrappers) { + if (w.flagType.getType().isAssignableFrom(w.defaultState.getClass())) { w.flagType.setDefaultValue(w.defaultState); w.flagType.setIsUsableForTowns(w.isAllowedInTowns); //MyTown.instance.log.info("Added flag: " + w.flagType.toString() + " with default " + w.defaultState.toString() + " and allowed in towns: " + w.isAllowedInTowns ); diff --git a/src/main/java/mytown/config/RanksConfig.java b/src/main/java/mytown/config/RanksConfig.java index 67130cef..eed7ab97 100644 --- a/src/main/java/mytown/config/RanksConfig.java +++ b/src/main/java/mytown/config/RanksConfig.java @@ -24,7 +24,7 @@ public RanksConfig(File file) { gson = new GsonBuilder().setPrettyPrinting().create(); this.path = file.getPath(); - if(!file.exists() || file.isDirectory()) { + if (!file.exists() || file.isDirectory()) { writeFile(); } else { readFile(); diff --git a/src/main/java/mytown/config/WildPermsConfig.java b/src/main/java/mytown/config/WildPermsConfig.java index a3a5431b..2887e625 100644 --- a/src/main/java/mytown/config/WildPermsConfig.java +++ b/src/main/java/mytown/config/WildPermsConfig.java @@ -10,7 +10,6 @@ import java.io.*; import java.lang.reflect.Type; -import java.util.ArrayList; import java.util.List; /** @@ -19,7 +18,8 @@ */ public class WildPermsConfig { - private Type type = new TypeToken>() {}.getType(); + private Type type = new TypeToken>() { + }.getType(); private Gson gson; private String path; @@ -27,7 +27,7 @@ public WildPermsConfig(File file) { gson = new GsonBuilder().setPrettyPrinting().create(); this.path = file.getPath(); - if(!file.exists() || file.isDirectory()) { + if (!file.exists() || file.isDirectory()) { MyTown.instance.log.info("Creating WildPerms config file!"); writeFile(); } else { @@ -49,8 +49,8 @@ public void saveChanges() { @SuppressWarnings("unchecked") private void writeFile() { - for(FlagType type : FlagType.values()) { - if(type.isWildPerm()) + for (FlagType type : FlagType.values()) { + if (type.isWildPerm()) Wild.getInstance().addFlag(new Flag(type, type.getDefaultWildPerm())); } @@ -76,16 +76,16 @@ private void readFile() { e.printStackTrace(); MyTown.instance.log.error("An error occurred when trying to load wild perms."); } - if(list != null) { + if (list != null) { for (Flag f : list) { - if(f.flagType.isWildPerm()) + if (f.flagType.isWildPerm()) Wild.getInstance().addFlag(f); else { MyTown.instance.log.error("A non wild perm has been found in the wild perm list. Deleting and saving: " + f.flagType.toString()); } } - for(FlagType type : FlagType.values()) { - if(type.isWildPerm()) { + for (FlagType type : FlagType.values()) { + if (type.isWildPerm()) { boolean ok = false; for (Flag f : list) { if (f.flagType == type) diff --git a/src/main/java/mytown/datasource/MyTownDatasource.java b/src/main/java/mytown/datasource/MyTownDatasource.java index d1a0e453..e8c0fdc4 100644 --- a/src/main/java/mytown/datasource/MyTownDatasource.java +++ b/src/main/java/mytown/datasource/MyTownDatasource.java @@ -75,13 +75,13 @@ public final AdminTown newAdminTown(String name, Resident creator) { */ @SuppressWarnings("unchecked") private void configureTown(Town town, Resident creator) { - for(World world : MinecraftServer.getServer().worldServers) { - if(!MyTownUniverse.getInstance().hasWorld(world.provider.dimensionId)) { + for (World world : MinecraftServer.getServer().worldServers) { + if (!MyTownUniverse.getInstance().hasWorld(world.provider.dimensionId)) { saveWorld(world.provider.dimensionId); } } - for(int dim : MyTownUniverse.getInstance().getWorldsList()) { - if(DimensionManager.getWorld(dim) == null) { + for (int dim : MyTownUniverse.getInstance().getWorldsList()) { + if (DimensionManager.getWorld(dim) == null) { deleteWorld(dim); } } @@ -102,13 +102,13 @@ private void configureTown(Town town, Resident creator) { saveBlock(block); // Saving and adding all flags to the database - for(FlagType type : FlagType.values()) { - if(type.isUsableForTowns() && type.shouldLoad()) { + for (FlagType type : FlagType.values()) { + if (type.isUsableForTowns() && type.shouldLoad()) { saveFlag(new Flag(type, type.getDefaultValue()), town); } } - if(!(town instanceof AdminTown)) { + if (!(town instanceof AdminTown)) { // Saving all ranks to database and town for (String rankName : Rank.defaultRanks.keySet()) { Rank rank = new Rank(rankName, Rank.defaultRanks.get(rankName), town); diff --git a/src/main/java/mytown/datasource/MyTownDatasource_SQL.java b/src/main/java/mytown/datasource/MyTownDatasource_SQL.java index b4ab7aac..7643baf8 100644 --- a/src/main/java/mytown/datasource/MyTownDatasource_SQL.java +++ b/src/main/java/mytown/datasource/MyTownDatasource_SQL.java @@ -15,7 +15,9 @@ import net.minecraftforge.common.DimensionManager; import java.sql.*; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; // TODO Check connection for each command and error out if connection doesn't check out // TODO Run DB writes (and maybe reads?) on a separate thread @@ -129,7 +131,7 @@ protected boolean loadWorlds() { PreparedStatement s = prepare("SELECT * FROM " + prefix + "Worlds", true); ResultSet rs = s.executeQuery(); - while(rs.next()) { + while (rs.next()) { MyTownUniverse.getInstance().addWorld(rs.getInt("dim")); } @@ -138,13 +140,13 @@ protected boolean loadWorlds() { return false; } - for(World world : MinecraftServer.getServer().worldServers) { - if(!MyTownUniverse.getInstance().hasWorld(world.provider.dimensionId)) { + for (World world : MinecraftServer.getServer().worldServers) { + if (!MyTownUniverse.getInstance().hasWorld(world.provider.dimensionId)) { saveWorld(world.provider.dimensionId); } } - for(int dim : MyTownUniverse.getInstance().getWorldsList()) { - if(DimensionManager.getWorld(dim) == null) { + for (int dim : MyTownUniverse.getInstance().getWorldsList()) { + if (DimensionManager.getWorld(dim) == null) { deleteWorld(dim); } } @@ -326,8 +328,8 @@ protected boolean loadTownFlags() { Flag flag = new Flag(FlagType.valueOf(flagName), gson.fromJson(rs.getString("serializedValue"), FlagType.valueOf(flagName).getType())); Town town = MyTownUniverse.getInstance().getTownsMap().get(townName); - if(town != null) { - if(flag.flagType.shouldLoad()) + if (town != null) { + if (flag.flagType.shouldLoad()) town.addFlag(flag); } else { log.error("Failed to load flag " + flagName + " because the town given was invalid!"); @@ -356,8 +358,8 @@ public boolean loadPlotFlags() { Flag flag = new Flag(FlagType.valueOf(flagName), gson.fromJson(rs.getString("serializedValue"), FlagType.valueOf(flagName).getType())); Plot plot = MyTownUniverse.getInstance().getPlot(plotID); - if(plot != null) { - if(flag.flagType.shouldLoad()) + if (plot != null) { + if (flag.flagType.shouldLoad()) plot.addFlag(flag); } else { log.error("Failed to load flag " + flagName + " because the town given was invalid!"); @@ -500,7 +502,7 @@ protected boolean loadFriends() { try { PreparedStatement s = prepare("SELECT * FROM " + prefix + "Friends", true); ResultSet rs = s.executeQuery(); - while(rs.next()) { + while (rs.next()) { Resident res1 = MyTownUniverse.getInstance().getResidentsMap().get(rs.getString("resident1")); Resident res2 = MyTownUniverse.getInstance().getResidentsMap().get(rs.getString("resident2")); @@ -519,7 +521,7 @@ protected boolean loadFriendRequests() { try { PreparedStatement s = prepare("SELECT * FROM " + prefix + "FriendRequests", true); ResultSet rs = s.executeQuery(); - while(rs.next()) { + while (rs.next()) { Resident res1 = MyTownUniverse.getInstance().getResidentsMap().get(rs.getString("resident")); Resident res2 = MyTownUniverse.getInstance().getResidentsMap().get(rs.getString("residentTarget")); @@ -537,7 +539,7 @@ protected boolean loadTownInvites() { try { PreparedStatement s = prepare("SELECT * FROM " + prefix + "TownInvites", true); ResultSet rs = s.executeQuery(); - while(rs.next()) { + while (rs.next()) { Resident res = MyTownUniverse.getInstance().getResident(rs.getString("resident")); Town town = MyTownUniverse.getInstance().getTown(rs.getString("townName")); res.addInvite(town); @@ -576,7 +578,7 @@ public boolean saveTown(Town town) { updateStatement.executeUpdate(); // Need to move the Town in the map from the old name to the new - if(town.getOldName() != null) { + if (town.getOldName() != null) { MyTownUniverse.getInstance().removeTown(town); // This updates the name MyTownUniverse.getInstance().addTown(town); @@ -709,7 +711,7 @@ public boolean saveResident(Resident resident) { if (MyTownUniverse.getInstance().hasResident(resident)) { // Update PreparedStatement updateStatement = prepare("UPDATE " + prefix + "Residents SET name=?, lastOnline=?, extraBlocks=? WHERE uuid=?", true); updateStatement.setString(1, resident.getPlayerName()); - updateStatement.setLong(2, resident.getLastOnline().getTime()/1000L); // Stupid hack... + updateStatement.setLong(2, resident.getLastOnline().getTime() / 1000L); // Stupid hack... updateStatement.setInt(3, resident.getExtraBlocks()); updateStatement.setString(4, resident.getUUID().toString()); updateStatement.executeUpdate(); @@ -717,8 +719,8 @@ public boolean saveResident(Resident resident) { PreparedStatement insertStatement = prepare("INSERT INTO " + prefix + "Residents (uuid, name, joined, lastOnline, extraBlocks) VALUES(?, ?, ?, ?, ?)", true); insertStatement.setString(1, resident.getUUID().toString()); insertStatement.setString(2, resident.getPlayerName()); - insertStatement.setLong(3, resident.getJoinDate().getTime()/1000L); // Stupid hack... - insertStatement.setLong(4, resident.getLastOnline().getTime()/1000L); // Stupid hack... + insertStatement.setLong(3, resident.getJoinDate().getTime() / 1000L); // Stupid hack... + insertStatement.setLong(4, resident.getLastOnline().getTime() / 1000L); // Stupid hack... insertStatement.setInt(5, resident.getExtraBlocks()); insertStatement.executeUpdate(); @@ -767,8 +769,8 @@ public boolean savePlot(Plot plot) { if (generatedKeys.next()) plot.setDb_ID(generatedKeys.getInt(1)); log.info("Saved plot with ID " + generatedKeys.getInt(1)); - for(Flag flag : plot.getTown().getFlags()) { - if(!flag.flagType.isTownOnly()) + for (Flag flag : plot.getTown().getFlags()) { + if (!flag.flagType.isTownOnly()) saveFlag(new Flag(flag.flagType, flag.getValue()), plot); } @@ -809,10 +811,10 @@ public boolean saveNation(Nation nation) { // TODO Link any new Towns to the giv @Override public boolean saveFlag(Flag flag, Plot plot) { - if(!flag.flagType.shouldLoad()) return false; + if (!flag.flagType.shouldLoad()) return false; log.debug("Saving Flag %s for Plot %s", flag.flagType.name(), plot.getKey()); try { - if(plot.hasFlag(flag.flagType)) { + if (plot.hasFlag(flag.flagType)) { // Update PreparedStatement updateStatement = prepare("UPDATE " + prefix + "PlotFlags SET serializedValue=? WHERE plotID=? AND name=?", true); updateStatement.setString(1, flag.serializeValue()); @@ -841,10 +843,10 @@ public boolean saveFlag(Flag flag, Plot plot) { @Override public boolean saveFlag(Flag flag, Town town) { - if(!flag.flagType.shouldLoad()) return false; + if (!flag.flagType.shouldLoad()) return false; log.debug("Saving Flag %s for Town %s", flag.flagType.name(), town.getName()); try { - if(town.hasFlag(flag.flagType)) { + if (town.hasFlag(flag.flagType)) { // Update PreparedStatement updateStatement = prepare("UPDATE " + prefix + "TownFlags SET serializedValue=? WHERE townName=? AND name=?", true); updateStatement.setString(1, flag.serializeValue()); @@ -875,7 +877,7 @@ public boolean saveFlag(Flag flag, Town town) { @Override public boolean saveBlockWhitelist(BlockWhitelist bw, Town town) { try { - if(!town.hasBlockWhitelist(bw)) { + if (!town.hasBlockWhitelist(bw)) { PreparedStatement insertStatement = prepare("INSERT INTO " + prefix + "BlockWhitelists(dim, x, y, z, flagName, townName) VALUES(?, ?, ?, ?, ?, ?)", true); insertStatement.setInt(1, bw.dim); insertStatement.setInt(2, bw.x); @@ -949,7 +951,7 @@ public boolean saveFriendLink(Resident res1, Resident res2) { @Override public boolean saveFriendRequest(Resident res1, Resident res2) { try { - if(res2.addFriendRequest(res1)) { + if (res2.addFriendRequest(res1)) { PreparedStatement s = prepare("INSERT INTO " + prefix + "FriendRequests(resident, residentTarget) VALUES(?, ?)", true); s.setString(1, res1.getUUID().toString()); s.setString(2, res2.getUUID().toString()); @@ -967,7 +969,7 @@ public boolean saveFriendRequest(Resident res1, Resident res2) { @Override public boolean saveTownInvite(Resident res, Town town) { try { - if(!res.hasInvite(town)) { + if (!res.hasInvite(town)) { PreparedStatement s = prepare("INSERT INTO " + prefix + "TownInvites(resident, townName) VALUES(?, ?)", true); s.setString(1, res.getUUID().toString()); s.setString(2, town.getName()); @@ -979,7 +981,7 @@ public boolean saveTownInvite(Resident res, Town town) { return false; } } catch (SQLException e) { - log.error("Failed to load town invite: " + res.getPlayerName() + " for town " + town.getName()); + log.error("Failed to load town invite: " + res.getPlayerName() + " for town " + town.getName()); return false; } @@ -1306,7 +1308,7 @@ public boolean deleteBlockWhitelist(BlockWhitelist bw, Town town) { @Override public boolean deleteSelectedTown(Resident res) { try { - if(res.getTowns().size() > 0) { + if (res.getTowns().size() > 0) { PreparedStatement s = prepare("UPDATE FROM " + prefix + "SelectedTown SET townName=? WHERE resdent=?", true); s.setString(1, res.getTowns().get(0).getName()); s.setString(2, res.getUUID().toString()); @@ -1344,13 +1346,13 @@ public boolean deleteFriendLink(Resident res1, Resident res2) { @Override public boolean deleteFriendRequest(Resident res1, Resident res2, boolean response) { try { - if(res2.hasFriendRequest(res1)) { + if (res2.hasFriendRequest(res1)) { PreparedStatement s = prepare("DELETE FROM " + prefix + "FriendRequests WHERE resident=? AND residentTarget=?", true); s.setString(1, res1.getUUID().toString()); s.setString(2, res2.getUUID().toString()); s.executeUpdate(); - if(response) + if (response) saveFriendLink(res1, res2); res2.verifyFriendRequest(res1, response); } else { @@ -1370,7 +1372,7 @@ public boolean deleteTownInvite(Resident res, Town town, boolean response) { s.setString(1, res.getUUID().toString()); s.setString(2, town.getName()); s.executeUpdate(); - if(response) + if (response) linkResidentToTown(res, town, town.getDefaultRank()); res.removeInvite(town); } catch (SQLException e) { @@ -1450,21 +1452,21 @@ protected boolean checkFlags() { // Checking if flag is supposed to exist and it doesn't or otherwise. - for(Town town : MyTownUniverse.getInstance().getTownsMap().values()) { - for(FlagType type : FlagType.values()) { - if(!type.isUsableForTowns() && town.hasFlag(type)) { + for (Town town : MyTownUniverse.getInstance().getTownsMap().values()) { + for (FlagType type : FlagType.values()) { + if (!type.isUsableForTowns() && town.hasFlag(type)) { deleteFlag(town.getFlag(type), town); MyTown.instance.log.info("A flag in town " + town.getName() + " got deleted because of the settings."); - } else if(type.isUsableForTowns() && !town.hasFlag(type)) { + } else if (type.isUsableForTowns() && !town.hasFlag(type)) { saveFlag(new Flag(type, type.getDefaultValue()), town); MyTown.instance.log.info("A flag in town " + town.getName() + " got created because of the settings."); } } } - for(Plot plot : MyTownUniverse.getInstance().getPlotsMap().values()) { - for(FlagType type : FlagType.values()) { - if(!type.isTownOnly()) { + for (Plot plot : MyTownUniverse.getInstance().getPlotsMap().values()) { + for (FlagType type : FlagType.values()) { + if (!type.isTownOnly()) { if (!type.isUsableForTowns() && plot.hasFlag(type)) { deleteFlag(plot.getFlag(type), plot); MyTown.instance.log.info("A flag in a plot in town " + plot.getTown().getName() + " got deleted because of the settings."); @@ -1683,7 +1685,7 @@ protected void setupUpdates() { // TODO Move these into a XML/JSON file? "Towns ADD extraBlocks INTEGER DEFAULT 0")); updates.add(new DBUpdate("10.23.2014.1", "Add 'maxPlots' to towns", "ALTER TABLE " + prefix + - "Towns ADD maxPlots INTEGER DEFAULT "+ Config.defaultMaxPlots+"")); + "Towns ADD maxPlots INTEGER DEFAULT " + Config.defaultMaxPlots + "")); updates.add(new DBUpdate("11.4.2014.1", "Add 'extraBlocks to residents", "ALTER TABLE " + prefix + "Residents ADD extraBlocks INTEGER DEFAULT 0;")); diff --git a/src/main/java/mytown/datasource/MyTownUniverse.java b/src/main/java/mytown/datasource/MyTownUniverse.java index bed0244c..088a429c 100644 --- a/src/main/java/mytown/datasource/MyTownUniverse.java +++ b/src/main/java/mytown/datasource/MyTownUniverse.java @@ -96,12 +96,15 @@ public final ImmutableMap getRanksMap() { * * @return */ - public final ImmutableList getWorldsList() { return ImmutableList.copyOf(worlds); } + public final ImmutableList getWorldsList() { + return ImmutableList.copyOf(worlds); + } /* ----- Add Entity ----- */ /** * Adds a Resident to the universe + * * @param res Resident to add * @return If successful */ @@ -113,6 +116,7 @@ public final boolean addResident(Resident res) { /** * Adds a Town to the universe + * * @param town Town to add * @return If successful */ @@ -125,6 +129,7 @@ public final boolean addTown(Town town) { /** * Adds a Nation to the universe + * * @param nation Nation to add * @return If successful */ @@ -135,6 +140,7 @@ public final boolean addNation(Nation nation) { /** * Adds a TownBlock to the universe + * * @param block TownBlock to add * @return If successful */ @@ -145,6 +151,7 @@ public final boolean addTownBlock(TownBlock block) { /** * Adds a Rank to the universe + * * @param rank Rank to add * @return If successful */ @@ -156,6 +163,7 @@ public final boolean addRank(Rank rank) { /** * Adds a Plot to the universe + * * @param plot Plot to add * @return If successful */ @@ -175,6 +183,7 @@ public final boolean addPlot(Plot plot) { /** * Adds a world/dim to the universe + * * @param dim Dimension ID of world to add * @return If successful */ @@ -230,7 +239,7 @@ public final boolean removePlot(Plot plot) { } public final boolean removeWorld(int dim) { - worlds.remove((Integer)dim); + worlds.remove((Integer) dim); return true; } @@ -295,7 +304,9 @@ public boolean hasPlot(Plot plot) { return plots.containsValue(plot); } - public boolean hasWorld(int dim) { return worlds.contains(dim); } + public boolean hasWorld(int dim) { + return worlds.contains(dim); + } /* ----- Singleton ----- */ diff --git a/src/main/java/mytown/entities/BlockWhitelist.java b/src/main/java/mytown/entities/BlockWhitelist.java index 55c8cb1b..b107eea2 100644 --- a/src/main/java/mytown/entities/BlockWhitelist.java +++ b/src/main/java/mytown/entities/BlockWhitelist.java @@ -1,6 +1,5 @@ package mytown.entities; -import mytown.datasource.MyTownUniverse; import mytown.entities.flag.FlagType; /** @@ -19,7 +18,6 @@ public class BlockWhitelist { private FlagType flagType; - public BlockWhitelist(int dim, int x, int y, int z, FlagType flagType) { this.dim = dim; this.x = x; @@ -32,7 +30,9 @@ public FlagType getFlagType() { return this.flagType; } - public void delete() { this.isDeleted = true; } + public void delete() { + this.isDeleted = true; + } public void setDb_ID(int id) { this.db_id = id; diff --git a/src/main/java/mytown/entities/Plot.java b/src/main/java/mytown/entities/Plot.java index 1883a961..df64a0e5 100644 --- a/src/main/java/mytown/entities/Plot.java +++ b/src/main/java/mytown/entities/Plot.java @@ -163,8 +163,8 @@ public void addFlag(Flag flag) { @Override public boolean hasFlag(FlagType type) { - for(Flag flag : flags) - if(flag.flagType.equals(type)) + for (Flag flag : flags) + if (flag.flagType.equals(type)) return true; return false; } @@ -176,16 +176,16 @@ public ImmutableList getFlags() { @Override public Flag getFlag(FlagType type) { - for(Flag flag : flags) - if(flag.flagType.equals(type)) + for (Flag flag : flags) + if (flag.flagType.equals(type)) return flag; return null; } @Override public boolean removeFlag(FlagType type) { - for(Iterator it = flags.iterator(); it.hasNext(); ) { - if(it.next().flagType == type) { + for (Iterator it = flags.iterator(); it.hasNext(); ) { + if (it.next().flagType == type) { it.remove(); return true; } @@ -195,8 +195,8 @@ public boolean removeFlag(FlagType type) { @Override public Object getValue(FlagType type) { - for(Flag flag : flags) { - if(flag.flagType == type) + for (Flag flag : flags) { + if (flag.flagType == type) return flag.getValue(); } return type.getDefaultValue(); @@ -204,7 +204,7 @@ public Object getValue(FlagType type) { @Override public Object getValueAtCoords(int dim, int x, int y, int z, FlagType flagType) { - if(!isCoordWithin(dim, x, y, z)) return null; + if (!isCoordWithin(dim, x, y, z)) return null; return getValue(flagType); } @@ -251,8 +251,8 @@ public ImmutableList getOwners() { } public boolean residentHasFriendInPlot(Resident res) { - for(Resident r : owners) - if(r.hasFriend(res)) + for (Resident r : owners) + if (r.hasFriend(res)) return true; return false; } diff --git a/src/main/java/mytown/entities/Resident.java b/src/main/java/mytown/entities/Resident.java index f73ce81d..03672e1c 100644 --- a/src/main/java/mytown/entities/Resident.java +++ b/src/main/java/mytown/entities/Resident.java @@ -2,16 +2,15 @@ import com.google.common.collect.ImmutableList; import mytown.MyTown; +import mytown.api.interfaces.IBlockWhitelister; +import mytown.api.interfaces.IHasPlots; +import mytown.api.interfaces.IHasTowns; +import mytown.api.interfaces.IPlotSelector; import mytown.config.Config; import mytown.core.ChatUtils; -import mytown.core.Localization; import mytown.datasource.MyTownDatasource; import mytown.datasource.MyTownUniverse; import mytown.entities.flag.FlagType; -import mytown.api.interfaces.IBlockWhitelister; -import mytown.api.interfaces.IHasPlots; -import mytown.api.interfaces.IHasTowns; -import mytown.api.interfaces.IPlotSelector; import mytown.handlers.VisualsTickHandler; import mytown.proxies.DatasourceProxy; import mytown.proxies.LocalizationProxy; @@ -25,9 +24,10 @@ import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.EnumChatFormatting; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; /** * @author Joe Goett @@ -72,8 +72,8 @@ public Resident(String uuid, String playerName) { */ public Resident(String uuid, String playerName, long joinDate, long lastOnline, int extraBlocks) { setUUID(uuid); - this.joinDate = new Date((long)joinDate * 1000L); - this.lastOnline = new Date((long)lastOnline * 1000L); + this.joinDate = new Date((long) joinDate * 1000L); + this.lastOnline = new Date((long) lastOnline * 1000L); this.playerName = playerName; this.extraBlocks = extraBlocks; } @@ -399,6 +399,7 @@ public boolean hasInvite(Town town) { private List friends = new ArrayList(); private List friendRequests = new ArrayList(); + public boolean addFriend(Resident res) { return friends.add(res); } @@ -416,12 +417,12 @@ public List getFriends() { } public boolean addFriendRequest(Resident res) { - if(friends.contains(res) || friendRequests.contains(res)) return false; + if (friends.contains(res) || friendRequests.contains(res)) return false; return friendRequests.add(res); } public void verifyFriendRequest(Resident res, boolean response) { - if(response) { + if (response) { friends.add(res); res.addFriend(this); } @@ -440,7 +441,7 @@ public void sendMessage(String msg) { } public void protectionDenial(String message, String owner) { - if(getPlayer() != null) { + if (getPlayer() != null) { ChatUtils.sendChat(getPlayer(), message); ChatUtils.sendChat(getPlayer(), owner); } diff --git a/src/main/java/mytown/entities/Town.java b/src/main/java/mytown/entities/Town.java index 8f3c73bf..4449a5ee 100644 --- a/src/main/java/mytown/entities/Town.java +++ b/src/main/java/mytown/entities/Town.java @@ -2,18 +2,17 @@ import com.google.common.collect.ImmutableList; import mytown.MyTown; +import mytown.api.interfaces.*; import mytown.config.Config; import mytown.core.utils.teleport.Teleport; import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; -import mytown.api.interfaces.*; import mytown.proxies.LocalizationProxy; import mytown.proxies.plugin.BukkitCompat; import mytown.proxies.plugin.PEXCompat; import mytown.util.Utils; import net.minecraft.entity.player.EntityPlayer; - import java.util.*; // TODO Implement TownType @@ -76,6 +75,7 @@ public String toString() { /** * Returns the name that is currently used in the DB + * * @return */ public String getDBName() { @@ -296,8 +296,8 @@ public int getMaxPlots() { */ public List getPlotsOwned(Resident res) { List list = new ArrayList(); - for(Plot plot : plots) { - if(plot.hasOwner(res)) + for (Plot plot : plots) { + if (plot.hasOwner(res)) list.add(plot); } return list; @@ -311,8 +311,8 @@ public List getPlotsOwned(Resident res) { */ public int getAmountPlotsOwned(Resident res) { int x = 0; - for(Plot plot : plots) { - if(plot.hasOwner(res)) + for (Plot plot : plots) { + if (plot.hasOwner(res)) x++; } return x; @@ -375,8 +375,8 @@ public void addFlag(Flag flag) { @Override public boolean hasFlag(FlagType type) { - for(Flag flag : flags) - if(flag.flagType == type) + for (Flag flag : flags) + if (flag.flagType == type) return true; return false; } @@ -388,16 +388,16 @@ public ImmutableList getFlags() { @Override public Flag getFlag(FlagType type) { - for(Flag flag : flags) - if(flag.flagType == type) + for (Flag flag : flags) + if (flag.flagType == type) return flag; return null; } @Override public boolean removeFlag(FlagType type) { - for(Iterator it = flags.iterator(); it.hasNext();) { - if(it.next().flagType == type) { + for (Iterator it = flags.iterator(); it.hasNext(); ) { + if (it.next().flagType == type) { it.remove(); return true; } @@ -407,8 +407,8 @@ public boolean removeFlag(FlagType type) { @Override public Object getValue(FlagType type) { - for(Flag flag : flags) { - if(flag.flagType == type) + for (Flag flag : flags) { + if (flag.flagType == type) return flag.getValue(); } return type.getDefaultValue(); @@ -434,8 +434,8 @@ public void addBlockWhitelist(BlockWhitelist bw) { @Override public boolean hasBlockWhitelist(int dim, int x, int y, int z, FlagType flagType) { - for(BlockWhitelist bw : blockWhitelists) { - if(bw.dim == dim && bw.x == x && bw.y == y && bw.z == z && bw.getFlagType().equals(flagType)) { + for (BlockWhitelist bw : blockWhitelists) { + if (bw.dim == dim && bw.x == x && bw.y == y && bw.z == z && bw.getFlagType().equals(flagType)) { return true; } } @@ -454,9 +454,9 @@ public void removeBlockWhitelist(BlockWhitelist bw) { @Override public void removeBlockWhitelist(int dim, int x, int y, int z, FlagType flagType) { - for(Iterator it = blockWhitelists.iterator(); it.hasNext();) { + for (Iterator it = blockWhitelists.iterator(); it.hasNext(); ) { BlockWhitelist bw = it.next(); - if(bw.dim == dim && bw.x == x && bw.y == y && bw.z == z && bw.getFlagType().equals(flagType)) { + if (bw.dim == dim && bw.x == x && bw.y == y && bw.z == z && bw.getFlagType().equals(flagType)) { it.remove(); } } @@ -464,8 +464,8 @@ public void removeBlockWhitelist(int dim, int x, int y, int z, FlagType flagType @Override public BlockWhitelist getBlockWhitelist(int dim, int x, int y, int z, FlagType flagType) { - for(BlockWhitelist bw : blockWhitelists) { - if(bw.dim == dim && bw.x == x && bw.y == y && bw.z == z && bw.getFlagType().equals(flagType)) { + for (BlockWhitelist bw : blockWhitelists) { + if (bw.dim == dim && bw.x == x && bw.y == y && bw.z == z && bw.getFlagType().equals(flagType)) { return bw; } } @@ -578,16 +578,16 @@ public void notifyResidentJoin(Resident res) { public void notifyEveryone(String message) { // TODO: Check permission for if it should receive message - for(Resident r : residents.keySet()) { + for (Resident r : residents.keySet()) { r.sendMessage(message); } } public boolean residentHasFriendInTown(Resident res) { - if(res.hasTown(this)) + if (res.hasTown(this)) return true; - for(Resident r : residents.keySet()) { - if(r.hasFriend(res)) + for (Resident r : residents.keySet()) { + if (r.hasFriend(res)) return true; } return false; @@ -595,13 +595,13 @@ public boolean residentHasFriendInTown(Resident res) { @SuppressWarnings("unchecked") public boolean checkPermission(Resident res, FlagType flagType, int dim, int x, int y, int z) { - if(flagType.getType() != Boolean.class) + if (flagType.getType() != Boolean.class) throw new RuntimeException("FlagType is not boolean!"); Plot plot = getPlotAtCoords(dim, x, y, z); - if(plot == null) { - if(!(Boolean)getValue(flagType) && !hasResident(res) && !residentHasFriendInTown(res)) { - if(MyTown.instance.isCauldron && BukkitCompat.getInstance().hasPEX()) + if (plot == null) { + if (!(Boolean) getValue(flagType) && !hasResident(res) && !residentHasFriendInTown(res)) { + if (MyTown.instance.isCauldron && BukkitCompat.getInstance().hasPEX()) // Check if PEX has a permission bypass return PEXCompat.getInstance().checkPermission(res, flagType.getBypassPermission()) || Utils.isOp(res); else @@ -609,7 +609,7 @@ public boolean checkPermission(Resident res, FlagType flagType, int dim, int x, return Utils.isOp(res); } } else { - if(!(Boolean)plot.getValue(flagType) && !plot.hasResident(res) && !plot.residentHasFriendInPlot(res)) + if (!(Boolean) plot.getValue(flagType) && !plot.hasResident(res) && !plot.residentHasFriendInPlot(res)) return false; } return true; @@ -617,13 +617,13 @@ public boolean checkPermission(Resident res, FlagType flagType, int dim, int x, @SuppressWarnings("unchecked") public boolean checkPermission(Resident res, FlagType flagType) { - if(flagType.getType() != Boolean.class) + if (flagType.getType() != Boolean.class) throw new RuntimeException("FlagType is not boolean!"); - if(!(Boolean)getValue(flagType) && !hasResident(res) && !residentHasFriendInTown(res)) { - //TODO: Check for permission - return false; - } + if (!(Boolean) getValue(flagType) && !hasResident(res) && !residentHasFriendInTown(res)) { + //TODO: Check for permission + return false; + } return true; } @@ -636,14 +636,14 @@ public boolean checkPermission(Resident res, FlagType flagType) { public List getOwnersAtPosition(int dim, int x, int y, int z) { List list = new ArrayList(); Plot plot = getPlotAtCoords(dim, x, y, z); - if(plot == null) { - if(isPointInTown(dim, x, z)) { + if (plot == null) { + if (isPointInTown(dim, x, z)) { list.add(getMayor()); } else { return null; } } else { - for(Resident res : plot.getOwners()) { + for (Resident res : plot.getOwners()) { list.add(res); } } @@ -656,8 +656,8 @@ public List getOwnersAtPosition(int dim, int x, int y, int z) { * @return */ public Resident getMayor() { - for(Resident res : residents.keySet()) { - if(residents.get(res).getName().equals(Rank.theMayorDefaultRank)) + for (Resident res : residents.keySet()) { + if (residents.get(res).getName().equals(Rank.theMayorDefaultRank)) return res; } return null; diff --git a/src/main/java/mytown/entities/Wild.java b/src/main/java/mytown/entities/Wild.java index 81cf2296..af944ab9 100644 --- a/src/main/java/mytown/entities/Wild.java +++ b/src/main/java/mytown/entities/Wild.java @@ -2,9 +2,9 @@ import com.google.common.collect.ImmutableList; import mytown.MyTown; +import mytown.api.interfaces.IHasFlags; import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; -import mytown.api.interfaces.IHasFlags; import mytown.proxies.plugin.BukkitCompat; import mytown.proxies.plugin.PEXCompat; import mytown.util.Utils; @@ -21,7 +21,7 @@ public class Wild implements IHasFlags { private static Wild instance; public static Wild getInstance() { - if(instance == null) { + if (instance == null) { instance = new Wild(); } return instance; @@ -37,8 +37,8 @@ public void addFlag(Flag flag) { @Override public boolean hasFlag(FlagType type) { - for(Flag f : flagList) { - if(f.flagType == type) + for (Flag f : flagList) { + if (f.flagType == type) return true; } return false; @@ -51,8 +51,8 @@ public ImmutableList getFlags() { @Override public Flag getFlag(FlagType type) { - for(Flag f : flagList) { - if(f.flagType == type) + for (Flag f : flagList) { + if (f.flagType == type) return f; } return null; @@ -60,8 +60,8 @@ public Flag getFlag(FlagType type) { @Override public boolean removeFlag(FlagType type) { - for(Iterator it = flagList.iterator(); it.hasNext();) { - if(it.next().flagType == type) { + for (Iterator it = flagList.iterator(); it.hasNext(); ) { + if (it.next().flagType == type) { it.remove(); return true; } @@ -70,9 +70,9 @@ public boolean removeFlag(FlagType type) { } public boolean checkPermission(Resident res, FlagType type) { - if(getFlag(type).getValue() instanceof Boolean) { - if(!(Boolean)getFlag(type).getValue()) { - if(MyTown.instance.isCauldron && BukkitCompat.getInstance().hasPEX()) + if (getFlag(type).getValue() instanceof Boolean) { + if (!(Boolean) getFlag(type).getValue()) { + if (MyTown.instance.isCauldron && BukkitCompat.getInstance().hasPEX()) return PEXCompat.getInstance().checkPermission(res, type.getBypassPermission()) || Utils.isOp(res); else return Utils.isOp(res); @@ -81,10 +81,11 @@ public boolean checkPermission(Resident res, FlagType type) { // TODO: Implement other types of flags return true; } + @Override public Object getValue(FlagType type) { - for(Flag flag : flagList) { - if(flag.flagType == type) + for (Flag flag : flagList) { + if (flag.flagType == type) return flag.getValue(); } return null; diff --git a/src/main/java/mytown/entities/flag/Flag.java b/src/main/java/mytown/entities/flag/Flag.java index e0391765..b33825be 100644 --- a/src/main/java/mytown/entities/flag/Flag.java +++ b/src/main/java/mytown/entities/flag/Flag.java @@ -3,14 +3,9 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; -import mytown.proxies.LocalizationProxy; import net.minecraft.util.EnumChatFormatting; import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; /** * Created by AfterWind on 8/26/2014. @@ -80,7 +75,7 @@ public boolean setValueFromString(String str) { T val = getValueFromString(str); if (val == null) return false; - if(flagType.isValueAllowed(val)) { + if (flagType.isValueAllowed(val)) { value = val; return true; } diff --git a/src/main/java/mytown/entities/flag/FlagType.java b/src/main/java/mytown/entities/flag/FlagType.java index 115a2581..d1ab6427 100644 --- a/src/main/java/mytown/entities/flag/FlagType.java +++ b/src/main/java/mytown/entities/flag/FlagType.java @@ -1,10 +1,7 @@ package mytown.entities.flag; -import cpw.mods.fml.common.registry.GameRegistry; import mytown.proxies.LocalizationProxy; -import mytown.proxies.mod.*; -import net.minecraft.block.Block; -import net.minecraft.tileentity.TileEntity; +import mytown.proxies.mod.ModProxies; /** * Created by AfterWind on 9/16/2014. @@ -19,7 +16,7 @@ public enum FlagType { pickupItems(Boolean.class, true, null, false, true, false, null), explosions(Boolean.class, false, null, true, false, false, null), // Only the values in the array are allowed - mobs(String.class, "all", new String[] {"all", "hostiles", "none"}, false, "all", false, null), + mobs(String.class, "all", new String[]{"all", "hostiles", "none"}, false, "all", false, null), attackEntities(Boolean.class, false, null, false, true, false, null), useItems(Boolean.class, false, null, false, true, false, null), activateBlocks(Boolean.class, false, null, true, true, false, null, true), @@ -62,6 +59,7 @@ private FlagType(Class type, Object defaultValue, Object[] allowedValues, boo /** * Type that is used by the flag + * * @return */ public Class getType() { @@ -73,28 +71,36 @@ public Class getType() { * * @return */ - public boolean isWildPerm() { return this.isWildPerm; } + public boolean isWildPerm() { + return this.isWildPerm; + } /** * Returns the permission needed to bypass the protection. * * @return */ - public String getBypassPermission() { return this.bypassPerm; } + public String getBypassPermission() { + return this.bypassPerm; + } /** * Gets the default wild perm. * * @return */ - public Object getDefaultWildPerm() { return this.defaultWildPerm; } + public Object getDefaultWildPerm() { + return this.defaultWildPerm; + } /** * Gets the default value * * @return */ - public Object getDefaultValue() { return this.defaultValue; } + public Object getDefaultValue() { + return this.defaultValue; + } /** * Sets the default value and returns if the value was set @@ -103,7 +109,7 @@ public Class getType() { * @return */ public boolean setDefaultValue(Object obj) { - if(type.isAssignableFrom(obj.getClass())) { + if (type.isAssignableFrom(obj.getClass())) { defaultValue = obj; return true; } @@ -112,20 +118,26 @@ public boolean setDefaultValue(Object obj) { /** - * Returns if this type of flag should be in a town - * @return + * Returns if this type of flag should be in a town + * + * @return */ - public boolean isUsableForTowns() { return this.isUsableForTowns; } + public boolean isUsableForTowns() { + return this.isUsableForTowns; + } /** * Sets whether or not the flagtype is changable/usable in a town * * @param bool */ - public void setIsUsableForTowns(boolean bool) { this.isUsableForTowns = bool; } + public void setIsUsableForTowns(boolean bool) { + this.isUsableForTowns = bool; + } /** * If flag is town only then it's not gonna be found on plots + * * @return */ public boolean isTownOnly() { @@ -134,6 +146,7 @@ public boolean isTownOnly() { /** * Checks to see if this type of flag has the mod needed to load + * * @return */ public boolean shouldLoad() { @@ -142,6 +155,7 @@ public boolean shouldLoad() { /** * Gets the localized description + * * @return */ public String getLocalizedDescription() { @@ -150,6 +164,7 @@ public String getLocalizedDescription() { /** * Gets the localized message of when the flag denies an action of a player + * * @return */ public String getLocalizedProtectionDenial() { @@ -167,6 +182,7 @@ public String getLocalizedTownNotification() { /** * If it's a flag that allows whitelists + * * @return */ public boolean isWhitelistable() { @@ -175,14 +191,15 @@ public boolean isWhitelistable() { /** * Checks to see if the value is allowed + * * @param value * @return */ public boolean isValueAllowed(Object value) { - if(allowedValues == null) return true; + if (allowedValues == null) return true; else { - for(Object s : allowedValues) { - if(s.equals(value)) + for (Object s : allowedValues) { + if (s.equals(value)) return true; } } diff --git a/src/main/java/mytown/handlers/PlayerTracker.java b/src/main/java/mytown/handlers/PlayerTracker.java index c4a2d6dd..b21f4e2a 100644 --- a/src/main/java/mytown/handlers/PlayerTracker.java +++ b/src/main/java/mytown/handlers/PlayerTracker.java @@ -9,11 +9,10 @@ import mytown.core.utils.Log; import mytown.datasource.MyTownDatasource; import mytown.datasource.MyTownUniverse; -import mytown.entities.*; -import mytown.entities.flag.Flag; +import mytown.entities.BlockWhitelist; +import mytown.entities.Resident; +import mytown.entities.Town; import mytown.entities.flag.FlagType; -import mytown.protection.Protection; -import mytown.protection.Protections; import mytown.proxies.DatasourceProxy; import mytown.proxies.LocalizationProxy; import mytown.util.Constants; @@ -23,8 +22,6 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagList; -import net.minecraft.nbt.NBTTagString; -import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; @@ -83,7 +80,7 @@ private void checkLocationAndSendMap(EntityEvent.EnteringChunk ev) { Town lastTown = Utils.getTownAtPosition(ev.entity.dimension, ev.oldChunkX, ev.oldChunkZ); Town currTown = Utils.getTownAtPosition(ev.entity.dimension, ev.newChunkX, ev.newChunkZ); - if(currTown != null && (lastTown == null || currTown != lastTown)) + if (currTown != null && (lastTown == null || currTown != lastTown)) TownEvent.fire(new TownEvent.TownEnterEvent(currTown, res)); if (res.isMapOn()) { @@ -107,12 +104,11 @@ public void onItemUse(PlayerInteractEvent ev) { return; - ItemStack currentStack = ev.entityPlayer.inventory.getCurrentItem(); if (currentStack == null) return; - if((ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK || ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_AIR) && ev.entityPlayer.isSneaking()) { - if(currentStack.getItem().equals(Items.wooden_hoe) && currentStack.getDisplayName().equals(Constants.EDIT_TOOL_NAME)) { + if ((ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK || ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_AIR) && ev.entityPlayer.isSneaking()) { + if (currentStack.getItem().equals(Items.wooden_hoe) && currentStack.getDisplayName().equals(Constants.EDIT_TOOL_NAME)) { // For shift right clicking the selector, we may need it } } @@ -124,7 +120,7 @@ public void onItemUse(PlayerInteractEvent ev) { NBTTagList lore = currentStack.getTagCompound().getCompoundTag("display").getTagList("Lore", 8); String description = lore.getStringTagAt(0); - if(description.equals(Constants.EDIT_TOOL_DESCRIPTION_PLOT)) { + if (description.equals(Constants.EDIT_TOOL_DESCRIPTION_PLOT)) { if (res.isFirstPlotSelectionActive() && res.isSecondPlotSelectionActive()) { ChatUtils.sendLocalizedChat(ev.entityPlayer, LocalizationProxy.getLocalization(), "mytown.cmd.err.plot.alreadySelected"); } else { @@ -143,7 +139,7 @@ public void onItemUse(PlayerInteractEvent ev) { } else if (description.equals(Constants.EDIT_TOOL_DESCRIPTION_BLOCK_WHITELIST)) { town = MyTownUniverse.getInstance().getTownsMap().get(Utils.getTownNameFromLore(ev.entityPlayer)); Town townAt = Utils.getTownAtPosition(ev.world.provider.dimensionId, ev.x >> 4, ev.z >> 4); - if(town == null || town != townAt) { + if (town == null || town != townAt) { res.sendMessage(LocalizationProxy.getLocalization().getLocalization("mytown.cmd.err.blockNotInTown")); } else { // If town is found then create of delete the block whitelist @@ -151,7 +147,7 @@ public void onItemUse(PlayerInteractEvent ev) { FlagType flagType = FlagType.valueOf(Utils.getFlagNameFromLore(ev.entityPlayer)); ev.entityPlayer.setCurrentItemOrArmor(0, null); BlockWhitelist bw = town.getBlockWhitelist(ev.world.provider.dimensionId, ev.x, ev.y, ev.z, flagType); - if(bw == null) { + if (bw == null) { bw = new BlockWhitelist(ev.world.provider.dimensionId, ev.x, ev.y, ev.z, flagType); res.sendMessage(LocalizationProxy.getLocalization().getLocalization("mytown.notification.perm.town.whitelist.added")); DatasourceProxy.getDatasource().saveBlockWhitelist(bw, town); diff --git a/src/main/java/mytown/protection/BloodMagicProtection.java b/src/main/java/mytown/protection/BloodMagicProtection.java index 187f883e..d7fa99ab 100644 --- a/src/main/java/mytown/protection/BloodMagicProtection.java +++ b/src/main/java/mytown/protection/BloodMagicProtection.java @@ -28,11 +28,11 @@ public class BloodMagicProtection extends Protection { @SuppressWarnings("unchecked") public BloodMagicProtection() { try { - clsBoundPickaxe = (Class)Class.forName("WayofTime.alchemicalWizardry.common.items.BoundPickaxe"); - clsSigilWater = (Class)Class.forName("WayofTime.alchemicalWizardry.common.items.sigil.WaterSigil"); - clsSigilLava = (Class)Class.forName("WayofTime.alchemicalWizardry.common.items.sigil.LavaSigil"); - clsSigilVoid = (Class)Class.forName("WayofTime.alchemicalWizardry.common.items.sigil.VoidSigil"); - clsSigilMagnetism = (Class)Class.forName("WayofTime.alchemicalWizardry.common.items.sigil.SigilOfMagnetism"); + clsBoundPickaxe = (Class) Class.forName("WayofTime.alchemicalWizardry.common.items.BoundPickaxe"); + clsSigilWater = (Class) Class.forName("WayofTime.alchemicalWizardry.common.items.sigil.WaterSigil"); + clsSigilLava = (Class) Class.forName("WayofTime.alchemicalWizardry.common.items.sigil.LavaSigil"); + clsSigilVoid = (Class) Class.forName("WayofTime.alchemicalWizardry.common.items.sigil.VoidSigil"); + clsSigilMagnetism = (Class) Class.forName("WayofTime.alchemicalWizardry.common.items.sigil.SigilOfMagnetism"); } catch (Exception e) { e.printStackTrace(); MyTown.instance.log.error("Failed to load BloodMagic classes!"); @@ -54,26 +54,26 @@ public BloodMagicProtection() { @Override public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { //MyTown.instance.log.info("Got item: " + itemStack.getDisplayName()); - if(clsBoundPickaxe == itemStack.getItem().getClass()) { + if (clsBoundPickaxe == itemStack.getItem().getClass()) { // Range is 11x11 around the player. List townsNearby = Utils.getTownsInRange(bp.dim, bp.x, bp.z, 5, 5); - for(Town town : townsNearby) { - boolean breakBlock = (Boolean)town.getValue(FlagType.breakBlocks); - if(!breakBlock) { + for (Town town : townsNearby) { + boolean breakBlock = (Boolean) town.getValue(FlagType.breakBlocks); + if (!breakBlock) { // If resident is null then it's used by a block - if(res == null) { + if (res == null) { town.notifyEveryone(FlagType.breakBlocks.getLocalizedProtectionDenial()); return true; - } else if(!town.checkPermission(res, FlagType.breakBlocks, res.getPlayer().dimension, (int)res.getPlayer().posX, (int)res.getPlayer().posY, (int)res.getPlayer().posZ)) { + } else if (!town.checkPermission(res, FlagType.breakBlocks, res.getPlayer().dimension, (int) res.getPlayer().posX, (int) res.getPlayer().posY, (int) res.getPlayer().posZ)) { res.sendMessage(FlagType.breakBlocks.getLocalizedProtectionDenial()); return true; } } } - } else if(clsSigilLava == itemStack.getItem().getClass() || clsSigilWater == itemStack.getItem().getClass() || clsSigilVoid == itemStack.getItem().getClass()) { + } else if (clsSigilLava == itemStack.getItem().getClass() || clsSigilWater == itemStack.getItem().getClass() || clsSigilVoid == itemStack.getItem().getClass()) { - if(res != null) { + if (res != null) { MovingObjectPosition pos; pos = Utils.getMovingObjectPositionFromPlayer(res.getPlayer().getEntityWorld(), res.getPlayer(), false); @@ -106,7 +106,7 @@ public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { Town town = Utils.getTownAtPosition(res.getPlayer().dimension, x >> 4, z >> 4); if (town != null) { - boolean itemUsage = (Boolean)town.getValueAtCoords(res.getPlayer().dimension, x, y, z, FlagType.useItems); + boolean itemUsage = (Boolean) town.getValueAtCoords(res.getPlayer().dimension, x, y, z, FlagType.useItems); if (!itemUsage && !town.checkPermission(res, FlagType.useItems, res.getPlayer().dimension, x, y, z)) { res.sendMessage(FlagType.useItems.getLocalizedProtectionDenial()); return true; @@ -141,7 +141,7 @@ public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { Town town = Utils.getTownAtPosition(bp.dim, x >> 4, z >> 4); if (town != null) { - boolean itemUsage = (Boolean)town.getValueAtCoords(bp.dim, x, y, z, FlagType.useItems); + boolean itemUsage = (Boolean) town.getValueAtCoords(bp.dim, x, y, z, FlagType.useItems); if (!itemUsage) { town.notifyEveryone(FlagType.useItems.getLocalizedTownNotification()); return true; @@ -149,21 +149,21 @@ public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { } } - } else if(clsSigilMagnetism == itemStack.getItem().getClass()) { + } else if (clsSigilMagnetism == itemStack.getItem().getClass()) { // Range to attract items is 5 from player List nearbyTowns = Utils.getTownsInRange(bp.dim, bp.x, bp.z, 5, 5); - for(Town town : nearbyTowns) { - boolean pickupFlag = (Boolean)town.getValue(FlagType.pickupItems); - if(!pickupFlag) - if(res == null) { + for (Town town : nearbyTowns) { + boolean pickupFlag = (Boolean) town.getValue(FlagType.pickupItems); + if (!pickupFlag) + if (res == null) { deactivateSigil(itemStack); return true; - } else if(!town.checkPermission(res, FlagType.pickupItems, res.getPlayer().dimension, (int)res.getPlayer().posX, (int)res.getPlayer().posY, (int)res.getPlayer().posZ)) { + } else if (!town.checkPermission(res, FlagType.pickupItems, res.getPlayer().dimension, (int) res.getPlayer().posX, (int) res.getPlayer().posY, (int) res.getPlayer().posZ)) { res.sendMessage(getLocal().getLocalization("mytown.protection.itemUsage.nearby")); // TODO: Rework the check for sigils that are already activated deactivateSigil(itemStack); return true; - } + } } } return false; diff --git a/src/main/java/mytown/protection/BotaniaProtection.java b/src/main/java/mytown/protection/BotaniaProtection.java index aa1e3996..732ab42e 100644 --- a/src/main/java/mytown/protection/BotaniaProtection.java +++ b/src/main/java/mytown/protection/BotaniaProtection.java @@ -2,18 +2,13 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import mytown.MyTown; -import mytown.datasource.MyTownUniverse; import mytown.entities.Resident; import mytown.entities.Town; -import mytown.entities.TownBlock; import mytown.entities.flag.FlagType; import mytown.proxies.DatasourceProxy; import mytown.util.Utils; -import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.world.NextTickListEntry; -import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.entity.player.PlayerInteractEvent; @@ -31,7 +26,7 @@ public class BotaniaProtection extends Protection { public BotaniaProtection() { isHandlingEvents = true; try { - clsTerraPick = (Class)Class.forName("vazkii.botania.common.item.equipment.tool.ItemTerraPick"); + clsTerraPick = (Class) Class.forName("vazkii.botania.common.item.equipment.tool.ItemTerraPick"); } catch (Exception e) { MyTown.instance.log.error("Failed to load Botania classes!"); } @@ -78,19 +73,18 @@ public void onPlayerBreaks(PlayerInteractEvent ev) { } /** - * @author Vazkii - * * @param stack * @return + * @author Vazkii */ public int getLevel(ItemStack stack) { - int[] LEVELS = new int[] { + int[] LEVELS = new int[]{ 0, 10000, 1000000, 10000000, 100000000, 1000000000 }; int mana = stack.getTagCompound().getInteger("mana"); - for(int i = LEVELS.length - 1; i > 0; i--) - if(mana >= LEVELS[i]) + for (int i = LEVELS.length - 1; i > 0; i--) + if (mana >= LEVELS[i]) return i; return 0; } diff --git a/src/main/java/mytown/protection/BuildCraftFactoryProtection.java b/src/main/java/mytown/protection/BuildCraftFactoryProtection.java index c2fc49c6..a49419ba 100644 --- a/src/main/java/mytown/protection/BuildCraftFactoryProtection.java +++ b/src/main/java/mytown/protection/BuildCraftFactoryProtection.java @@ -1,6 +1,5 @@ package mytown.protection; -import buildcraft.builders.TileAbstractBuilder; import buildcraft.core.BlockIndex; import buildcraft.core.Box; import buildcraft.factory.TilePump; @@ -9,7 +8,6 @@ import mytown.entities.Town; import mytown.entities.TownBlock; import mytown.entities.Wild; -import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; import mytown.util.ChunkPos; import mytown.util.Utils; @@ -31,7 +29,7 @@ public class BuildCraftFactoryProtection extends Protection { public BuildCraftFactoryProtection() { // We need reflection only for loading the mod clsTileAbstractBuilder = - clsTilePump = TilePump.class; + clsTilePump = TilePump.class; trackedTileEntities.add(clsTilePump); trackedTileEntities.add(clsTileAbstractBuilder); @@ -41,7 +39,7 @@ public BuildCraftFactoryProtection() { @Override public boolean checkTileEntity(TileEntity te) { - if(clsTileAbstractBuilder.isAssignableFrom(te.getClass())) { + if (clsTileAbstractBuilder.isAssignableFrom(te.getClass())) { // In case we add more tile entities to check Box box = null; try { @@ -53,37 +51,37 @@ public boolean checkTileEntity(TileEntity te) { } List chunks = Utils.getChunksInBox(box.xMin, box.zMin, box.xMax, box.zMax); - for(ChunkPos p : chunks) { + for (ChunkPos p : chunks) { TownBlock block = MyTownUniverse.getInstance().getBlocksMap().get(String.format(TownBlock.keyFormat, te.getWorldObj().provider.dimensionId, p.getX(), p.getZ())); - if(block == null) { - if(!(Boolean) Wild.getInstance().getFlag(FlagType.breakBlocks).getValue()) { + if (block == null) { + if (!(Boolean) Wild.getInstance().getFlag(FlagType.breakBlocks).getValue()) { MyTown.instance.log.info("A buildcraft machine at coordonates " + te.xCoord + ", " + te.yCoord + ", " + te.zCoord + " in dimension " + te.getWorldObj().provider.dimensionId + " tried to bypass protection!"); return true; } } else { // Directly from the town, not checking per plot since it's quite the pain - boolean bcFlag = (Boolean)block.getTown().getValue(FlagType.breakBlocks); - if(!bcFlag) { + boolean bcFlag = (Boolean) block.getTown().getValue(FlagType.breakBlocks); + if (!bcFlag) { block.getTown().notifyEveryone(FlagType.breakBlocks.getLocalizedTownNotification()); MyTown.instance.log.info("A buildcraft machine at coordonates " + te.xCoord + ", " + te.yCoord + ", " + te.zCoord + " in dimension " + te.getWorldObj().provider.dimensionId + " tried to bypass protection!"); return true; } } } - } else if(clsTilePump.isAssignableFrom(te.getClass())) { + } else if (clsTilePump.isAssignableFrom(te.getClass())) { try { Method method = clsTilePump.getMethod("getNextIndexToPump", Boolean.class); method.setAccessible(true); // Invoke method: getting the next block to pump, but not removing it - BlockIndex blockIndex = (BlockIndex)method.invoke(te, false); + BlockIndex blockIndex = (BlockIndex) method.invoke(te, false); Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, blockIndex.x >> 4, blockIndex.z >> 4); - if(town == null) { - if(!(Boolean)Wild.getInstance().getFlag(FlagType.pumps).getValue()) { + if (town == null) { + if (!(Boolean) Wild.getInstance().getFlag(FlagType.pumps).getValue()) { MyTown.instance.log.info("A buildcraft machine at coordonates " + te.xCoord + ", " + te.yCoord + ", " + te.zCoord + " in dimension " + te.getWorldObj().provider.dimensionId + " tried to bypass protection!"); return true; } } else { - if (!((Boolean)town.getValue(FlagType.pumps))) { + if (!((Boolean) town.getValue(FlagType.pumps))) { MyTown.instance.log.info("A buildcraft machine at coordonates " + te.xCoord + ", " + te.yCoord + ", " + te.zCoord + " in dimension " + te.getWorldObj().provider.dimensionId + " tried to bypass protection!"); town.notifyEveryone(FlagType.pumps.getLocalizedTownNotification()); return true; @@ -99,9 +97,9 @@ public boolean checkTileEntity(TileEntity te) { @Override public List getFlagTypeForTile(Class te) { List list = new ArrayList(); - if(clsTileAbstractBuilder.isAssignableFrom(te)) { + if (clsTileAbstractBuilder.isAssignableFrom(te)) { list.add(FlagType.breakBlocks); - } else if(clsTilePump.isAssignableFrom(te)) { + } else if (clsTilePump.isAssignableFrom(te)) { list.add(FlagType.pumps); } return list; diff --git a/src/main/java/mytown/protection/BuildCraftTransportProtection.java b/src/main/java/mytown/protection/BuildCraftTransportProtection.java index d9394936..f2677c96 100644 --- a/src/main/java/mytown/protection/BuildCraftTransportProtection.java +++ b/src/main/java/mytown/protection/BuildCraftTransportProtection.java @@ -1,17 +1,7 @@ package mytown.protection; import cpw.mods.fml.common.registry.GameRegistry; -import mytown.MyTown; -import mytown.entities.Town; -import mytown.entities.TownBlock; -import mytown.entities.flag.FlagType; import mytown.proxies.mod.ModProxies; -import mytown.util.BlockPos; -import mytown.util.Utils; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.DimensionManager; - -import java.util.List; /** * Created by AfterWind on 9/21/2014. diff --git a/src/main/java/mytown/protection/ExtraUtilitiesProtection.java b/src/main/java/mytown/protection/ExtraUtilitiesProtection.java index d6b5127d..42c6e136 100644 --- a/src/main/java/mytown/protection/ExtraUtilitiesProtection.java +++ b/src/main/java/mytown/protection/ExtraUtilitiesProtection.java @@ -2,9 +2,7 @@ import mytown.MyTown; import mytown.entities.Town; -import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; -import mytown.protection.Protection; import mytown.util.ChunkPos; import mytown.util.Utils; import net.minecraft.tileentity.TileEntity; @@ -25,8 +23,8 @@ public class ExtraUtilitiesProtection extends Protection { @SuppressWarnings("unchecked") public ExtraUtilitiesProtection() { try { - clsTileEnderQuarry = (Class)Class.forName("com.rwtema.extrautils.tileentity.enderquarry.TileEntityEnderQuarry"); - clsTileEnderPump = (Class)Class.forName("com.rwtema.extrautils.tileentity.TileEntityEnderThermicLavaPump"); + clsTileEnderQuarry = (Class) Class.forName("com.rwtema.extrautils.tileentity.enderquarry.TileEntityEnderQuarry"); + clsTileEnderPump = (Class) Class.forName("com.rwtema.extrautils.tileentity.TileEntityEnderThermicLavaPump"); trackedTileEntities.add(clsTileEnderPump); trackedTileEntities.add(clsTileEnderQuarry); @@ -39,7 +37,7 @@ public ExtraUtilitiesProtection() { @SuppressWarnings("unchecked") @Override public boolean checkTileEntity(TileEntity te) { - if(clsTileEnderQuarry.isAssignableFrom(te.getClass())) { + if (clsTileEnderQuarry.isAssignableFrom(te.getClass())) { // Ender Quarry try { Field minX = clsTileEnderQuarry.getDeclaredField("min_x"); @@ -52,10 +50,10 @@ public boolean checkTileEntity(TileEntity te) { maxZ.setAccessible(true); List chunks = Utils.getChunksInBox(minX.getInt(te), minZ.getInt(te), maxX.getInt(te), maxZ.getInt(te)); - for(ChunkPos cp : chunks) { + for (ChunkPos cp : chunks) { Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, cp.getX(), cp.getZ()); - if(town != null) { - if(!((Boolean)town.getValue(FlagType.breakBlocks))) { + if (town != null) { + if (!((Boolean) town.getValue(FlagType.breakBlocks))) { town.notifyEveryone(FlagType.breakBlocks.getLocalizedTownNotification()); return true; } @@ -64,7 +62,7 @@ public boolean checkTileEntity(TileEntity te) { } catch (Exception e) { e.printStackTrace(); } - } else if(clsTileEnderPump.isAssignableFrom(te.getClass())) { + } else if (clsTileEnderPump.isAssignableFrom(te.getClass())) { try { Field chunkX = clsTileEnderPump.getDeclaredField("chunk_x"); chunkX.setAccessible(true); @@ -72,7 +70,7 @@ public boolean checkTileEntity(TileEntity te) { chunkZ.setAccessible(true); Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, chunkX.getInt(te), chunkZ.getInt(te)); - if(town != null && !((Boolean)town.getValue(FlagType.pumps))) { + if (town != null && !((Boolean) town.getValue(FlagType.pumps))) { town.notifyEveryone(FlagType.pumps.getLocalizedTownNotification()); return true; } @@ -86,9 +84,9 @@ public boolean checkTileEntity(TileEntity te) { @Override public List getFlagTypeForTile(Class te) { List list = new ArrayList(); - if(clsTileEnderQuarry.isAssignableFrom(te)) + if (clsTileEnderQuarry.isAssignableFrom(te)) list.add(FlagType.breakBlocks); - else if(clsTileEnderPump.isAssignableFrom(te)) + else if (clsTileEnderPump.isAssignableFrom(te)) list.add(FlagType.pumps); return list; } diff --git a/src/main/java/mytown/protection/IC2Protection.java b/src/main/java/mytown/protection/IC2Protection.java index 87c5aec2..9d224ea8 100644 --- a/src/main/java/mytown/protection/IC2Protection.java +++ b/src/main/java/mytown/protection/IC2Protection.java @@ -1,14 +1,8 @@ package mytown.protection; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -//import ic2.api.event.LaserEvent; -import mytown.MyTown; -import mytown.entities.Resident; -import mytown.entities.TownBlock; -import mytown.entities.flag.FlagType; -import mytown.proxies.DatasourceProxy; import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; + +//import ic2.api.event.LaserEvent; /** * Created by AfterWind on 7/8/2014. @@ -22,10 +16,10 @@ public IC2Protection() { isHandlingEvents = true; try { - this.explosiveBlocks.add((Class)Class.forName("ic2.core.block.EntityNuke")); - this.explosiveBlocks.add((Class)Class.forName("ic2.core.block.EntityItnt")); - this.explosiveBlocks.add((Class)Class.forName("ic2.core.block.EntityDynamite")); - this.explosiveBlocks.add((Class)Class.forName("ic2.core.block.EntityStickyDynamite")); + this.explosiveBlocks.add((Class) Class.forName("ic2.core.block.EntityNuke")); + this.explosiveBlocks.add((Class) Class.forName("ic2.core.block.EntityItnt")); + this.explosiveBlocks.add((Class) Class.forName("ic2.core.block.EntityDynamite")); + this.explosiveBlocks.add((Class) Class.forName("ic2.core.block.EntityStickyDynamite")); } catch (ClassNotFoundException ex) { ex.printStackTrace(); diff --git a/src/main/java/mytown/protection/MekanismProtection.java b/src/main/java/mytown/protection/MekanismProtection.java index 37adf6db..1a35fc53 100644 --- a/src/main/java/mytown/protection/MekanismProtection.java +++ b/src/main/java/mytown/protection/MekanismProtection.java @@ -11,7 +11,7 @@ public class MekanismProtection extends Protection { @SuppressWarnings("unchecked") public MekanismProtection() { try { - Class clsObsidianTNT = (Class)Class.forName("mekanism.common.entity.EntityObsidianTNT"); + Class clsObsidianTNT = (Class) Class.forName("mekanism.common.entity.EntityObsidianTNT"); explosiveBlocks.add(clsObsidianTNT); } catch (Exception e) { MyTown.instance.log.info("Failed to load Mekanism classes!"); diff --git a/src/main/java/mytown/protection/MinefactoryReloadedProtection.java b/src/main/java/mytown/protection/MinefactoryReloadedProtection.java index 536640bf..2fe5fde0 100644 --- a/src/main/java/mytown/protection/MinefactoryReloadedProtection.java +++ b/src/main/java/mytown/protection/MinefactoryReloadedProtection.java @@ -35,10 +35,10 @@ public class MinefactoryReloadedProtection extends Protection { @SuppressWarnings("unchecked") public MinefactoryReloadedProtection() { try { - Class clsFishingRod = (Class)Class.forName("powercrystals.minefactoryreloaded.entity.EntityFishingRod"); - Class clsRocket = (Class)Class.forName("powercrystals.minefactoryreloaded.entity.EntityRocket"); + Class clsFishingRod = (Class) Class.forName("powercrystals.minefactoryreloaded.entity.EntityFishingRod"); + Class clsRocket = (Class) Class.forName("powercrystals.minefactoryreloaded.entity.EntityRocket"); - clsTileEntityFactory = (Class)Class.forName("powercrystals.minefactoryreloaded.tile.base.TileEntityFactory"); + clsTileEntityFactory = (Class) Class.forName("powercrystals.minefactoryreloaded.tile.base.TileEntityFactory"); Class clsAreaManager = Class.forName("powercrystals.minefactoryreloaded.core.HarvestAreaManager"); Class clsArea = Class.forName("cofh.lib.util.position.Area"); @@ -65,17 +65,17 @@ public MinefactoryReloadedProtection() { @SuppressWarnings("unchecked") @Override public boolean checkTileEntity(TileEntity te) { - if(clsTileEntityFactory.isAssignableFrom(te.getClass())) { + if (clsTileEntityFactory.isAssignableFrom(te.getClass())) { MyTown.instance.log.info("Checking machine in mfr."); // Getting harvest area manager Object areaManager = mAccessTile.invoke(te, "getHAM"); - if(areaManager == null) + if (areaManager == null) return false; // Getting area Object areaObj = mAccessArea.invoke(areaManager, "getHarvestArea"); - if(areaObj == null) + if (areaObj == null) return false; List chunkPos = Utils.getChunksInBox(fAccessArea.getInt(areaObj, fAccessArea.getIndex("xMin")), fAccessArea.getInt(areaObj, fAccessArea.getIndex("zMin")), fAccessArea.getInt(areaObj, fAccessArea.getIndex("xMax")), fAccessArea.getInt(areaObj, fAccessArea.getIndex("zMax"))); @@ -84,7 +84,7 @@ public boolean checkTileEntity(TileEntity te) { if (town != null) { //DEV MyTown.instance.log.info("Found town for mfr protection: " + town.getName()); - boolean breakFlag = (Boolean)town.getValue(FlagType.breakBlocks); + boolean breakFlag = (Boolean) town.getValue(FlagType.breakBlocks); if (!breakFlag && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.breakBlocks)) { town.notifyEveryone(FlagType.breakBlocks.getLocalizedTownNotification()); return true; @@ -97,13 +97,13 @@ public boolean checkTileEntity(TileEntity te) { @Override public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { - if(itemStack.getItem() == safariNet || itemStack.getItem() == safariNetR || itemStack.getItem() == safariNetJ || itemStack.getItem() == portaSpawner) { + if (itemStack.getItem() == safariNet || itemStack.getItem() == safariNetR || itemStack.getItem() == safariNetJ || itemStack.getItem() == portaSpawner) { MyTown.instance.log.info("Found safari net usage!"); Town town = Utils.getTownAtPosition(bp.dim, bp.x >> 4, bp.z >> 4); - if(town != null) { - boolean entityFlag = (Boolean)town.getValueAtCoords(bp.dim, bp.x, bp.y, bp.z, FlagType.attackEntities); - if(!entityFlag && (res == null || !town.checkPermission(res, FlagType.attackEntities))) { - if(res != null) + if (town != null) { + boolean entityFlag = (Boolean) town.getValueAtCoords(bp.dim, bp.x, bp.y, bp.z, FlagType.attackEntities); + if (!entityFlag && (res == null || !town.checkPermission(res, FlagType.attackEntities))) { + if (res != null) res.sendMessage(FlagType.attackEntities.getLocalizedProtectionDenial()); else town.notifyEveryone(FlagType.attackEntities.getLocalizedTownNotification()); @@ -117,7 +117,7 @@ public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { @Override public List getFlagTypeForTile(Class te) { List list = new ArrayList(); - if(te.isAssignableFrom(clsTileEntityFactory)) + if (te.isAssignableFrom(clsTileEntityFactory)) list.add(FlagType.breakBlocks); return list; } diff --git a/src/main/java/mytown/protection/Protection.java b/src/main/java/mytown/protection/Protection.java index 71e2d406..463be7e8 100644 --- a/src/main/java/mytown/protection/Protection.java +++ b/src/main/java/mytown/protection/Protection.java @@ -1,12 +1,10 @@ package mytown.protection; -import mytown.MyTown; import mytown.core.Localization; import mytown.datasource.MyTownDatasource; import mytown.entities.Resident; import mytown.entities.Town; import mytown.entities.Wild; -import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; import mytown.proxies.DatasourceProxy; import mytown.proxies.LocalizationProxy; @@ -85,6 +83,7 @@ public Protection() { interactiveBlocks = new ArrayList(); isHandlingEvents = false; } + /** * Checks the entity and returns whether or not the entity was destroyed * If you override this, call super method. @@ -95,21 +94,21 @@ public Protection() { @SuppressWarnings("unchecked") public boolean checkEntity(Entity entity) { Town town = Utils.getTownAtPosition(entity.dimension, entity.chunkCoordX, entity.chunkCoordZ); - if(town == null) { + if (town == null) { //Wild explosives - if(explosiveBlocks.contains(entity.getClass())) { + if (explosiveBlocks.contains(entity.getClass())) { //MyTown.instance.log.info("Checking entity with explosives."); - if (!(Boolean)Wild.getInstance().getFlag(FlagType.explosions).getValue()) { + if (!(Boolean) Wild.getInstance().getFlag(FlagType.explosions).getValue()) { //Temporary - if(entity instanceof EntityWitherSkull) - return false; + if (entity instanceof EntityWitherSkull) + return false; return true; } } } else { - String value = (String)town.getValueAtCoords(entity.dimension, (int) entity.posX, (int) entity.posY, (int) entity.posZ, FlagType.mobs); + String value = (String) town.getValueAtCoords(entity.dimension, (int) entity.posX, (int) entity.posY, (int) entity.posZ, FlagType.mobs); if (value.equals("none")) { if (entity instanceof EntityLivingBase) { return true; @@ -120,7 +119,7 @@ public boolean checkEntity(Entity entity) { } } - boolean explosionValue = (Boolean)town.getValueAtCoords(entity.dimension, (int) entity.posX, (int) entity.posY, (int) entity.posZ, FlagType.explosions); + boolean explosionValue = (Boolean) town.getValueAtCoords(entity.dimension, (int) entity.posX, (int) entity.posY, (int) entity.posZ, FlagType.explosions); if (!explosionValue) { if (explosiveBlocks.contains(entity.getClass())) { return true; @@ -138,7 +137,9 @@ public boolean checkEntity(Entity entity) { * @param te * @return */ - public boolean checkTileEntity(TileEntity te) { return false; } + public boolean checkTileEntity(TileEntity te) { + return false; + } /** * Checks if the resident or block with tile entity can use this item. @@ -148,30 +149,46 @@ public boolean checkEntity(Entity entity) { * @param res * @return */ - public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { return false; } + public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { + return false; + } public boolean hasToCheckTileEntity(TileEntity te) { - for(Class cls : trackedTileEntities) { - if(cls.isAssignableFrom(te.getClass())) + for (Class cls : trackedTileEntities) { + if (cls.isAssignableFrom(te.getClass())) return true; } return false; } - public boolean hasToCheckEntity(Entity entity) { return trackedEntities.contains(entity.getClass()) || explosiveBlocks.contains(entity.getClass()); } + + public boolean hasToCheckEntity(Entity entity) { + return trackedEntities.contains(entity.getClass()) || explosiveBlocks.contains(entity.getClass()); + } /** * Gets the range at which items can range bypassing flags + * * @return */ - public int getRange() { return 0; } + public int getRange() { + return 0; + } - public final List getFlagTypeForTile(TileEntity te) { return getFlagTypeForTile(te.getClass()); } - public List getFlagTypeForTile(Class te) { return null; } + public final List getFlagTypeForTile(TileEntity te) { + return getFlagTypeForTile(te.getClass()); + } + + public List getFlagTypeForTile(Class te) { + return null; + } /* ---- Helpers ---- */ protected MyTownDatasource getDatasource() { return DatasourceProxy.getDatasource(); } - protected Localization getLocal() {return LocalizationProxy.getLocalization(); } + + protected Localization getLocal() { + return LocalizationProxy.getLocalization(); + } } diff --git a/src/main/java/mytown/protection/Protections.java b/src/main/java/mytown/protection/Protections.java index 9ae56d20..d5c075ed 100644 --- a/src/main/java/mytown/protection/Protections.java +++ b/src/main/java/mytown/protection/Protections.java @@ -33,11 +33,7 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.world.BlockEvent; -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Iterator; +import java.util.*; /** * Created by AfterWind on 9/2/2014. @@ -76,7 +72,7 @@ public Protections() { */ public void addProtection(Protection prot, String modid) { protections.put(modid, prot); - if(prot.getRange() > maximalRange) + if (prot.getRange() > maximalRange) maximalRange = prot.getRange(); if (prot.isHandlingEvents) { @@ -95,9 +91,9 @@ public void addProtection(Protection prot, String modid) { * @param town */ private void addToBlockWhitelist(Class te, int dim, int x, int y, int z, Town town) { - for(Protection prot : protections.values()) { - if(prot.trackedTileEntities.contains(te)) - for(FlagType flagType : prot.getFlagTypeForTile(te)) { + for (Protection prot : protections.values()) { + if (prot.trackedTileEntities.contains(te)) + for (FlagType flagType : prot.getFlagTypeForTile(te)) { if (!town.hasBlockWhitelist(dim, x, y, z, flagType)) { BlockWhitelist bw = new BlockWhitelist(dim, x, y, z, flagType); DatasourceProxy.getDatasource().saveBlockWhitelist(bw, town); @@ -127,39 +123,40 @@ private void removeFromWhitelist(Class te, int dim, int x, } } } + public List getFlagTypesForTile(TileEntity te) { List list = new ArrayList(); - for(Protection prot : protections.values()) - if(prot.hasToCheckTileEntity(te)) + for (Protection prot : protections.values()) + if (prot.hasToCheckTileEntity(te)) list.addAll(prot.getFlagTypeForTile(te.getClass())); return list; } public boolean checkTileEntity(TileEntity te) { - for(Protection prot : protections.values()) - if(prot.checkTileEntity(te)) + for (Protection prot : protections.values()) + if (prot.checkTileEntity(te)) return true; return false; } public boolean checkItemUsage(ItemStack stack, Resident res, BlockPos bp) { - for(Protection prot : protections.values()) - if(prot.checkItemUsage(stack, res, bp)) + for (Protection prot : protections.values()) + if (prot.checkItemUsage(stack, res, bp)) return true; return false; } public boolean checkActivatedBlocks(Block block) { - for(Protection prot : protections.values()) { - if(prot.activatedBlocks.contains(block)) + for (Protection prot : protections.values()) { + if (prot.activatedBlocks.contains(block)) return true; } return false; } public boolean checkIsEntityHostile(Class ent) { - for(Protection prot : protections.values()) { - if(prot.hostileEntities.contains(ent)) { + for (Protection prot : protections.values()) { + if (prot.hostileEntities.contains(ent)) { return true; } } @@ -169,14 +166,14 @@ public boolean checkIsEntityHostile(Class ent) { public boolean isBlockWhitelistValid(BlockWhitelist bw) { // TODO: Maybe make this better // Delete if the town is gone - if(Utils.getTownAtPosition(bw.dim, bw.x >> 4, bw.z >> 4) == null) + if (Utils.getTownAtPosition(bw.dim, bw.x >> 4, bw.z >> 4) == null) bw.delete(); - if(bw.getFlagType() == FlagType.activateBlocks && !checkActivatedBlocks(DimensionManager.getWorld(bw.dim).getBlock(bw.x, bw.y, bw.z))) + if (bw.getFlagType() == FlagType.activateBlocks && !checkActivatedBlocks(DimensionManager.getWorld(bw.dim).getBlock(bw.x, bw.y, bw.z))) return false; - if((bw.getFlagType() == FlagType.breakBlocks || bw.getFlagType() == FlagType.placeBlocks || bw.getFlagType() == FlagType.activateBlocks || bw.getFlagType() == FlagType.useItems || bw.getFlagType() == FlagType.pumps)) { + if ((bw.getFlagType() == FlagType.breakBlocks || bw.getFlagType() == FlagType.placeBlocks || bw.getFlagType() == FlagType.activateBlocks || bw.getFlagType() == FlagType.useItems || bw.getFlagType() == FlagType.pumps)) { TileEntity te = DimensionManager.getWorld(bw.dim).getTileEntity(bw.x, bw.y, bw.z); - if(te == null) return false; + if (te == null) return false; return getFlagTypesForTile(te).contains(bw.getFlagType()); } return true; @@ -186,11 +183,11 @@ public boolean isBlockWhitelistValid(BlockWhitelist bw) { @SuppressWarnings("unchecked") @SubscribeEvent public void tick(TickEvent.WorldTickEvent ev) { - if(ev.world.isRemote) + if (ev.world.isRemote) return; // Ticker for updating the map - if(ticker == 0) { + if (ticker == 0) { //MyTown.instance.log.info("Updating check maps."); for (Map.Entry entry : checkedEntities.entrySet()) { entry.setValue(false); @@ -198,7 +195,7 @@ public void tick(TickEvent.WorldTickEvent ev) { for (Iterator> it = checkedTileEntities.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = it.next(); - if(entry.getKey().isInvalid()) + if (entry.getKey().isInvalid()) it.remove(); else entry.setValue(false); @@ -210,12 +207,12 @@ public void tick(TickEvent.WorldTickEvent ev) { // TODO: Add a command to clean up the block whitelist table periodically - if(ticker2 == 0) { + if (ticker2 == 0) { // Also updating the block whitelists - for(Town town : MyTownUniverse.getInstance().getTownsMap().values()) { - for(BlockWhitelist bw : town.getWhitelists()) { - if(!isBlockWhitelistValid(bw)) { + for (Town town : MyTownUniverse.getInstance().getTownsMap().values()) { + for (BlockWhitelist bw : town.getWhitelists()) { + if (!isBlockWhitelistValid(bw)) { bw.delete(); } } @@ -233,7 +230,7 @@ public void tick(TickEvent.WorldTickEvent ev) { // Player check, every tick Town town = Utils.getTownAtPosition(entity.dimension, entity.chunkCoordX, entity.chunkCoordZ); - if(entity instanceof EntityPlayer) { + if (entity instanceof EntityPlayer) { Resident res = DatasourceProxy.getDatasource().getOrMakeResident(entity); ChunkCoordinates playerPos = res.getPlayer().getPlayerCoordinates(); @@ -248,7 +245,7 @@ public void tick(TickEvent.WorldTickEvent ev) { } } */ - if(town != null) { + if (town != null) { if (!town.checkPermission(res, FlagType.enter, entity.dimension, playerPos.posX, playerPos.posY, playerPos.posZ)) { res.respawnPlayer(); res.protectionDenial("§cYou have been moved because you can't access this place!", Formatter.formatOwnersToString(town.getOwnersAtPosition(entity.dimension, playerPos.posX, playerPos.posY, playerPos.posZ))); @@ -285,7 +282,7 @@ public void tick(TickEvent.WorldTickEvent ev) { // Prechecks go here if (prot.hasToCheckTileEntity(te)) { // Checks go here - if((checkedTileEntities.get(te) == null || !checkedTileEntities.get(te)) && prot.checkTileEntity(te)) { + if ((checkedTileEntities.get(te) == null || !checkedTileEntities.get(te)) && prot.checkTileEntity(te)) { Utils.dropAsEntity(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, new ItemStack(te.getBlockType(), 1, te.getBlockMetadata())); //te.getBlockType().breakBlock(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, te.blockType, te.blockMetadata); te.getWorldObj().setBlock(te.xCoord, te.yCoord, te.zCoord, Blocks.air); @@ -343,14 +340,14 @@ private void onPlayerTick(TickEvent.PlayerTickEvent ev) { public void onPlayerAttackEntityEvent(AttackEntityEvent ev) { // TODO: More wilderness goes here TownBlock block = DatasourceProxy.getDatasource().getBlock(ev.target.dimension, ev.target.chunkCoordX, ev.target.chunkCoordZ); - if(block != null) { + if (block != null) { Resident res = DatasourceProxy.getDatasource().getOrMakeResident(ev.entityPlayer); Town town = block.getTown(); - if(!town.checkPermission(res, FlagType.attackEntities, ev.target.dimension, (int)ev.target.posX, (int)ev.target.posY, (int)ev.target.posZ)) { + if (!town.checkPermission(res, FlagType.attackEntities, ev.target.dimension, (int) ev.target.posX, (int) ev.target.posY, (int) ev.target.posZ)) { for (Protection prot : protections.values()) { if (prot.protectedEntities.contains(ev.target.getClass())) { ev.setCanceled(true); - res.protectionDenial(LocalizationProxy.getLocalization().getLocalization("mytown.protection.vanilla.animalCruelty"), Formatter.formatOwnersToString(town.getOwnersAtPosition(ev.target.dimension, (int)ev.target.posX, (int)ev.target.posY, (int)ev.target.posZ))); + res.protectionDenial(LocalizationProxy.getLocalization().getLocalization("mytown.protection.vanilla.animalCruelty"), Formatter.formatOwnersToString(town.getOwnersAtPosition(ev.target.dimension, (int) ev.target.posX, (int) ev.target.posY, (int) ev.target.posZ))); } } } @@ -363,15 +360,15 @@ public void onBlockPlacement(BlockEvent.PlaceEvent ev) { TownBlock tblock = DatasourceProxy.getDatasource().getBlock(ev.world.provider.dimensionId, ev.x >> 4, ev.z >> 4); Resident res = DatasourceProxy.getDatasource().getOrMakeResident(ev.player); - if(tblock == null) { - if(!Wild.getInstance().checkPermission(res, FlagType.placeBlocks)) { + if (tblock == null) { + if (!Wild.getInstance().checkPermission(res, FlagType.placeBlocks)) { res.sendMessage(FlagType.placeBlocks.getLocalizedProtectionDenial()); ev.setCanceled(true); } else { // If it has permission, then check nearby List nearbyTowns = Utils.getTownsInRange(ev.world.provider.dimensionId, ev.x, ev.z, Config.placeProtectionRange, Config.placeProtectionRange); - for(Town t : nearbyTowns) { - if(!t.checkPermission(res, FlagType.placeBlocks)) { + for (Town t : nearbyTowns) { + if (!t.checkPermission(res, FlagType.placeBlocks)) { res.protectionDenial(FlagType.placeBlocks.getLocalizedProtectionDenial(), Formatter.formatOwnerToString(t.getMayor())); ev.setCanceled(true); return; @@ -386,8 +383,8 @@ public void onBlockPlacement(BlockEvent.PlaceEvent ev) { } else { // If it has permission, then check nearby List nearbyTowns = Utils.getTownsInRange(ev.world.provider.dimensionId, ev.x, ev.z, Config.placeProtectionRange, Config.placeProtectionRange); - for(Town t : nearbyTowns) { - if(!t.checkPermission(res, FlagType.placeBlocks)) { + for (Town t : nearbyTowns) { + if (!t.checkPermission(res, FlagType.placeBlocks)) { res.protectionDenial(FlagType.placeBlocks.getLocalizedProtectionDenial(), Formatter.formatOwnerToString(t.getMayor())); ev.setCanceled(true); return; @@ -409,15 +406,15 @@ public void onMultiBlockPlacement(BlockEvent.MultiPlaceEvent ev) { TownBlock tblock = DatasourceProxy.getDatasource().getBlock(ev.world.provider.dimensionId, ev.x >> 4, ev.z >> 4); Resident res = DatasourceProxy.getDatasource().getOrMakeResident(ev.player); - if(tblock == null) { - if(!Wild.getInstance().checkPermission(res, FlagType.placeBlocks)) { + if (tblock == null) { + if (!Wild.getInstance().checkPermission(res, FlagType.placeBlocks)) { res.sendMessage(FlagType.placeBlocks.getLocalizedProtectionDenial()); ev.setCanceled(true); } else { // If it has permission, then check nearby List nearbyTowns = Utils.getTownsInRange(ev.world.provider.dimensionId, ev.x, ev.z, Config.placeProtectionRange, Config.placeProtectionRange); - for(Town t : nearbyTowns) { - if(!t.checkPermission(res, FlagType.placeBlocks)) { + for (Town t : nearbyTowns) { + if (!t.checkPermission(res, FlagType.placeBlocks)) { res.protectionDenial(FlagType.placeBlocks.getLocalizedProtectionDenial(), Formatter.formatOwnerToString(t.getMayor())); ev.setCanceled(true); return; @@ -432,8 +429,8 @@ public void onMultiBlockPlacement(BlockEvent.MultiPlaceEvent ev) { } else { // If it has permission, then check nearby List nearbyTowns = Utils.getTownsInRange(ev.world.provider.dimensionId, ev.x, ev.z, Config.placeProtectionRange, Config.placeProtectionRange); - for(Town t : nearbyTowns) { - if(!t.checkPermission(res, FlagType.placeBlocks)) { + for (Town t : nearbyTowns) { + if (!t.checkPermission(res, FlagType.placeBlocks)) { res.protectionDenial(FlagType.placeBlocks.getLocalizedProtectionDenial(), Formatter.formatOwnerToString(t.getMayor())); ev.setCanceled(true); return; @@ -451,14 +448,13 @@ public void onMultiBlockPlacement(BlockEvent.MultiPlaceEvent ev) { } - @SubscribeEvent public void onEntityInteract(EntityInteractEvent ev) { Resident res = DatasourceProxy.getDatasource().getOrMakeResident(ev.entityPlayer); ItemStack currStack = ev.entityPlayer.getHeldItem(); - if(currStack != null) { - for(Protection prot : protections.values()) { - if(prot.checkItemUsage(currStack, res, new BlockPos((int)ev.target.posX, (int)ev.target.posY, (int)ev.target.posZ, ev.entityPlayer.worldObj.provider.dimensionId))) { + if (currStack != null) { + for (Protection prot : protections.values()) { + if (prot.checkItemUsage(currStack, res, new BlockPos((int) ev.target.posX, (int) ev.target.posY, (int) ev.target.posZ, ev.entityPlayer.worldObj.provider.dimensionId))) { ev.setCanceled(true); return; } @@ -498,10 +494,10 @@ public void onPlayerInteract(PlayerInteractEvent ev) { ItemStack currentStack = ev.entityPlayer.inventory.getCurrentItem(); // Item usage check here - if(currentStack != null && !(currentStack.getItem() instanceof ItemBlock)) { + if (currentStack != null && !(currentStack.getItem() instanceof ItemBlock)) { //MyTown.instance.log.info("Item usage position: " + x + ", " + y + ", " + z); - for(Protection protection : protections.values()) { - if(protection.checkItemUsage(currentStack, res, new BlockPos(x, y, z, ev.world.provider.dimensionId))) { + for (Protection protection : protections.values()) { + if (protection.checkItemUsage(currentStack, res, new BlockPos(x, y, z, ev.world.provider.dimensionId))) { ev.setCanceled(true); return; } @@ -570,7 +566,7 @@ public void onPlayerBreaksBlock(BlockEvent.BreakEvent ev) { TownBlock block = DatasourceProxy.getDatasource().getBlock(ev.world.provider.dimensionId, ev.x >> 4, ev.z >> 4); Resident res = DatasourceProxy.getDatasource().getOrMakeResident(ev.getPlayer()); if (block == null) { - if(!Wild.getInstance().checkPermission(res, FlagType.breakBlocks)) { + if (!Wild.getInstance().checkPermission(res, FlagType.breakBlocks)) { res.sendMessage(FlagType.breakBlocks.getLocalizedProtectionDenial()); ev.setCanceled(true); } @@ -582,7 +578,7 @@ public void onPlayerBreaksBlock(BlockEvent.BreakEvent ev) { return; } - if(ev.block instanceof ITileEntityProvider) + if (ev.block instanceof ITileEntityProvider) removeFromWhitelist(((ITileEntityProvider) ev.block).createNewTileEntity(ev.world, ev.blockMetadata).getClass(), ev.world.provider.dimensionId, ev.x, ev.y, ev.z, town); } } @@ -607,7 +603,6 @@ public void onItemUse(PlayerUseItemEvent.Start ev) { */ - private int counter = 0; @SuppressWarnings("unchecked") diff --git a/src/main/java/mytown/protection/QuarryPlusProtection.java b/src/main/java/mytown/protection/QuarryPlusProtection.java index c4c66923..9a4c3a87 100644 --- a/src/main/java/mytown/protection/QuarryPlusProtection.java +++ b/src/main/java/mytown/protection/QuarryPlusProtection.java @@ -1,7 +1,6 @@ package mytown.protection; import com.esotericsoftware.reflectasm.FieldAccess; -import com.esotericsoftware.reflectasm.MethodAccess; import mytown.MyTown; import mytown.entities.Town; import mytown.entities.flag.FlagType; @@ -21,10 +20,11 @@ public class QuarryPlusProtection extends Protection { FieldAccess fAccessQuarry; Class clsQuarry; + @SuppressWarnings("unchecked") public QuarryPlusProtection() { try { - clsQuarry = (Class)Class.forName("com.yogpc.qp.TileQuarry"); + clsQuarry = (Class) Class.forName("com.yogpc.qp.TileQuarry"); fAccessQuarry = FieldAccess.get(clsQuarry); trackedTileEntities.add(clsQuarry); } catch (Exception e) { @@ -34,7 +34,7 @@ public QuarryPlusProtection() { @Override public boolean checkTileEntity(TileEntity te) { - if(clsQuarry.isAssignableFrom(te.getClass())) { + if (clsQuarry.isAssignableFrom(te.getClass())) { int xMin, xMax, zMin, zMax; xMin = fAccessQuarry.getInt(te, fAccessQuarry.getIndex("xMin")); xMax = fAccessQuarry.getInt(te, fAccessQuarry.getIndex("xMax")); @@ -43,10 +43,10 @@ public boolean checkTileEntity(TileEntity te) { List chunks = Utils.getChunksInBox(xMin, zMin, xMax, zMax); - for(ChunkPos chunk : chunks) { + for (ChunkPos chunk : chunks) { Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, chunk.getX(), chunk.getZ()); - if(town != null) { - if((Boolean)town.getValue(FlagType.breakBlocks) && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.breakBlocks)) { + if (town != null) { + if ((Boolean) town.getValue(FlagType.breakBlocks) && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.breakBlocks)) { town.notifyEveryone(FlagType.breakBlocks.getLocalizedTownNotification()); return true; } @@ -59,7 +59,7 @@ public boolean checkTileEntity(TileEntity te) { @Override public List getFlagTypeForTile(Class te) { List flags = new ArrayList(); - if(clsQuarry.isAssignableFrom(te)) + if (clsQuarry.isAssignableFrom(te)) flags.add(FlagType.breakBlocks); return flags; } diff --git a/src/main/java/mytown/protection/ThermalExpansionProtection.java b/src/main/java/mytown/protection/ThermalExpansionProtection.java index 3fe39167..40c5f9c5 100644 --- a/src/main/java/mytown/protection/ThermalExpansionProtection.java +++ b/src/main/java/mytown/protection/ThermalExpansionProtection.java @@ -1,9 +1,7 @@ package mytown.protection; import mytown.MyTown; -import mytown.entities.Plot; import mytown.entities.Town; -import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; import mytown.util.BlockPos; import mytown.util.Utils; @@ -29,8 +27,8 @@ public class ThermalExpansionProtection extends Protection { public ThermalExpansionProtection() { try { - clsTileActivator = (Class)Class.forName("thermalexpansion.block.device.TileActivator"); - clsTileBreaker = (Class)Class.forName("thermalexpansion.block.device.TileBreaker"); + clsTileActivator = (Class) Class.forName("thermalexpansion.block.device.TileActivator"); + clsTileBreaker = (Class) Class.forName("thermalexpansion.block.device.TileBreaker"); trackedTileEntities.add(clsTileActivator); trackedTileEntities.add(clsTileBreaker); @@ -44,7 +42,7 @@ public ThermalExpansionProtection() { @SuppressWarnings("unchecked") @Override public boolean checkTileEntity(TileEntity te) { - if(clsTileActivator.isAssignableFrom(te.getClass())) { + if (clsTileActivator.isAssignableFrom(te.getClass())) { //Get the position at which is pointing at @@ -73,14 +71,14 @@ public boolean checkTileEntity(TileEntity te) { break; } - IInventory inv = (IInventory)te; - for(int i = 0; i < inv.getSizeInventory(); i++) { + IInventory inv = (IInventory) te; + for (int i = 0; i < inv.getSizeInventory(); i++) { ItemStack stack = inv.getStackInSlot(i); if (stack != null) { if (stack.getItem() instanceof ItemBlock) { Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, x >> 4, z >> 4); if (town != null) { - boolean placeFlag= (Boolean)town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.placeBlocks); + boolean placeFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.placeBlocks); if (!placeFlag) { town.notifyEveryone(FlagType.placeBlocks.getLocalizedTownNotification()); return true; @@ -96,21 +94,21 @@ public boolean checkTileEntity(TileEntity te) { // The break flag Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, x >> 4, z >> 4); - if(town != null) { - boolean breakFlag = (Boolean)town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.breakBlocks); + if (town != null) { + boolean breakFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.breakBlocks); if (!breakFlag && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.breakBlocks)) { town.notifyEveryone(FlagType.breakBlocks.getLocalizedTownNotification()); return true; } else { // The activate flag - boolean activateFlag = (Boolean)town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.activateBlocks); + boolean activateFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.activateBlocks); if (!activateFlag && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.activateBlocks)) { town.notifyEveryone(FlagType.activateBlocks.getLocalizedTownNotification()); return true; } } } - } else if(clsTileBreaker.isAssignableFrom(te.getClass())) { + } else if (clsTileBreaker.isAssignableFrom(te.getClass())) { int x = te.xCoord; int y = te.yCoord; int z = te.zCoord; @@ -137,9 +135,9 @@ public boolean checkTileEntity(TileEntity te) { } Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, x >> 4, z >> 4); - if(town != null) { - boolean breakFlag = (Boolean)town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.breakBlocks); - if(!breakFlag && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.breakBlocks)) { + if (town != null) { + boolean breakFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.breakBlocks); + if (!breakFlag && !town.hasBlockWhitelist(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.breakBlocks)) { town.notifyEveryone(FlagType.breakBlocks.getLocalizedTownNotification()); return true; } @@ -151,12 +149,12 @@ public boolean checkTileEntity(TileEntity te) { @Override public List getFlagTypeForTile(Class te) { List list = new ArrayList(); - if(clsTileActivator.isAssignableFrom(te)) { + if (clsTileActivator.isAssignableFrom(te)) { list.add(FlagType.useItems); list.add(FlagType.activateBlocks); list.add(FlagType.placeBlocks); list.add(FlagType.breakBlocks); - } else if(clsTileBreaker.isAssignableFrom(te)) { + } else if (clsTileBreaker.isAssignableFrom(te)) { list.add(FlagType.breakBlocks); } return list; @@ -165,7 +163,7 @@ public List getFlagTypeForTile(Class te) { public static int getFacing(TileEntity te) { try { Method method = clsTileActivator.getMethod("getFacing"); - return (Integer)method.invoke(te); + return (Integer) method.invoke(te); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/mytown/protection/VanillaProtection.java b/src/main/java/mytown/protection/VanillaProtection.java index a9e06864..2aea62bd 100644 --- a/src/main/java/mytown/protection/VanillaProtection.java +++ b/src/main/java/mytown/protection/VanillaProtection.java @@ -2,17 +2,12 @@ import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import mytown.MyTown; -import mytown.api.events.TownEvent; -import mytown.entities.Plot; import mytown.entities.Resident; import mytown.entities.Town; -import mytown.entities.flag.Flag; import mytown.entities.flag.FlagType; import mytown.util.BlockPos; import mytown.util.Utils; import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.entity.boss.EntityWither; import net.minecraft.entity.item.EntityMinecartTNT; @@ -23,15 +18,12 @@ import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.entity.projectile.EntityWitherSkull; import net.minecraft.init.Blocks; -import net.minecraft.init.Items; import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityPiston; -import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.MovingObjectPosition; import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.entity.player.FillBucketEvent; import net.minecraftforge.event.entity.player.PlayerOpenContainerEvent; @@ -102,11 +94,10 @@ public VanillaProtection() { @Override public boolean checkEntity(Entity entity) { // This is first since I don't want any premature return statements - if(super.checkEntity(entity)) + if (super.checkEntity(entity)) return true; - // Town only checks here return false; @@ -115,10 +106,10 @@ public boolean checkEntity(Entity entity) { @SuppressWarnings("unchecked") @Override public boolean checkTileEntity(TileEntity te) { - if(te instanceof TileEntityPiston) { + if (te instanceof TileEntityPiston) { Town town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, te.xCoord >> 4, te.zCoord >> 4); if (town != null) { - boolean placeFlag = (Boolean)town.getValueAtCoords(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.placeBlocks); + boolean placeFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, te.xCoord, te.yCoord, te.zCoord, FlagType.placeBlocks); if (!placeFlag) { return true; } @@ -147,7 +138,7 @@ public boolean checkTileEntity(TileEntity te) { } town = Utils.getTownAtPosition(te.getWorldObj().provider.dimensionId, x >> 4, z >> 4); if (town != null) { - boolean placeFlag = (Boolean)town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.placeBlocks); + boolean placeFlag = (Boolean) town.getValueAtCoords(te.getWorldObj().provider.dimensionId, x, y, z, FlagType.placeBlocks); if (!placeFlag) { town.notifyEveryone(FlagType.placeBlocks.getLocalizedTownNotification()); return true; @@ -162,10 +153,10 @@ public boolean checkTileEntity(TileEntity te) { @SuppressWarnings("unchecked") @Override public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { - if(itemStack.getItem() instanceof ItemBucket) { - if(res != null) { + if (itemStack.getItem() instanceof ItemBucket) { + if (res != null) { MovingObjectPosition pos = Utils.getMovingObjectPositionFromPlayer(res.getPlayer().worldObj, res.getPlayer(), false); - if(pos != null) { + if (pos != null) { //TODO: Properly check for fluid pickup if (pos.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { int x = pos.blockX; @@ -195,7 +186,7 @@ public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { Town town = Utils.getTownAtPosition(res.getPlayer().dimension, x >> 4, z >> 4); if (town != null) { - boolean itemUsage = (Boolean)town.getValueAtCoords(res.getPlayer().dimension, x, y, z, FlagType.useItems); + boolean itemUsage = (Boolean) town.getValueAtCoords(res.getPlayer().dimension, x, y, z, FlagType.useItems); if (!itemUsage && !town.checkPermission(res, FlagType.useItems, res.getPlayer().dimension, x, y, z)) { res.sendMessage(FlagType.useItems.getLocalizedProtectionDenial()); return true; @@ -234,7 +225,7 @@ public boolean checkItemUsage(ItemStack itemStack, Resident res, BlockPos bp) { Town town = Utils.getTownAtPosition(bp.dim, x >> 4, z >> 4); if (town != null) { - boolean itemUsage = (Boolean)town.getValueAtCoords(bp.dim, x, y, z, FlagType.useItems); + boolean itemUsage = (Boolean) town.getValueAtCoords(bp.dim, x, y, z, FlagType.useItems); if (!itemUsage) { town.notifyEveryone(FlagType.useItems.getLocalizedTownNotification()); return true; @@ -265,9 +256,9 @@ public void onPlayerOpenContainer(PlayerOpenContainerEvent ev) { public void onBucketFill(FillBucketEvent ev) { Resident res = getDatasource().getOrMakeResident(ev.entityPlayer); Town town = Utils.getTownAtPosition(ev.world.provider.dimensionId, ev.target.blockX >> 4, ev.target.blockZ >> 4); - if(town != null) { - boolean itemFlag = (Boolean)town.getValueAtCoords(ev.world.provider.dimensionId, ev.target.blockX, ev.target.blockY, ev.target.blockZ, FlagType.useItems); - if(!itemFlag && !town.checkPermission(res, FlagType.useItems)) { + if (town != null) { + boolean itemFlag = (Boolean) town.getValueAtCoords(ev.world.provider.dimensionId, ev.target.blockX, ev.target.blockY, ev.target.blockZ, FlagType.useItems); + if (!itemFlag && !town.checkPermission(res, FlagType.useItems)) { ev.setCanceled(true); } } diff --git a/src/main/java/mytown/proxies/DatasourceProxy.java b/src/main/java/mytown/proxies/DatasourceProxy.java index a0ca411d..080f7535 100644 --- a/src/main/java/mytown/proxies/DatasourceProxy.java +++ b/src/main/java/mytown/proxies/DatasourceProxy.java @@ -62,7 +62,7 @@ public static boolean start(Configuration config) { return false; } - if(!datasource.checkAll()) { + if (!datasource.checkAll()) { log.error("Failed to check the Datasource!"); return false; } diff --git a/src/main/java/mytown/proxies/mod/ModProxies.java b/src/main/java/mytown/proxies/mod/ModProxies.java index e0d3e739..963374db 100644 --- a/src/main/java/mytown/proxies/mod/ModProxies.java +++ b/src/main/java/mytown/proxies/mod/ModProxies.java @@ -42,7 +42,7 @@ public static void load() { continue; } */ - if(p.getModID() != null) { + if (p.getModID() != null) { for (ModContainer mc : Loader.instance().getModList()) { if (mc.getModId().equals(p.getModID()) && (p.getModVersion() == null || mc.getVersion().startsWith(p.getModVersion()))) { MyTown.instance.log.info("Loading proxy and protection: " + p.getName() + (p.getModVersion() != null ? p.getModVersion() : "")); @@ -95,8 +95,8 @@ public static void removeProxy(ModProxy proxy) { * @return */ public static boolean isProxyLoaded(String mod_id) { - for(ModProxy proxy : proxies) { - if(proxy.getModID().equals(mod_id)) + for (ModProxy proxy : proxies) { + if (proxy.getModID().equals(mod_id)) return true; } return false; diff --git a/src/main/java/mytown/proxies/mod/ModProxy.java b/src/main/java/mytown/proxies/mod/ModProxy.java index e74d2208..6a2b5a99 100644 --- a/src/main/java/mytown/proxies/mod/ModProxy.java +++ b/src/main/java/mytown/proxies/mod/ModProxy.java @@ -24,8 +24,8 @@ public ModProxy(String name, String modid, Class protClass } - public boolean isLoaded = false; + /** * Returns the name of the ModProxy * @@ -50,7 +50,9 @@ public String getModID() { * * @return */ - public String getModVersion() { return this.version; } + public String getModVersion() { + return this.version; + } /** * Loads this {@link ModProxy}, its run during {@link FMLPostInitializationEvent}. diff --git a/src/main/java/mytown/proxies/plugin/BukkitCompat.java b/src/main/java/mytown/proxies/plugin/BukkitCompat.java index 30f5a040..dfbbb64c 100644 --- a/src/main/java/mytown/proxies/plugin/BukkitCompat.java +++ b/src/main/java/mytown/proxies/plugin/BukkitCompat.java @@ -3,7 +3,6 @@ import mytown.MyTown; import mytown.util.Utils; import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; import java.io.File; @@ -14,8 +13,9 @@ public class BukkitCompat { private static BukkitCompat instance; + public static BukkitCompat getInstance() { - if(instance == null) + if (instance == null) instance = new BukkitCompat(); return instance; } @@ -26,7 +26,7 @@ public boolean hasPlugin(String pluginID) { public void loadPEX(File sourceFile) { File pluginsFolder = new File("plugins/PermissionsEx.jar"); - if(pluginsFolder.exists()) + if (pluginsFolder.exists()) Utils.addURL(pluginsFolder); //Utils.injectBukkitBridge(sourceFile, pluginsFolder); else @@ -34,5 +34,7 @@ public void loadPEX(File sourceFile) { } - public boolean hasPEX() { return hasPlugin("PermissionEx"); } + public boolean hasPEX() { + return hasPlugin("PermissionEx"); + } } diff --git a/src/main/java/mytown/proxies/plugin/PEXCompat.java b/src/main/java/mytown/proxies/plugin/PEXCompat.java index f285b021..4c120bd1 100644 --- a/src/main/java/mytown/proxies/plugin/PEXCompat.java +++ b/src/main/java/mytown/proxies/plugin/PEXCompat.java @@ -10,17 +10,16 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntityCommandBlock; import net.minecraft.world.World; -import org.bukkit.Bukkit; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.RemoteConsoleCommandSender; import org.bukkit.entity.Player; import ru.tehkode.permissions.PermissionUser; -//import ru.tehkode.permissions.bukkit.PermissionsEx; import java.util.List; -import java.util.Set; + +//import ru.tehkode.permissions.bukkit.PermissionsEx; /** * Created by AfterWind on 10/29/2014. @@ -29,20 +28,20 @@ public class PEXCompat { private static PEXCompat instance; + public static PEXCompat getInstance() { - if(instance == null) { + if (instance == null) { instance = new PEXCompat(); } return instance; } public static boolean firstPermissionBreachPEX(String permission, ICommandSender sender) { - if(!(sender instanceof EntityPlayer)) + if (!(sender instanceof EntityPlayer)) return true; - - PermissionUser user = null; //ru.tehkode.permissions.bukkit.PermissionsEx.getUser(Bukkit.getPlayer(((EntityPlayer) sender).getUniqueID())); + PermissionUser user = null; //ru.tehkode.permissions.bukkit.PermissionsEx.getUser(Bukkit.getPlayer(((EntityPlayer) sender).getUniqueID())); try { Class c = Class.forName("ru.tehkode.permissions.bukkit.PermissionsEx"); @@ -52,7 +51,7 @@ public static boolean firstPermissionBreachPEX(String permission, ICommandSender } - if(user == null) + if (user == null) return false; MyTown.instance.log.info("Got user: " + user.getName()); @@ -77,7 +76,7 @@ public PEXCompat() { public boolean checkPermission(Resident res, String permission) { PermissionUser user = null;//PermissionsEx.getUser(Bukkit.getPlayer(res.getUUID())); - if(user == null) + if (user == null) return false; MyTown.instance.log.info("Got user: " + user.getName()); @@ -87,21 +86,21 @@ public boolean checkPermission(Resident res, String permission) { @SuppressWarnings("unchecked") private ICommandSender convertToForge(CommandSender sender) { - if(sender instanceof Player) { - Player player = (Player)sender; - for(EntityPlayer entityPlayer : (List)MinecraftServer.getServer().getConfigurationManager().playerEntityList) { - if(player.getUniqueId().equals(entityPlayer.getUniqueID())) { + if (sender instanceof Player) { + Player player = (Player) sender; + for (EntityPlayer entityPlayer : (List) MinecraftServer.getServer().getConfigurationManager().playerEntityList) { + if (player.getUniqueId().equals(entityPlayer.getUniqueID())) { return entityPlayer; } } - } else if(sender instanceof ConsoleCommandSender) { + } else if (sender instanceof ConsoleCommandSender) { return MinecraftServer.getServer(); - } else if(sender instanceof BlockCommandSender) { + } else if (sender instanceof BlockCommandSender) { BlockCommandSender block = (BlockCommandSender) sender; World world = getWorldFromName(block.getBlock().getWorld().getName()); - TileEntityCommandBlock commandBlock = (TileEntityCommandBlock)world.getTileEntity(block.getBlock().getX(), block.getBlock().getY(), block.getBlock().getZ()); + TileEntityCommandBlock commandBlock = (TileEntityCommandBlock) world.getTileEntity(block.getBlock().getX(), block.getBlock().getY(), block.getBlock().getZ()); return commandBlock.func_145993_a(); - } else if(sender instanceof RemoteConsoleCommandSender) { + } else if (sender instanceof RemoteConsoleCommandSender) { return RConConsoleSource.instance; } return null; @@ -109,8 +108,8 @@ private ICommandSender convertToForge(CommandSender sender) { private World getWorldFromName(String name) { MyTown.instance.log.info("Trying to find world with name: " + name); - for(World world : MinecraftServer.getServer().worldServers) - if(world.provider.getDimensionName().equals(name)) + for (World world : MinecraftServer.getServer().worldServers) + if (world.provider.getDimensionName().equals(name)) return world; return null; } diff --git a/src/main/java/mytown/util/BlockPos.java b/src/main/java/mytown/util/BlockPos.java index bce480b7..20dceeaa 100644 --- a/src/main/java/mytown/util/BlockPos.java +++ b/src/main/java/mytown/util/BlockPos.java @@ -1,7 +1,5 @@ package mytown.util; -import net.minecraft.block.Block; - /** * Created by AfterWind on 9/20/2014. * Helper class for storing position of a block @@ -11,6 +9,7 @@ public class BlockPos { public final int x; public final int y; public final int z; + public BlockPos(int x, int y, int z, int dim) { this.x = x; this.y = y; diff --git a/src/main/java/mytown/util/ChunkPos.java b/src/main/java/mytown/util/ChunkPos.java index 446d159c..bc41201d 100644 --- a/src/main/java/mytown/util/ChunkPos.java +++ b/src/main/java/mytown/util/ChunkPos.java @@ -7,11 +7,17 @@ public class ChunkPos { private final int x; private final int z; + public ChunkPos(int x, int z) { this.x = x; this.z = z; } - public int getX() { return x; } - public int getZ() { return z; } + public int getX() { + return x; + } + + public int getZ() { + return z; + } } diff --git a/src/main/java/mytown/util/Constants.java b/src/main/java/mytown/util/Constants.java index 945427b4..fd02403a 100644 --- a/src/main/java/mytown/util/Constants.java +++ b/src/main/java/mytown/util/Constants.java @@ -1,11 +1,7 @@ package mytown.util; -import net.minecraft.item.Item; import net.minecraft.util.EnumChatFormatting; -import java.util.List; -import java.util.Map; - public class Constants { public static final String VERSION = "@VERSION@"; public static final String MODID = "MyTown2"; diff --git a/src/main/java/mytown/util/Formatter.java b/src/main/java/mytown/util/Formatter.java index 47b17577..db40822b 100644 --- a/src/main/java/mytown/util/Formatter.java +++ b/src/main/java/mytown/util/Formatter.java @@ -59,7 +59,7 @@ public static String formatResidentInfo(Resident resident) { else towns += ", " + added; } - String format = EnumChatFormatting.WHITE + "Resident: %s" +EnumChatFormatting.WHITE + + String format = EnumChatFormatting.WHITE + "Resident: %s" + EnumChatFormatting.WHITE + "\nTowns: %s" + EnumChatFormatting.WHITE + "\nJoined: %s" + EnumChatFormatting.WHITE + "\nLast Online: %s" + EnumChatFormatting.WHITE; @@ -186,8 +186,8 @@ public static String formatRankToString(Rank rank) { */ public static String formatOwnersToString(List residentList) { String formattedList = null; - for(Resident res : residentList) { - if(res != null) { + for (Resident res : residentList) { + if (res != null) { if (formattedList == null) formattedList = "§6Owners: " + res.getPlayerName(); else @@ -207,7 +207,6 @@ public static String formatOwnerToString(Resident res) { } - public static String blockInfoFormat = " ---------- Block ----------\nTown: %1$s\nDimension: %2$s\nLocation: %3$s"; public static String nationInfoFormat = " ---------- %1$s ----------\nCapital: TODO"; @@ -219,10 +218,9 @@ public static String formatOwnerToString(Resident res) { public static String residentInfoFormat = " ---------- %1$s ----------"; public static String townInfoFormat = - EnumChatFormatting.GRAY + " -------- " + EnumChatFormatting.GREEN+" %1$s "+EnumChatFormatting.GREEN+" ("+EnumChatFormatting.WHITE+"R:%2$s"+EnumChatFormatting.GREEN+" |"+EnumChatFormatting.WHITE+" C:%3$s/%4$s "+EnumChatFormatting.GREEN+"| "+EnumChatFormatting.WHITE+"P:%5$s"+EnumChatFormatting.GREEN+")"+EnumChatFormatting.GRAY+" --------" + - "\n"+EnumChatFormatting.GRAY+"Residents: %6$s" + - "\n"+EnumChatFormatting.GRAY+"Ranks: %7$s"; - + EnumChatFormatting.GRAY + " -------- " + EnumChatFormatting.GREEN + " %1$s " + EnumChatFormatting.GREEN + " (" + EnumChatFormatting.WHITE + "R:%2$s" + EnumChatFormatting.GREEN + " |" + EnumChatFormatting.WHITE + " C:%3$s/%4$s " + EnumChatFormatting.GREEN + "| " + EnumChatFormatting.WHITE + "P:%5$s" + EnumChatFormatting.GREEN + ")" + EnumChatFormatting.GRAY + " --------" + + "\n" + EnumChatFormatting.GRAY + "Residents: %6$s" + + "\n" + EnumChatFormatting.GRAY + "Ranks: %7$s"; } diff --git a/src/main/java/mytown/util/Utils.java b/src/main/java/mytown/util/Utils.java index e02e2b4d..a5331836 100644 --- a/src/main/java/mytown/util/Utils.java +++ b/src/main/java/mytown/util/Utils.java @@ -2,10 +2,10 @@ import mytown.MyTown; import mytown.datasource.MyTownDatasource; -import mytown.entities.Resident; -import mytown.entities.TownBlock; import mytown.entities.BlockWhitelist; +import mytown.entities.Resident; import mytown.entities.Town; +import mytown.entities.TownBlock; import mytown.entities.flag.FlagType; import mytown.proxies.DatasourceProxy; import net.minecraft.entity.Entity; @@ -47,7 +47,7 @@ public class Utils { */ public static Town getTownAtPosition(int dim, int x, int z) { TownBlock block = getDatasource().getBlock(dim, x, z); - if(block == null) + if (block == null) return null; return block.getTown(); } @@ -101,9 +101,9 @@ public static List getNearbyTileEntity(TileEntity te, Class getNearbyTileEntity(TileEntity te, Class getChunksInBox(int minX, int minZ, int maxX, int maxZ) { List list = new ArrayList(); - for(int i = minX >> 4; i <= maxX >> 4; i++) { - for(int j = minZ >> 4; j <= maxZ >> 4; j++) { + for (int i = minX >> 4; i <= maxX >> 4; i++) { + for (int j = minZ >> 4; j <= maxZ >> 4; j++) { list.add(new ChunkPos(i, j)); } } @@ -142,10 +142,10 @@ public static List getChunksInBox(int minX, int minZ, int maxX, int ma */ public static boolean isBlockWhitelisted(int dim, int x, int y, int z, FlagType flagType) { Town town = getTownAtPosition(dim, x >> 4, z >> 4); - if(town == null) return false; + if (town == null) return false; BlockWhitelist bw = town.getBlockWhitelist(dim, x, y, z, flagType); - if(bw != null) { - if(bw.isDeleted) { + if (bw != null) { + if (bw.isDeleted) { getDatasource().deleteBlockWhitelist(bw, town); return false; } @@ -166,9 +166,9 @@ public static List getPositionNearby(BlockPos block) { int[] dx = {0, 1, 0, -1}; int[] dz = {1, 0, -1, 0}; - for(int i = 0; i < 4; i++) { + for (int i = 0; i < 4; i++) { Town town = getTownAtPosition(block.dim, (block.x + dx[i]) >> 4, (block.z + dz[i]) >> 4); - if(town != null) { + if (town != null) { list.add(new BlockPos(block.x + dx[i], block.y, block.z + dz[i], block.dim)); } } @@ -187,10 +187,10 @@ public static List getPositionNearby(BlockPos block) { */ public static List getTownsInRange(int dim, int x, int z, int rangeX, int rangeZ) { List list = new ArrayList(); - for(int i = x - rangeX; i <= x + rangeX; i++) { - for(int j = z - rangeZ; j <= z + rangeZ; j++) { + for (int i = x - rangeX; i <= x + rangeX; i++) { + for (int j = z - rangeZ; j <= z + rangeZ; j++) { Town town = getTownAtPosition(dim, i >> 4, j >> 4); - if(town != null) + if (town != null) list.add(town); } } @@ -206,8 +206,7 @@ public static List getTownsInRange(int dim, int x, int z, int rangeX, int * @param z * @param itemStack */ - public static void dropAsEntity(World world, int x, int y, int z, ItemStack itemStack) - { + public static void dropAsEntity(World world, int x, int y, int z, ItemStack itemStack) { if (itemStack == null) { return; } @@ -229,27 +228,25 @@ public static void dropAsEntity(World world, int x, int y, int z, ItemStack item * @param p_77621_3_ * @return */ - public static MovingObjectPosition getMovingObjectPositionFromPlayer(World p_77621_1_, EntityPlayer p_77621_2_, boolean p_77621_3_) - { + public static MovingObjectPosition getMovingObjectPositionFromPlayer(World p_77621_1_, EntityPlayer p_77621_2_, boolean p_77621_3_) { float f = 1.0F; float f1 = p_77621_2_.prevRotationPitch + (p_77621_2_.rotationPitch - p_77621_2_.prevRotationPitch) * f; float f2 = p_77621_2_.prevRotationYaw + (p_77621_2_.rotationYaw - p_77621_2_.prevRotationYaw) * f; - double d0 = p_77621_2_.prevPosX + (p_77621_2_.posX - p_77621_2_.prevPosX) * (double)f; - double d1 = p_77621_2_.prevPosY + (p_77621_2_.posY - p_77621_2_.prevPosY) * (double)f + (double)(p_77621_1_.isRemote ? p_77621_2_.getEyeHeight() - p_77621_2_.getDefaultEyeHeight() : p_77621_2_.getEyeHeight()); // isRemote check to revert changes to ray trace position due to adding the eye height clientside and player yOffset differences - double d2 = p_77621_2_.prevPosZ + (p_77621_2_.posZ - p_77621_2_.prevPosZ) * (double)f; + double d0 = p_77621_2_.prevPosX + (p_77621_2_.posX - p_77621_2_.prevPosX) * (double) f; + double d1 = p_77621_2_.prevPosY + (p_77621_2_.posY - p_77621_2_.prevPosY) * (double) f + (double) (p_77621_1_.isRemote ? p_77621_2_.getEyeHeight() - p_77621_2_.getDefaultEyeHeight() : p_77621_2_.getEyeHeight()); // isRemote check to revert changes to ray trace position due to adding the eye height clientside and player yOffset differences + double d2 = p_77621_2_.prevPosZ + (p_77621_2_.posZ - p_77621_2_.prevPosZ) * (double) f; Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); - float f4 = MathHelper.sin(-f2 * 0.017453292F - (float)Math.PI); + float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = 5.0D; - if (p_77621_2_ instanceof EntityPlayerMP) - { - d3 = ((EntityPlayerMP)p_77621_2_).theItemInWorldManager.getBlockReachDistance(); + if (p_77621_2_ instanceof EntityPlayerMP) { + d3 = ((EntityPlayerMP) p_77621_2_).theItemInWorldManager.getBlockReachDistance(); } - Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3); + Vec3 vec31 = vec3.addVector((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); return p_77621_1_.func_147447_a(vec3, vec31, p_77621_3_, !p_77621_3_, false); } @@ -277,7 +274,7 @@ public static void injectBukkitBridge(File self, File pluginFolder) { } InputStream stream = zip.getInputStream(entry); FileOutputStream outStream = new FileOutputStream(new File(pluginFolder, entry.getName())); - byte[] tmp = new byte[4*1024]; + byte[] tmp = new byte[4 * 1024]; int size = 0; while ((size = stream.read(tmp)) != -1) { outStream.write(tmp, 0, size); @@ -301,7 +298,7 @@ public static void addURL(File file) { method.setAccessible(true); method.invoke(sysloader, file.toURI().toURL()); ClassLoader.getSystemClassLoader().loadClass("ru.tehkode.permissions.bukkit.PermissionsEx"); - MyTown.instance.log.info("Added PEX to the classpath. ("+ file.toURI().toURL().toString() +")"); + MyTown.instance.log.info("Added PEX to the classpath. (" + file.toURI().toURL().toString() + ")"); } catch (Throwable t) { t.printStackTrace();