diff options
Diffstat (limited to 'EssentialsProtect/src/com')
17 files changed, 1508 insertions, 962 deletions
diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java index b35a1346b..afa98b568 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java @@ -2,8 +2,15 @@ package com.earth2me.essentials.protect; import com.earth2me.essentials.Essentials; import com.earth2me.essentials.IConf; +import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.User; import com.earth2me.essentials.Util; +import com.earth2me.essentials.protect.data.IProtectedBlock; +import com.earth2me.essentials.protect.data.ProtectedBlockMemory; +import com.earth2me.essentials.protect.data.ProtectedBlockMySQL; +import com.earth2me.essentials.protect.data.ProtectedBlockSQLite; +import java.beans.PropertyVetoException; +import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.logging.Level; @@ -16,119 +23,148 @@ import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; -public class EssentialsProtect extends JavaPlugin implements IConf +public class EssentialsProtect extends JavaPlugin implements IConf, IProtect { - private EssentialsProtectBlockListener blockListener = null; - private EssentialsProtectPlayerListener playerListener = null; - private EssentialsProtectEntityListener entityListener = null; - private EssentialsProtectWeatherListener weatherListener = null; - private EssentialsProtectServerListener serverListener = null; - public static final String AUTHORS = Essentials.AUTHORS; - private static final Logger logger = Logger.getLogger("Minecraft"); - public static Map<String, Boolean> genSettings = null; - public static Map<String, String> dataSettings = null; - public static Map<String, Boolean> guardSettings = null; - public static Map<String, Boolean> playerSettings = null; - public static List<Integer> usageList = null; - public static List<Integer> blackListPlace = null; - public static List<Integer> breakBlackList = null; - public static List<Integer> onPlaceAlert = null; - public static List<Integer> onUseAlert = null; - public static List<Integer> onBreakAlert = null; - - public EssentialsProtect() - { - } + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + + private final transient Map<ProtectConfig, Boolean> settingsBoolean = new EnumMap<ProtectConfig, Boolean>(ProtectConfig.class); + private final transient Map<ProtectConfig, String> settingsString = new EnumMap<ProtectConfig, String>(ProtectConfig.class); + private final transient Map<ProtectConfig, List<Integer>> settingsList = new EnumMap<ProtectConfig, List<Integer>>(ProtectConfig.class); + private transient IProtectedBlock storage = null; + public transient IEssentials ess = null; public void onEnable() { - PluginManager pm = this.getServer().getPluginManager(); - - playerListener = new EssentialsProtectPlayerListener(this); - blockListener = new EssentialsProtectBlockListener(this); - entityListener = new EssentialsProtectEntityListener(this); - weatherListener = new EssentialsProtectWeatherListener(this); - serverListener = new EssentialsProtectServerListener(this); - + ess = Essentials.getStatic(); + final PluginManager pm = this.getServer().getPluginManager(); + + final EssentialsProtectPlayerListener playerListener = new EssentialsProtectPlayerListener(this); pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.Low, this); - - //blocklistener + + final EssentialsProtectBlockListener blockListener = new EssentialsProtectBlockListener(this); pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Highest, this); pm.registerEvent(Type.BLOCK_FROMTO, blockListener, Priority.Highest, this); pm.registerEvent(Type.BLOCK_IGNITE, blockListener, Priority.Highest, this); pm.registerEvent(Type.BLOCK_BURN, blockListener, Priority.Highest, this); pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Highest, this); - - //entitylistener + + final EssentialsProtectEntityListener entityListener = new EssentialsProtectEntityListener(this); pm.registerEvent(Type.ENTITY_EXPLODE, entityListener, Priority.Highest, this); pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Highest, this); - pm.registerEvent(Type.ENTITY_TARGET, entityListener, Priority.Highest, this); pm.registerEvent(Type.CREATURE_SPAWN, entityListener, Priority.Highest, this); + pm.registerEvent(Type.ENTITY_TARGET, entityListener, Priority.Highest, this); - //weatherlistener - pm.registerEvent(Type.WEATHER_CHANGE, weatherListener, Priority.Highest, this); - pm.registerEvent(Type.THUNDER_CHANGE, weatherListener, Priority.Highest, this); + final EssentialsProtectWeatherListener weatherListener = new EssentialsProtectWeatherListener(this); pm.registerEvent(Type.LIGHTNING_STRIKE, weatherListener, Priority.Highest, this); - - //serverlistener - pm.registerEvent(Type.PLUGIN_ENABLE, serverListener, Priority.Highest, this); - + pm.registerEvent(Type.THUNDER_CHANGE, weatherListener, Priority.Highest, this); + pm.registerEvent(Type.WEATHER_CHANGE, weatherListener, Priority.Highest, this); + reloadConfig(); - Essentials.getStatic().addReloadListener(this); - if (!this.getDescription().getVersion().equals(Essentials.getStatic().getDescription().getVersion())) { - logger.log(Level.WARNING, Util.i18n("versionMismatchAll")); + ess.addReloadListener(this); + if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) + { + LOGGER.log(Level.WARNING, Util.i18n("versionMismatchAll")); } - logger.info(Util.format("loadinfo", this.getDescription().getName(), this.getDescription().getVersion(), Essentials.AUTHORS)); + LOGGER.info(Util.format("loadinfo", this.getDescription().getName(), this.getDescription().getVersion(), Essentials.AUTHORS)); } - public static boolean checkProtectionItems(List<Integer> itemList, int id) + @Override + public boolean checkProtectionItems(final ProtectConfig list, final int id) { - return !itemList.isEmpty() && itemList.contains(id); + final List<Integer> itemList = settingsList.get(list); + return itemList != null && !itemList.isEmpty() && itemList.contains(id); } @Override - public void onDisable() + public void alert(final User user, final String item, final String type) { - genSettings.clear(); - dataSettings.clear(); - - blockListener = null; - playerListener = null; - entityListener = null; - genSettings = null; - dataSettings = null; - guardSettings = null; - playerSettings = null; - usageList = null; - blackListPlace = null; - onPlaceAlert = null; - onUseAlert = null; - onBreakAlert = null; + final Location loc = user.getLocation(); + for (Player p : this.getServer().getOnlinePlayers()) + { + final User alertUser = ess.getUser(p); + if (alertUser.isAuthorized("essentials.protect.alerts")) + { + alertUser.sendMessage(Util.format("alertFormat", user.getName(), type, item, formatCoords(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()))); + } + } } - public void reloadConfig() + public static String formatCoords(final int x, final int y, final int z) { - dataSettings = Essentials.getStatic().getSettings().getEpDBSettings(); - genSettings = Essentials.getStatic().getSettings().getEpSettings(); - guardSettings = Essentials.getStatic().getSettings().getEpGuardSettings(); - usageList = Essentials.getStatic().getSettings().epBlackListUsage(); - blackListPlace = Essentials.getStatic().getSettings().epBlackListPlacement(); - breakBlackList = Essentials.getStatic().getSettings().epBlockBreakingBlacklist(); - onPlaceAlert = Essentials.getStatic().getSettings().getEpAlertOnPlacement(); - onUseAlert = Essentials.getStatic().getSettings().getEpAlertOnUse(); - onBreakAlert = Essentials.getStatic().getSettings().getEpAlertOnBreak(); - playerSettings = Essentials.getStatic().getSettings().getEpPlayerSettings(); - EssentialsProtectData.createSqlTable(); + return x + "," + y + "," + z; } - public void alert(User user, String item, String type) + public void reloadConfig() { - Location loc = user.getLocation(); - for (Player p : this.getServer().getOnlinePlayers()) + for (ProtectConfig protectConfig : ProtectConfig.values()) { - User alertUser = Essentials.getStatic().getUser(p); - if (alertUser.isAuthorized("essentials.protect.alerts")) - alertUser.sendMessage(Util.format("alertFormat", user.getName(), type, item, EssentialsProtectData.formatCoords(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()))); + if (protectConfig.isList()) { + settingsList.put(protectConfig, ess.getSettings().getProtectList(protectConfig.getConfigName())); + } else if (protectConfig.isString()) { + settingsString.put(protectConfig, ess.getSettings().getProtectString(protectConfig.getConfigName())); + } else { + settingsBoolean.put(protectConfig, ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), protectConfig.getDefaultValueBoolean())); + } + } + + if (getSettingString(ProtectConfig.datatype).equalsIgnoreCase("mysql")) + { + try + { + storage = new ProtectedBlockMySQL( + getSettingString(ProtectConfig.mysqlDB), + getSettingString(ProtectConfig.dbUsername), + getSettingString(ProtectConfig.dbPassword)); + } + catch (PropertyVetoException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + else + { + try + { + storage = new ProtectedBlockSQLite("jdbc:sqlite:plugins/Essentials/EssentialsProtect.db"); + } + catch (PropertyVetoException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (getSettingBool(ProtectConfig.memstore)) + { + storage = new ProtectedBlockMemory(storage, this); + } + } + + @Override + public IProtectedBlock getStorage() + { + return storage; + } + + @Override + public boolean getSettingBool(final ProtectConfig protectConfig) + { + final Boolean bool = settingsBoolean.get(protectConfig); + return bool == null ? protectConfig.getDefaultValueBoolean() : bool; + } + + @Override + public String getSettingString(final ProtectConfig protectConfig) + { + final String str = settingsString.get(protectConfig); + return str == null ? protectConfig.getDefaultValueString() : str; + } + + public void onDisable() + { + } + + public IEssentials getEssentials() + { + return ess; } } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java index b32ac95a1..39e912fbe 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java @@ -1,8 +1,11 @@ package com.earth2me.essentials.protect; -import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.User; import com.earth2me.essentials.Util; +import com.earth2me.essentials.protect.data.IProtectedBlock; +import java.util.ArrayList; +import java.util.List; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; @@ -12,266 +15,296 @@ import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockListener; import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.inventory.ItemStack; public class EssentialsProtectBlockListener extends BlockListener { - private EssentialsProtect parent; - private int railBlockX; - private int railBlockY; - private int railBlockZ; - private EssentialsProtectData spData; + final private transient IProtect prot; + final private transient IEssentials ess; - public EssentialsProtectBlockListener(EssentialsProtect parent) + public EssentialsProtectBlockListener(final IProtect parent) { - this.parent = parent; - } - - private void initialize() - { - if (spData != null) return; - spData = new EssentialsProtectData(); + this.prot = parent; + this.ess = prot.getEssentials(); } @Override - public void onBlockPlace(BlockPlaceEvent event) + public void onBlockPlace(final BlockPlaceEvent event) { - if (event.isCancelled()) return; - initialize(); - ItemStack item = event.getItemInHand(); - User user = Essentials.getStatic().getUser(event.getPlayer()); + if (event.isCancelled()) + { + return; + } - if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) + final User user = ess.getUser(event.getPlayer()); + + if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild()) { - if(Essentials.getStatic().getSettings().warnOnBuildDisallow()) - { - user.sendMessage(Util.i18n("buildAlert")); - } event.setCancelled(true); return; } - Block blockPlaced = event.getBlockPlaced(); - int id = event.getBlockPlaced().getTypeId(); + final Block blockPlaced = event.getBlockPlaced(); + final int id = blockPlaced.getTypeId(); - if (EssentialsProtect.checkProtectionItems(EssentialsProtect.blackListPlace, id) && !user.isAuthorized("essentials.protect.exemptplacement")) + if (prot.checkProtectionItems(ProtectConfig.blacklist_placement, id) && !user.isAuthorized("essentials.protect.exemptplacement")) { event.setCancelled(true); return; } - if (EssentialsProtect.checkProtectionItems(EssentialsProtect.onPlaceAlert, id)) + if (prot.checkProtectionItems(ProtectConfig.alert_on_placement, id)) { - parent.alert(user, item.getType().toString(), Util.i18n("alertPlaced")); + prot.alert(user, blockPlaced.getType().toString(), Util.i18n("alertPlaced")); } - if (spData.isBlockAboveProtectedRail(blockPlaced.getFace(BlockFace.DOWN))) + final Block below = blockPlaced.getFace(BlockFace.DOWN); + if (below.getType() == Material.RAILS + && prot.getSettingBool(ProtectConfig.prevent_block_on_rail) + && prot.getStorage().isProtected(below, user.getName())) { - if (EssentialsProtect.genSettings.get("protect.protect.prevent-block-on-rails")) - { - event.setCancelled(true); - return; - } + event.setCancelled(true); + return; } - if (blockPlaced.getType() == Material.RAILS) + final List<Block> protect = new ArrayList<Block>(); + if (blockPlaced.getType() == Material.RAILS + && prot.getSettingBool(ProtectConfig.protect_rails) + && user.isAuthorized("essentials.protect")) { - if (EssentialsProtect.genSettings.get("protect.protect.rails")) + protect.add(blockPlaced); + if (prot.getSettingBool(ProtectConfig.protect_below_rails)) { - if (user.isAuthorized("essentials.protect")) - { - railBlockX = blockPlaced.getX(); - railBlockY = blockPlaced.getY(); - railBlockZ = blockPlaced.getZ(); - - spData.insertProtectionIntoDb(user.getWorld().getName(), user.getName(), railBlockX, railBlockY, railBlockZ); - if (EssentialsProtect.genSettings.get("protect.protect.block-below")) - { - spData.insertProtectionIntoDb(user.getWorld().getName(), user.getName(), railBlockX, railBlockY - 1, railBlockZ); - } - } + protect.add(blockPlaced.getFace(BlockFace.DOWN)); } } - if (blockPlaced.getType() == Material.SIGN_POST || blockPlaced.getType() == Material.WALL_SIGN) { - if (EssentialsProtect.genSettings.get("protect.protect.signs")) + if ((blockPlaced.getType() == Material.SIGN_POST || blockPlaced.getType() == Material.WALL_SIGN) + && prot.getSettingBool(ProtectConfig.protect_signs) + && user.isAuthorized("essentials.protect")) + { + protect.add(blockPlaced); + if (prot.getSettingBool(ProtectConfig.protect_against_signs)) { - if (user.isAuthorized("essentials.protect")) - { - int signBlockX = blockPlaced.getX(); - int signBlockY = blockPlaced.getY(); - int signBlockZ = blockPlaced.getZ(); - - initialize(); - spData.insertProtectionIntoDb(user.getWorld().getName(), user.getName(), signBlockX, - signBlockY, signBlockZ); - - if (EssentialsProtect.genSettings.get("protect.protect.block-below")) - { - signBlockX = event.getBlockAgainst().getX(); - signBlockY = event.getBlockAgainst().getY(); - signBlockZ = event.getBlockAgainst().getZ(); - spData.insertProtectionIntoDb(user.getWorld().getName(), user.getName(), signBlockX, - signBlockY, signBlockZ); - } - } + protect.add(event.getBlockAgainst()); } } + for (Block block : protect) + { + prot.getStorage().protectBlock(block, user.getName()); + } } @Override public void onBlockIgnite(BlockIgniteEvent event) { Block block = event.getBlock(); - if (block.getType() == Material.RAILS && EssentialsProtect.genSettings.get("protect.protect.rails")) + if (block.getType() == Material.RAILS + && prot.getSettingBool(ProtectConfig.protect_rails)) { event.setCancelled(true); return; } - if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) && EssentialsProtect.genSettings.get("protect.protect.signs")) + if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) + && prot.getSettingBool(ProtectConfig.protect_signs)) { event.setCancelled(true); return; } - - if (event.getBlock().getType() == Material.OBSIDIAN || - event.getBlock().getFace(BlockFace.DOWN).getType() == Material.OBSIDIAN) + if (event.getBlock().getType() == Material.OBSIDIAN + || event.getBlock().getFace(BlockFace.DOWN).getType() == Material.OBSIDIAN) { - event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.portal-creation")); + event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_portal_creation)); return; } - - if ((event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD))) + + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD)) { - event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.fire-spread")); + event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_fire_spread)); return; } if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL)) { - event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.flint-fire")); + event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_flint_fire)); return; } if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LAVA)) { - event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.lava-fire-spread")); + event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lava_fire_spread)); return; } - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LIGHTNING)) { - event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.lightning-fire-spread")); + event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lightning_fire_spread)); return; } } @Override - public void onBlockFromTo(BlockFromToEvent event) + public void onBlockFromTo(final BlockFromToEvent event) { - if (event.isCancelled()) return; - Block block = event.getBlock(); - Block toBlock = event.getToBlock(); - if (toBlock.getType() == Material.RAILS && EssentialsProtect.genSettings.get("protect.protect.rails")) + if (event.isCancelled()) + { + return; + } + final Block toBlock = event.getToBlock(); + if (toBlock.getType() == Material.RAILS + && prot.getSettingBool(ProtectConfig.protect_rails)) { event.setCancelled(true); return; } - if ((toBlock.getType() == Material.WALL_SIGN || toBlock.getType() == Material.SIGN_POST) && EssentialsProtect.genSettings.get("protect.protect.signs")) + if ((toBlock.getType() == Material.WALL_SIGN || toBlock.getType() == Material.SIGN_POST) + && prot.getSettingBool(ProtectConfig.protect_signs)) { event.setCancelled(true); return; } + + final Block block = event.getBlock(); if (block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER) { - event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.water-flow")); + event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_flow)); return; } if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA) { - event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.lava-flow")); + event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lava_flow)); return; } if (block.getType() == Material.AIR) { - event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.water-bucket-flow")); + event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_bucket_flow)); return; } } @Override - public void onBlockBurn(BlockBurnEvent event) + public void onBlockBurn(final BlockBurnEvent event) { - Block block = event.getBlock(); - if (block.getType() == Material.RAILS && EssentialsProtect.genSettings.get("protect.protect.rails")) + final Block block = event.getBlock(); + if (block.getType() == Material.RAILS && prot.getSettingBool(ProtectConfig.protect_rails)) { event.setCancelled(true); return; } - if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) && EssentialsProtect.genSettings.get("protect.protect.signs")) + if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) + && prot.getSettingBool(ProtectConfig.protect_signs)) { event.setCancelled(true); return; } - if (EssentialsProtect.guardSettings.get("protect.prevent.fire-spread")) + if (prot.getSettingBool(ProtectConfig.prevent_fire_spread)) { event.setCancelled(true); return; } } + private final static BlockFace[] faces = new BlockFace[] + { + BlockFace.NORTH, + BlockFace.EAST, + BlockFace.SOUTH, + BlockFace.WEST, + BlockFace.UP, + BlockFace.DOWN, + BlockFace.SELF + }; @Override - public void onBlockBreak(BlockBreakEvent event) + public void onBlockBreak(final BlockBreakEvent event) { - if (event.isCancelled()) return; - initialize(); - User user = Essentials.getStatic().getUser(event.getPlayer()); - Block block = event.getBlock(); - if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) + if (event.isCancelled()) + { + return; + } + final User user = ess.getUser(event.getPlayer()); + + if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild()) { event.setCancelled(true); return; } + final Block block = event.getBlock(); + final int typeId = block.getTypeId(); - if (EssentialsProtect.checkProtectionItems(EssentialsProtect.breakBlackList, block.getTypeId()) && !user.isAuthorized("essentials.protect.exemptbreak")) + if (prot.checkProtectionItems(ProtectConfig.blacklist_break, typeId) + && !user.isAuthorized("essentials.protect.exemptbreak")) { event.setCancelled(true); return; } + final Material type = block.getType(); - if (EssentialsProtect.checkProtectionItems(EssentialsProtect.onBreakAlert, block.getTypeId())) + if (prot.checkProtectionItems(ProtectConfig.alert_on_break, typeId)) { - parent.alert(user, block.getType().toString(), Util.i18n("alertBroke")); + prot.alert(user, type.toString(), Util.i18n("alertBroke")); } + final IProtectedBlock storage = prot.getStorage(); if (user.isAuthorized("essentials.protect.admin")) { - if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST || block.getType() == Material.RAILS) + if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS) { - spData.removeProtectionFromDB(block, true); + storage.unprotectBlock(block); + if (type == Material.RAILS || type == Material.SIGN_POST) + { + final Block below = block.getFace(BlockFace.DOWN); + storage.unprotectBlock(below); + } + else + { + for (BlockFace blockFace : faces) + { + final Block against = block.getFace(blockFace); + storage.unprotectBlock(against); + } + } } else { - spData.removeProtectionFromDB(block); - } + for (BlockFace blockFace : faces) + { + final Block against = block.getFace(blockFace); + storage.unprotectBlock(against); + } + } return; } else { - boolean canDestroy = spData.canDestroy(user.getWorld().getName(), user.getName(), block); - if (canDestroy) + + final boolean isProtected = storage.isProtected(block, user.getName()); + if (!isProtected) { - if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST || block.getType() == Material.RAILS) + if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS) { - spData.removeProtectionFromDB(block, true); + storage.unprotectBlock(block); + if (type == Material.RAILS || type == Material.SIGN_POST) + { + final Block below = block.getFace(BlockFace.DOWN); + storage.unprotectBlock(below); + } + else + { + for (BlockFace blockFace : faces) + { + final Block against = block.getFace(blockFace); + storage.unprotectBlock(against); + } + } } else { - spData.removeProtectionFromDB(block); + for (BlockFace blockFace : faces) + { + final Block against = block.getFace(blockFace); + storage.unprotectBlock(against); + } } - return; } event.setCancelled(true); return; diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectData.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectData.java deleted file mode 100644 index 76b36d810..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectData.java +++ /dev/null @@ -1,533 +0,0 @@ -package com.earth2me.essentials.protect; - -import com.earth2me.essentials.Essentials; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.block.Block; - - -public class EssentialsProtectData -{ - private static final Logger logger = Logger.getLogger("Minecraft"); - private static final String mysqlDriver = "com.mysql.jdbc.Driver"; - private static String mysqlUsername; - private static String mysqlPassword; - private static String mysqlDatabase; - private static String dataType; - private static final String sqlite = "jdbc:sqlite:plugins/Essentials/EssentialsProtect.db"; - private static final String mysqlTable; - private static final String sqliteTable; - private static final String insertQuery; - private static final String countByLocationQuery; - private static final String countByPlayerLocationQuery; - private static final String playerByLocationQuery; - private static final String deleteByLocationQuery; - - static - { - mysqlTable = EssentialsProtectSqlProperties.EssentialsProtect; - sqliteTable = EssentialsProtectSqlProperties.EssentialsProtect_sqlite; - insertQuery = EssentialsProtectSqlProperties.Insert; - countByLocationQuery = EssentialsProtectSqlProperties.CountByLocation; - countByPlayerLocationQuery = EssentialsProtectSqlProperties.CountByPLayerLocation; - playerByLocationQuery = EssentialsProtectSqlProperties.PlayerByLocation; - deleteByLocationQuery = EssentialsProtectSqlProperties.DeleteByLocation; - mysqlUsername = EssentialsProtect.dataSettings.get("protect.username"); - mysqlPassword = EssentialsProtect.dataSettings.get("protect.password"); - mysqlDatabase = EssentialsProtect.dataSettings.get("protect.mysqlDb"); - dataType = EssentialsProtect.dataSettings.get("protect.datatype"); - } - - public EssentialsProtectData() - { - } - - public static String formatCoords(int x, int y, int z) - { - return x + "," + y + "," + z; - } - - public void insertProtectionIntoDb(String worldname, String playerName, int x, int y, int z) - { - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; - try - { - if (dataType.contentEquals("mysql")) - { - Class.forName(mysqlDriver); - conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); - } - else - { - Class.forName("org.sqlite.JDBC"); - conn = DriverManager.getConnection(sqlite); - } - ps = conn.prepareStatement(insertQuery); - ps.setString(1, worldname); - ps.setString(2, playerName); - ps.setInt(3, x); - ps.setInt(4, y); - ps.setInt(5, z); - ps.executeUpdate(); - - } - catch (SQLException ex) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unable to add protection into SQL", ex); - } - catch (ClassNotFoundException e) - { - // TODO Auto-generated catch block - logger.log(Level.SEVERE, "[EssentialsProtect] Class not found", e); - } - finally - { - try - { - if (ps != null) - { - ps.close(); - } - if (rs != null) - { - rs.close(); - } - if (conn != null) - { - conn.close(); - } - } - catch (SQLException ex) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Could not close connection to SQL", ex); - } - } - } - - public boolean canDestroy(String worldName, String playerName, Block block) - { - int x = block.getX(); - int y = block.getY(); - int z = block.getZ(); - - int rowCount = 0; - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; - try - { - if (dataType.contentEquals("mysql")) - { - Class.forName(mysqlDriver); - conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); - } - else - { - Class.forName("org.sqlite.JDBC"); - conn = DriverManager.getConnection(sqlite); - } - conn.setAutoCommit(false); - ps = conn.prepareStatement(countByLocationQuery); - ps.setString(1, worldName); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - rs = ps.executeQuery(); - rs.next(); - rowCount = rs.getInt(1); - rs.close(); - ps.close(); - - if (rowCount == 0) - { - return true; - } - else - { - ps = conn.prepareStatement(countByPlayerLocationQuery); - ps.setString(1, worldName); - ps.setString(2, playerName); - ps.setInt(3, x); - ps.setInt(4, y); - ps.setInt(5, z); - rs = ps.executeQuery(); - rs.next(); - rowCount = rs.getInt(1); - - if (rowCount == 0) - { - return false; - } - - } - - } - catch (SQLException ex) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unable to query Protection", ex); - } - catch (Throwable e) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unable to query Protection", e); - } - finally - { - try - { - if (ps != null) - { - ps.close(); - } - if (rs != null) - { - rs.close(); - } - if (conn != null) - { - conn.close(); - } - } - catch (SQLException ex) - { - logger.log(Level.SEVERE, "[EssentialsProtection] Could not close connection to SQL", ex); - } - } - return true; - } - - @SuppressWarnings("CallToThreadDumpStack") - public static void createSqlTable() - { - Connection conn = null; - Statement st = null; - - try - { - if (dataType.contentEquals("mysql")) - { - Class.forName(mysqlDriver); - conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); - } - else - { - Class.forName("org.sqlite.JDBC"); - conn = DriverManager.getConnection(sqlite); - } - - st = conn.createStatement(); - st.executeUpdate(dataType.contentEquals("mysql") ? mysqlTable : sqliteTable); - } - catch (SQLException s) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Could not create table for " + dataType, s); - - } - catch (ClassNotFoundException ex) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Could not find driver for " + dataType, ex); - - } - catch (Throwable e) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unexpected error occured whilst creating table ", e); - } - finally - { - try - { - if (conn != null && !conn.isClosed()) - { - try - { - conn.close(); - } - catch (SQLException e) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unexpected error occured whilst closing the connection", e); - } - } - } - catch (SQLException e) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - public String getBlockOwner(String worldName, String playerName, Block block) - { - String returnPlayerName = null; - int x = block.getX(); - int y = block.getY(); - int z = block.getZ(); - - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; - try - { - if (dataType.contentEquals("mysql")) - { - Class.forName(mysqlDriver); - conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); - } - else - { - Class.forName("org.sqlite.JDBC"); - conn = DriverManager.getConnection(sqlite); - } - conn.setAutoCommit(false); - ps = conn.prepareStatement(playerByLocationQuery); - - ps.setString(1, worldName); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - rs = ps.executeQuery(); - while (rs.next()) - { - returnPlayerName = rs.getString("playerName"); - } - rs.close(); - ps.close(); - - } - catch (SQLException ex) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unable to query EssentialsProtection", ex); - } - catch (Throwable e) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unable to query EssentialsProtection", e); - } - finally - { - try - { - if (ps != null) - { - ps.close(); - } - if (rs != null) - { - rs.close(); - } - if (conn != null) - { - conn.close(); - } - } - catch (SQLException ex) - { - logger.log(Level.SEVERE, "[EssentialsProtection] Could not close connection to SQL", ex); - } - - } - return returnPlayerName; - } - - - public void removeProtectionFromDB(Block block) - { - try - { - Connection conn = null; - if (dataType.contentEquals("mysql")) - { - Class.forName(mysqlDriver); - conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, - mysqlPassword); - } - else - { - Class.forName("org.sqlite.JDBC"); - conn = DriverManager.getConnection(sqlite); - } - PreparedStatement ps = null; - try - { - ps = conn.prepareStatement(deleteByLocationQuery); - ps.setString(1, block.getWorld().getName()); - ps.setInt(2, block.getX()); - ps.setInt(3, block.getY()); - ps.setInt(4, block.getZ()); - ps.executeUpdate(); - - } - catch (SQLException ex) - { - logger.log(Level.WARNING, - "[EssentialsProtect] Could not delete block data from database", - ex); - } - finally - { - if (conn != null && !conn.isClosed()) - { - conn.close(); - } - if (ps != null) - { - ps.close(); - } - } - - } - catch (Throwable e) - { - logger.log(Level.SEVERE, " [EssentialsProtect] Exception occured whilst trying to delete data from sql", e); - } - - } - - public void removeProtectionFromDB(Block block, boolean removeBelow) - { - try - { - Connection conn = null; - if (dataType.contentEquals("mysql")) - { - Class.forName(mysqlDriver); - conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); - } - else - { - Class.forName("org.sqlite.JDBC"); - conn = DriverManager.getConnection(sqlite); - } - PreparedStatement ps = null; - try - { - ps = conn.prepareStatement(deleteByLocationQuery); - ps.setString(1, block.getWorld().getName()); - ps.setInt(2, block.getX()); - ps.setInt(3, block.getY()); - ps.setInt(4, block.getZ()); - ps.executeUpdate(); - if (removeBelow) - { - ps = conn.prepareStatement(deleteByLocationQuery); - ps.setString(1, block.getWorld().getName()); - ps.setInt(2, block.getX()); - ps.setInt(3, block.getY() - 1); - ps.setInt(4, block.getZ()); - ps.executeUpdate(); - } - - } - catch (SQLException ex) - { - logger.log(Level.WARNING, "[EssentialsProtect] Could not delete block data from database", ex); - } - finally - { - if (conn != null && !conn.isClosed()) - { - conn.close(); - } - if (ps != null) - { - ps.close(); - } - } - - } - catch (Throwable e) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Exception occured whilst trying to delete data from sql", e); - } - - } - - public boolean isBlockAboveProtectedRail(Block block) - { - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; - if (block.getTypeId() == 66) - { - try - { - if (dataType.contentEquals("mysql")) - { - Class.forName(mysqlDriver); - conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); - } - else - { - Class.forName("org.sqlite.JDBC"); - conn = DriverManager.getConnection(sqlite); - } - int rowCount = 0; - conn.setAutoCommit(false); - ps = conn.prepareStatement(countByLocationQuery); - ps.setString(1, block.getWorld().getName()); - ps.setInt(2, block.getX()); - ps.setInt(3, block.getY()); - ps.setInt(4, block.getZ()); - rs = ps.executeQuery(); - rs.next(); - rowCount = rs.getInt(1); - rs.close(); - ps.close(); - - if (rowCount == 0) - { - - return false; - } - else - { - return true; - } - } - catch (SQLException s) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Could not query protection", s); - - } - catch (ClassNotFoundException ex) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Could not find driver for " + dataType, ex); - - } - catch (Throwable e) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unexpected error occured whilst creating table", e); - } - finally - { - try - { - if (conn != null && !conn.isClosed()) - { - try - { - conn.close(); - } - catch (SQLException e) - { - logger.log(Level.SEVERE, "[EssentialsProtect] Unexpected error occured whilst closing the connection", e); - } - - } - } - catch (SQLException e) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - return false; - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java index 89afc7cff..42a55c874 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java @@ -1,11 +1,10 @@ package com.earth2me.essentials.protect;
-import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.EssentialsBlockListener;
+import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.User;
-import java.util.ArrayList;
import java.util.HashSet;
-import java.util.List;
+import java.util.Set;
import net.minecraft.server.ChunkPosition;
import net.minecraft.server.Packet60Explosion;
import org.bukkit.Location;
@@ -18,7 +17,6 @@ import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
-import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
@@ -34,11 +32,13 @@ import org.bukkit.event.entity.EntityTargetEvent.TargetReason; public class EssentialsProtectEntityListener extends EntityListener
{
- private EssentialsProtect parent;
+ private final transient IProtect prot;
+ private final transient IEssentials ess;
- public EssentialsProtectEntityListener(EssentialsProtect parent)
+ public EssentialsProtectEntityListener(final IProtect prot)
{
- this.parent = parent;
+ this.prot = prot;
+ this.ess = prot.getEssentials();
}
@Override
@@ -48,30 +48,35 @@ public class EssentialsProtectEntityListener extends EntityListener {
return;
}
+ final Entity target = event.getEntity();
+ final User user = ess.getUser(target);
if (event instanceof EntityDamageByBlockEvent)
{
- DamageCause cause = event.getCause();
+ final DamageCause cause = event.getCause();
- if (EssentialsProtect.playerSettings.get("protect.disable.contactdmg") && cause == DamageCause.CONTACT
- && !(event.getEntity() instanceof Player
- && Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.contact")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
+ if (prot.getSettingBool(ProtectConfig.disable_contactdmg)
+ && cause == DamageCause.CONTACT
+ && !(target instanceof Player
+ && user.isAuthorized("essentials.protect.damage.contact")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
}
- if (EssentialsProtect.playerSettings.get("protect.disable.lavadmg") && cause == DamageCause.LAVA
- && !(event.getEntity() instanceof Player
- && Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.lava")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
+ if (prot.getSettingBool(ProtectConfig.disable_lavadmg)
+ && cause == DamageCause.LAVA
+ && !(target instanceof Player
+ && user.isAuthorized("essentials.protect.damage.lava")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
}
- if (EssentialsProtect.guardSettings.get("protect.prevent.tnt-explosion") && cause == DamageCause.BLOCK_EXPLOSION
- && !(event.getEntity() instanceof Player
- && Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.tnt")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
+ if (prot.getSettingBool(ProtectConfig.prevent_tnt_explosion)
+ && cause == DamageCause.BLOCK_EXPLOSION
+ && !(target instanceof Player
+ && user.isAuthorized("essentials.protect.damage.tnt")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
@@ -80,97 +85,90 @@ public class EssentialsProtectEntityListener extends EntityListener if (event instanceof EntityDamageByEntityEvent)
{
- EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event;
- Entity eAttack = edEvent.getDamager();
- Entity eDefend = edEvent.getEntity();
+ final EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event;
+ final Entity eAttack = edEvent.getDamager();
+ final User attacker = ess.getUser(eAttack);
// PVP Settings
- if (eDefend instanceof Player && eAttack instanceof Player)
+ if (target instanceof Player && eAttack instanceof Player
+ && prot.getSettingBool(ProtectConfig.disable_pvp)
+ && (!user.isAuthorized("essentials.protect.pvp") || !attacker.isAuthorized("essentials.protect.pvp")))
{
- if (EssentialsProtect.playerSettings.get("protect.disable.pvp"))
- {
- User defender = Essentials.getStatic().getUser(eDefend);
- User attacker = Essentials.getStatic().getUser(eAttack);
-
- if (!defender.isAuthorized("essentials.protect.pvp") || !attacker.isAuthorized("essentials.protect.pvp"))
- {
- event.setCancelled(true);
- return;
- }
- }
+ event.setCancelled(true);
+ return;
}
+
//Creeper explode prevention
- if (eAttack != null && eAttack instanceof Monster)
+ if (eAttack instanceof Creeper && prot.getSettingBool(ProtectConfig.prevent_creeper_explosion)
+ && !(target instanceof Player
+ && user.isAuthorized("essentials.protect.damage.creeper")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
- if (eAttack instanceof Creeper && EssentialsProtect.guardSettings.get("protect.prevent.creeper-explosion")
- && !(event.getEntity() instanceof Player
- && Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.creeper")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
- {
- event.setCancelled(true);
- return;
- }
-
- if (eAttack instanceof Creeper && EssentialsProtect.guardSettings.get("protect.prevent.creeper-playerdamage")
- && !(event.getEntity() instanceof Player
- && Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.creeper")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
- {
- event.setCancelled(true);
- return;
- }
+ event.setCancelled(true);
+ return;
}
- }
- if (event instanceof EntityDamageByProjectileEvent)
- {
- if (event.getEntity() instanceof Player
- && EssentialsProtect.playerSettings.get("protect.disable.projectiles")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.projectiles")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable"))
+ if (eAttack instanceof Creeper && prot.getSettingBool(ProtectConfig.prevent_creeper_playerdmg)
+ && !(target instanceof Player
+ && user.isAuthorized("essentials.protect.damage.creeper")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
}
}
- DamageCause cause = event.getCause();
- Entity casualty = event.getEntity();
- if (casualty instanceof Player)
+ if (event instanceof EntityDamageByProjectileEvent
+ && target instanceof Player
+ && prot.getSettingBool(ProtectConfig.disable_projectiles)
+ && !(user.isAuthorized("essentials.protect.damage.projectiles")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
- if (EssentialsProtect.playerSettings.get("protect.disable.fall") && cause == DamageCause.FALL
- && !(Essentials.getStatic().getUser(casualty).isAuthorized("essentials.protect.damage.fall")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
+ event.setCancelled(true);
+ return;
+ }
+
+ final DamageCause cause = event.getCause();
+ if (target instanceof Player)
+ {
+ if (cause == DamageCause.FALL
+ && prot.getSettingBool(ProtectConfig.disable_fall)
+ && !(user.isAuthorized("essentials.protect.damage.fall")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
}
- if (EssentialsProtect.playerSettings.get("protect.disable.suffocate") && cause == DamageCause.SUFFOCATION
- && !(Essentials.getStatic().getUser(casualty).isAuthorized("essentials.protect.damage.suffocation")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
+ if (cause == DamageCause.SUFFOCATION
+ && prot.getSettingBool(ProtectConfig.disable_suffocate)
+ && !(user.isAuthorized("essentials.protect.damage.suffocation")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
}
- if (EssentialsProtect.playerSettings.get("protect.disable.firedmg") && (cause == DamageCause.FIRE
- || cause == DamageCause.FIRE_TICK)
- && !(Essentials.getStatic().getUser(casualty).isAuthorized("essentials.protect.damage.fire")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
+ if ((cause == DamageCause.FIRE
+ || cause == DamageCause.FIRE_TICK)
+ && prot.getSettingBool(ProtectConfig.disable_firedmg)
+ && !(user.isAuthorized("essentials.protect.damage.fire")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
}
- if (EssentialsProtect.playerSettings.get("protect.disable.drown") && cause == DamageCause.DROWNING
- && !(Essentials.getStatic().getUser(casualty).isAuthorized("essentials.protect.damage.drowning")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
+ if (cause == DamageCause.DROWNING
+ && prot.getSettingBool(ProtectConfig.disable_drown)
+ && !(user.isAuthorized("essentials.protect.damage.drowning")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
}
- if (EssentialsProtect.playerSettings.get("protect.disable.lightning") && cause == DamageCause.LIGHTNING
- && !(Essentials.getStatic().getUser(casualty).isAuthorized("essentials.protect.damage.lightning")
- && !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
+ if (cause == DamageCause.LIGHTNING
+ && prot.getSettingBool(ProtectConfig.disable_lightning)
+ && !(user.isAuthorized("essentials.protect.damage.lightning")
+ && !user.isAuthorized("essentials.protect.damage.disable")))
{
event.setCancelled(true);
return;
@@ -185,57 +183,56 @@ public class EssentialsProtectEntityListener extends EntityListener {
return;
}
- if (event.getEntity() instanceof LivingEntity)
+ final int maxHeight = ess.getSettings().getProtectCreeperMaxHeight();
+ //Nicccccccccce plaaacccccccccce..
+ if (event.getEntity() instanceof LivingEntity
+ && (prot.getSettingBool(ProtectConfig.prevent_creeper_explosion)
+ || prot.getSettingBool(ProtectConfig.prevent_creeper_blockdmg)
+ || (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight)))
{
- //Nicccccccccce plaaacccccccccce..
- int maxHeight = Essentials.getStatic().getSettings().getEpCreeperMaxHeight();
- if (EssentialsProtect.guardSettings.get("protect.prevent.creeper-explosion")
- || EssentialsProtect.guardSettings.get("protect.prevent.creeper-blockdamage")
- || (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight))
+ final Set<ChunkPosition> set = new HashSet<ChunkPosition>(event.blockList().size());
+ final Player[] players = ess.getServer().getOnlinePlayers();
+ final Set<ChunkPosition> blocksUnderPlayers = new HashSet<ChunkPosition>(players.length);
+ final Location loc = event.getLocation();
+ for (Player player : players)
{
- HashSet<ChunkPosition> set = new HashSet<ChunkPosition>(event.blockList().size());
- Player[] players = parent.getServer().getOnlinePlayers();
- List<ChunkPosition> blocksUnderPlayers = new ArrayList<ChunkPosition>(players.length);
- Location loc = event.getLocation();
- for (Player player : players)
+ if (player.getWorld().equals(loc.getWorld()))
{
- if (player.getWorld().equals(loc.getWorld()))
- {
- blocksUnderPlayers.add(
- new ChunkPosition(
- player.getLocation().getBlockX(),
- player.getLocation().getBlockY() - 1,
- player.getLocation().getBlockZ()));
- }
+ blocksUnderPlayers.add(
+ new ChunkPosition(
+ player.getLocation().getBlockX(),
+ player.getLocation().getBlockY() - 1,
+ player.getLocation().getBlockZ()));
}
- for (Block block : event.blockList())
+ }
+ ChunkPosition cp;
+ for (Block block : event.blockList())
+ {
+ cp = new ChunkPosition(block.getX(), block.getY(), block.getZ());
+ if (!blocksUnderPlayers.contains(cp))
{
- ChunkPosition cp = new ChunkPosition(block.getX(), block.getY(), block.getZ());
- if (!blocksUnderPlayers.contains(cp))
- {
- set.add(cp);
- }
+ set.add(cp);
}
-
- ((CraftServer)parent.getServer()).getHandle().a(loc.getX(), loc.getY(), loc.getZ(), 64.0D, ((CraftWorld)loc.getWorld()).getHandle().worldProvider.dimension,
- new Packet60Explosion(loc.getX(), loc.getY(), loc.getZ(), 3.0f, set));
- event.setCancelled(true);
- return;
}
+
+ ((CraftServer)ess.getServer()).getHandle().a(loc.getX(), loc.getY(), loc.getZ(), 64.0D, ((CraftWorld)loc.getWorld()).getHandle().worldProvider.dimension,
+ new Packet60Explosion(loc.getX(), loc.getY(), loc.getZ(), 3.0f, set));
+ event.setCancelled(true);
+ return;
}
- else
- { //OH NOES TNT
- if (EssentialsProtect.guardSettings.get("protect.prevent.tnt-explosion"))
- {
- event.setCancelled(true);
- return;
- }
+ else if (!(event.getEntity() instanceof LivingEntity)
+ && prot.getSettingBool(ProtectConfig.prevent_tnt_explosion))
+ {
+ event.setCancelled(true);
+ return;
}
// This code will prevent explosions near protected rails, signs or protected chests
// TODO: Use protect db instead of this code
+
for (Block block : event.blockList())
{
- if ((block.getType() == Material.RAILS || block.getFace(BlockFace.UP).getType() == Material.RAILS) && EssentialsProtect.genSettings.get("protect.protect.rails"))
+ if ((block.getType() == Material.RAILS || block.getFace(BlockFace.UP).getType() == Material.RAILS)
+ && prot.getSettingBool(ProtectConfig.protect_rails))
{
event.setCancelled(true);
return;
@@ -247,7 +244,7 @@ public class EssentialsProtectEntityListener extends EntityListener || block.getFace(BlockFace.WEST).getType() == Material.WALL_SIGN
|| block.getType() == Material.SIGN_POST
|| block.getFace(BlockFace.UP).getType() == Material.SIGN_POST)
- && EssentialsProtect.genSettings.get("protect.protect.signs"))
+ && prot.getSettingBool(ProtectConfig.protect_signs))
{
event.setCancelled(true);
return;
@@ -262,7 +259,7 @@ public class EssentialsProtectEntityListener extends EntityListener }
@Override
- public void onCreatureSpawn(CreatureSpawnEvent event)
+ public void onCreatureSpawn(final CreatureSpawnEvent event)
{
if (event.getEntity() instanceof CraftPlayer)
{
@@ -272,32 +269,32 @@ public class EssentialsProtectEntityListener extends EntityListener {
return;
}
- String creatureName = event.getCreatureType().toString().toLowerCase();
+ final String creatureName = event.getCreatureType().toString().toLowerCase();
if (creatureName == null || creatureName.isEmpty())
{
return;
}
- if (EssentialsProtect.guardSettings.get("protect.prevent.spawn." + creatureName))
+ if (ess.getSettings().getProtectPreventSpawn(creatureName))
{
event.setCancelled(true);
}
}
@Override
- public void onEntityTarget(EntityTargetEvent event)
+ public void onEntityTarget(final EntityTargetEvent event)
{
if (!(event.getTarget() instanceof Player))
{
return;
}
- User user = Essentials.getStatic().getUser(event.getTarget());
+ final User user = ess.getUser(event.getTarget());
if ((event.getReason() == TargetReason.CLOSEST_PLAYER
|| event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY
|| event.getReason() == TargetReason.PIG_ZOMBIE_TARGET
|| event.getReason() == TargetReason.RANDOM_TARGET
|| event.getReason() == TargetReason.TARGET_ATTACKED_OWNER
|| event.getReason() == TargetReason.OWNER_ATTACKED_TARGET)
- && EssentialsProtect.guardSettings.get("protect.prevent.entitytarget")
+ && prot.getSettingBool(ProtectConfig.prevent_entitytarget)
&& !user.isAuthorized("essentials.protect.entitytarget.bypass"))
{
event.setCancelled(true);
diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java index 9e1d35732..a2209a46a 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java @@ -1,43 +1,34 @@ package com.earth2me.essentials.protect; -import com.earth2me.essentials.Essentials; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.IEssentials; import org.bukkit.block.Block; -import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerListener; import org.bukkit.inventory.ItemStack; +import com.earth2me.essentials.User; +import com.earth2me.essentials.Util; +import org.bukkit.event.block.Action; public class EssentialsProtectPlayerListener extends PlayerListener { - private EssentialsProtect parent; - private EssentialsProtectData spData = null; + private final transient IProtect prot; + private final transient IEssentials ess; - public EssentialsProtectPlayerListener(EssentialsProtect parent) + public EssentialsProtectPlayerListener(final IProtect prot) { - this.parent = parent; - } - - public void initialize() - { - if (spData != null) return; - spData = new EssentialsProtectData(); + this.prot = prot; + this.ess = prot.getEssentials(); } @Override - public void onPlayerInteract(PlayerInteractEvent event) + public void onPlayerInteract(final PlayerInteractEvent event) { - initialize(); - if (event.isCancelled()) return; - ItemStack item = event.getItem(); - User user = Essentials.getStatic().getUser(event.getPlayer()); - Block blockClicked = event.getClickedBlock(); + final User user = ess.getUser(event.getPlayer()); - if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) + if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild()) { - if(Essentials.getStatic().getSettings().warnOnBuildDisallow()) + if (ess.getSettings().warnOnBuildDisallow()) { user.sendMessage(Util.i18n("buildAlert")); } @@ -45,25 +36,39 @@ public class EssentialsProtectPlayerListener extends PlayerListener return; } - - if (item != null && EssentialsProtect.checkProtectionItems(EssentialsProtect.usageList, item.getTypeId()) && !user.isAuthorized("essentials.protect.exemptusage")) + final ItemStack item = event.getItem(); + if (item != null + && prot.checkProtectionItems(ProtectConfig.blacklist_usage, item.getTypeId()) + && !user.isAuthorized("essentials.protect.exemptusage")) { event.setCancelled(true); return; } - if (event.getAction() == Action.RIGHT_CLICK_BLOCK && user.isAuthorized("essentials.protect.ownerinfo")) + if (user.isAuthorized("essentials.protect.ownerinfo") && event.getAction() == Action.RIGHT_CLICK_BLOCK) { - String ownerName = spData.getBlockOwner(user.getWorld().getName(), user.getName(), - blockClicked); - if (ownerName != null) + final StringBuilder stringBuilder = new StringBuilder(); + boolean first = true; + final Block blockClicked = event.getClickedBlock(); + for (String owner : prot.getStorage().getOwners(blockClicked)) + { + if (!first) + { + stringBuilder.append(", "); + } + first = false; + stringBuilder.append(owner); + } + final String ownerNames = stringBuilder.toString(); + if (ownerNames != null && !ownerNames.isEmpty()) { - user.sendMessage(Util.format("protectionOwner", ownerName)); + user.sendMessage(Util.format("protectionOwner", ownerNames)); } } - if (item != null && EssentialsProtect.checkProtectionItems(EssentialsProtect.onUseAlert, item.getTypeId())) + if (item != null + && prot.checkProtectionItems(ProtectConfig.alert_on_use, item.getTypeId())) { - parent.alert(user, item.getType().toString(), Util.i18n("alertUsed")); + prot.alert(user, item.getType().toString(), Util.i18n("alertUsed")); } } } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectRegions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectRegions.java deleted file mode 100644 index 6a640f3e1..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectRegions.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.earth2me.essentials.protect; - -public class EssentialsProtectRegions { - -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectServerListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectServerListener.java deleted file mode 100644 index 5642ef0dd..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectServerListener.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.earth2me.essentials.protect; - -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.event.server.PluginEnableEvent; -import org.bukkit.event.server.ServerListener; - - -public class EssentialsProtectServerListener extends ServerListener -{ - private EssentialsProtect parent; - Logger log = Logger.getLogger("minecraft"); - - public EssentialsProtectServerListener(EssentialsProtect parent) - { - this.parent = parent; - } - - @Override - public void onPluginEnable(PluginEnableEvent event) - { - if ("WorldGuard".equals(event.getPlugin().getDescription().getName())) - { - String[] features = new String[] {"disable water flow", "disable lava flow", "disable water bucket flow", "disable all fire spread", "disable tnt explosion", "disable creeper explosion", "disable all damage types"}; - log.log(Level.WARNING, "[EssentialsProtect] WorldGuard was detected, in the near future the following features of Protect will be disabled in favor of WorldGuard's versions"); - - for (String s : features) - { - log.log(Level.WARNING, s); - } - - } - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectSqlProperties.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectSqlProperties.java deleted file mode 100644 index 30b2a7032..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectSqlProperties.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.protect; - -public class EssentialsProtectSqlProperties { - - public static String EssentialsProtect="CREATE TABLE IF NOT EXISTS `EssentialsProtect` (`id` int(11) NOT NULL AUTO_INCREMENT, `worldName` varchar(150) NOT NULL, `playerName` varchar(150) NOT NULL, `x` int(11) NOT NULL, `y` int(11) NOT NULL, `z` int(11) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=205 DEFAULT CHARSET=latin1"; - public static String EssentialsProtect_sqlite = "CREATE TABLE IF NOT EXISTS EssentialsProtect (id INTEGER PRIMARY KEY, worldName TEXT ,playerName TEXT, x NUMERIC, y NUMERIC, z NUMERIC)"; - public static String CountByLocation="SELECT COUNT(*) from EssentialsProtect where worldName = ? and x = ? and y = ? and z = ? limit 10"; - public static String CountByPLayerLocation="SELECT COUNT(*) from EssentialsProtect where worldName = ? and playerName =? and x = ? and y = ? and z = ? limit 10"; - public static String DeleteByLocation="DELETE FROM EssentialsProtect WHERE worldName=? and x=? and y=? and z=?"; - public static String Insert="INSERT INTO EssentialsProtect (worldName, playerName, x, y, z) VALUES (?,?,?,?,?)"; - public static String PlayerByLocation="SELECT playerName FROM EssentialsProtect WHERE worldname = ? and x = ? and y = ? and z = ? LIMIT 10"; -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java index 901d3d8c7..e81efc72b 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java @@ -8,53 +8,43 @@ import org.bukkit.event.weather.WeatherListener; public class EssentialsProtectWeatherListener extends WeatherListener { - private EssentialsProtect parent; + private final transient IProtect prot; - public EssentialsProtectWeatherListener(EssentialsProtect parent) + public EssentialsProtectWeatherListener(final IProtect prot) { - this.parent = parent; + this.prot = prot; } @Override - public void onWeatherChange(WeatherChangeEvent event) + public void onWeatherChange(final WeatherChangeEvent event) { - if (event.isCancelled()) - { - return; - } - if (EssentialsProtect.playerSettings.get("protect.disable.weather.storm") && event.toWeatherState()) + if (!event.isCancelled() + && prot.getSettingBool(ProtectConfig.disable_weather_storm) + && event.toWeatherState()) { event.setCancelled(true); - return; } } @Override - public void onLightningStrike(LightningStrikeEvent event) + public void onLightningStrike(final LightningStrikeEvent event) { - if (event.isCancelled()) - { - return; - } - if (EssentialsProtect.playerSettings.get("protect.disable.weather.lightning")) + if (!event.isCancelled() + && prot.getSettingBool(ProtectConfig.disable_weather_lightning)) { event.setCancelled(true); - return; } } @Override - public void onThunderChange(ThunderChangeEvent event) + public void onThunderChange(final ThunderChangeEvent event) { - if (event.isCancelled()) - { - return; - } - if (EssentialsProtect.playerSettings.get("protect.disable.weather.thunder") && event.toThunderState()) + if (!event.isCancelled() + && prot.getSettingBool(ProtectConfig.disable_weather_thunder) + && event.toThunderState()) { event.setCancelled(true); - return; } } } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java new file mode 100644 index 000000000..ac095e33d --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.protect.data.IProtectedBlock; + + +public interface IProtect +{ + void alert(final User user, final String item, final String type); + + boolean checkProtectionItems(final ProtectConfig list, final int id); + + boolean getSettingBool(final ProtectConfig protectConfig); + + String getSettingString(final ProtectConfig protectConfig); + + IProtectedBlock getStorage(); + + IEssentials getEssentials(); +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java new file mode 100644 index 000000000..d9161bda8 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java @@ -0,0 +1,111 @@ +package com.earth2me.essentials.protect; + + +public enum ProtectConfig +{ + datatype("protect.datatype", "sqlite"), + mysqlDB("protect.mysqlDb", "jdbc:mysql://localhost:3306/minecraft"), + dbUsername("protect.username", "root"), + dbPassword("protect.password", ""), + memstore("protect.memstore", false), + disable_contactdmg("protect.disable.contactdmg", false), + disable_lavadmg("protect.disable.lavadmg", false), + disable_build("protect.disable.build", false), + disable_pvp("protect.disable.pvp", false), + disable_projectiles("protect.disable.projectiles", false), + disable_fall("protect.disable.fall", false), + disable_suffocate("protect.disable.suffocate", false), + disable_firedmg("protect.disable.firedmg", false), + disable_lightning("protect.disable.lightning", false), + disable_drown("protect.disable.drown", false), + disable_weather_storm("protect.disable.weather.storm", false), + disable_weather_lightning("protect.disable.weather.lightning", false), + disable_weather_thunder("protect.disable.weather.thunder", false), + prevent_fire_spread("protect.prevent.fire-spread", true), + prevent_flint_fire("protect.prevent.flint-fire", false), + prevent_lava_fire_spread("protect.prevent.lava-fire-spread", true), + prevent_lightning_fire_spread("protect.prevent.lightning-fire-spread", true), + prevent_water_flow("protect.prevent.water-flow", false), + prevent_lava_flow("protect.prevent.lava-flow", false), + prevent_water_bucket_flow("protect.prevent.water-bucket-flow", false), + prevent_portal_creation("protect.prevent.portal-creation", false), + prevent_block_on_rail("protect.protect.prevent-block-on-rails", false), + prevent_tnt_explosion("protect.prevent.tnt-explosion", false), + prevent_creeper_explosion("protect.prevent.creeper-explosion", true), + prevent_creeper_playerdmg("protect.prevent.creeper-playerdamage", false), + prevent_creeper_blockdmg("protect.prevent.creeper-blockdamage", false), + prevent_entitytarget("protect.prevent.entitytarget", false), + protect_rails("protect.protect.rails", true), + protect_below_rails("protect.protect.block-below", true), + protect_signs("protect.protect.signs", true), + protect_against_signs("protect.protect.block-below", true), + alert_on_placement("protect.alert.on-placement"), + alert_on_use("protect.alert.on-use"), + alert_on_break("protect.alert.on-break"), + blacklist_placement("protect.blacklist.placement"), + blacklist_usage("protect.blacklist.usage"), + blacklist_break("protect.blacklist.break"); + private final String configName; + private final String defValueString; + private final boolean defValueBoolean; + private final boolean isList; + private final boolean isString; + + private ProtectConfig(final String configName) + { + this(configName, null, false, true, false); + } + + private ProtectConfig(final String configName, final String defValueString) + { + this(configName, defValueString, false, false, true); + } + + private ProtectConfig(final String configName, final boolean defValueBoolean) + { + this(configName, null, defValueBoolean, false, false); + } + + private ProtectConfig(final String configName, final String defValueString, final boolean defValueBoolean, final boolean isList, final boolean isString) + { + this.configName = configName; + this.defValueString = defValueString; + this.defValueBoolean = defValueBoolean; + this.isList = isList; + this.isString = isString; + } + + /** + * @return the configName + */ + public String getConfigName() + { + return configName; + } + + /** + * @return the default value String + */ + public String getDefaultValueString() + { + return defValueString; + } + + /** + * @return the default value boolean + */ + public boolean getDefaultValueBoolean() + { + return defValueBoolean; + } + + public boolean isString() + { + return isString; + } + + public boolean isList() + { + return isList; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java new file mode 100644 index 000000000..6580ce7f8 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java @@ -0,0 +1,14 @@ +package com.earth2me.essentials.protect.data; + +import java.util.List; +import org.bukkit.block.Block; + +public interface IProtectedBlock { + public void clearProtections(); + public void importProtections(List<OwnedBlock> blocks); + public List<OwnedBlock> exportProtections(); + public void protectBlock(Block block, String playerName); + public boolean isProtected(Block block, String playerName); + public List<String> getOwners(Block block); + public int unprotectBlock(Block block); +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java new file mode 100644 index 000000000..dea124b58 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java @@ -0,0 +1,18 @@ +package com.earth2me.essentials.protect.data; + +public class OwnedBlock { + final int x; + final int y; + final int z; + final String world; + final String playerName; + + public OwnedBlock(int x, int y, int z, String world, String playerName) + { + this.x = x; + this.y = y; + this.z = z; + this.world = world; + this.playerName = playerName; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java new file mode 100644 index 000000000..e6b3c7592 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java @@ -0,0 +1,421 @@ +package com.earth2me.essentials.protect.data; + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.block.Block; + + +public abstract class ProtectedBlockJDBC implements IProtectedBlock +{ + protected static final Logger LOGGER = Logger.getLogger("Minecraft"); + protected final transient ComboPooledDataSource cpds; + + protected abstract PreparedStatement getStatementCreateTable(Connection conn) throws SQLException; + + protected abstract PreparedStatement getStatementUpdateFrom2_0Table(Connection conn) throws SQLException; + + protected abstract PreparedStatement getStatementDeleteAll(Connection conn) throws SQLException; + + protected abstract PreparedStatement getStatementInsert(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException; + + protected abstract PreparedStatement getStatementPlayerCountByLocation(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException; + + protected abstract PreparedStatement getStatementPlayersByLocation(Connection conn, String name, int x, int y, int z) throws SQLException; + + protected abstract PreparedStatement getStatementDeleteByLocation(Connection conn, String world, int x, int y, int z) throws SQLException; + + protected abstract PreparedStatement getStatementAllBlocks(Connection conn) throws SQLException; + + public ProtectedBlockJDBC(String driver, String url) throws PropertyVetoException + { + this(driver, url, null, null); + } + + public ProtectedBlockJDBC(String driver, String url, String username, String password) throws PropertyVetoException + { + cpds = new ComboPooledDataSource(); + cpds.setDriverClass(driver); + cpds.setJdbcUrl(url); + if (username != null) + { + cpds.setUser(username); + cpds.setPassword(password); + } + cpds.setMaxStatements(20); + createAndConvertTable(); + } + + private void createAndConvertTable() + { + Connection conn = null; + PreparedStatement ps = null; + try + { + conn = cpds.getConnection(); + ps = getStatementCreateTable(conn); + ps.execute(); + ps.close(); + ps = getStatementUpdateFrom2_0Table(conn); + ps.execute(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + finally + { + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + public void clearProtections() + { + Connection conn = null; + PreparedStatement ps = null; + try + { + conn = cpds.getConnection(); + ps = getStatementDeleteAll(conn); + ps.executeUpdate(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + finally + { + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + public void importProtections(List<OwnedBlock> blocks) + { + for (OwnedBlock ownedBlock : blocks) + { + if (ownedBlock.playerName == null) + { + continue; + } + protectBlock(ownedBlock.world, ownedBlock.x, ownedBlock.y, ownedBlock.z, ownedBlock.playerName); + } + } + + public List<OwnedBlock> exportProtections() + { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + List<OwnedBlock> blocks = new ArrayList<OwnedBlock>(); + try + { + conn = cpds.getConnection(); + ps = getStatementAllBlocks(conn); + rs = ps.executeQuery(); + while (rs.next()) + { + OwnedBlock ob = new OwnedBlock( + rs.getInt(2), + rs.getInt(3), + rs.getInt(4), + rs.getString(1), + rs.getString(5)); + blocks.add(ob); + } + return blocks; + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + return blocks; + } + finally + { + if (rs != null) + { + try + { + rs.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + public void protectBlock(Block block, String playerName) + { + protectBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), playerName); + } + + private void protectBlock(String world, int x, int y, int z, String playerName) + { + Connection conn = null; + PreparedStatement ps = null; + try + { + conn = cpds.getConnection(); + ps = getStatementInsert(conn, world, x, y, z, playerName); + ps.executeUpdate(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + finally + { + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + public boolean isProtected(Block block, String playerName) + { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try + { + conn = cpds.getConnection(); + ps = getStatementPlayerCountByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), playerName); + rs = ps.executeQuery(); + return rs.next() && rs.getInt(1) > 0 && rs.getInt(2) == 0; + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + return true; + } + finally + { + if (rs != null) + { + try + { + rs.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + public List<String> getOwners(Block block) + { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + List<String> owners = new ArrayList<String>(); + try + { + conn = cpds.getConnection(); + ps = getStatementPlayersByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); + rs = ps.executeQuery(); + while (rs.next()) + { + owners.add(rs.getString(1)); + } + return owners; + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + return owners; + } + finally + { + if (rs != null) + { + try + { + rs.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + public int unprotectBlock(Block block) + { + Connection conn = null; + PreparedStatement ps = null; + try + { + conn = cpds.getConnection(); + ps = getStatementDeleteByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); + return ps.executeUpdate(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + return 0; + } + finally + { + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java new file mode 100644 index 000000000..2fd32b026 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java @@ -0,0 +1,248 @@ +package com.earth2me.essentials.protect.data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.plugin.Plugin; + + +public class ProtectedBlockMemory implements IProtectedBlock +{ + private final transient List<String> worlds = new ArrayList<String>(); + private final transient List<String> playerNames = new ArrayList<String>(); + private final transient IProtectedBlock storage; + private final transient Plugin plugin; + + + static class ProtectedLocation + { + private final transient int x; + private final transient int y; + private final transient int z; + private final transient int w; + + public ProtectedLocation(final Block block, final int worldId) + { + this.x = block.getX(); + this.y = block.getY(); + this.z = block.getZ(); + this.w = worldId; + } + + public ProtectedLocation(final OwnedBlock ownedBlock, final int worldId) + { + this.x = ownedBlock.x; + this.y = ownedBlock.y; + this.z = ownedBlock.z; + this.w = worldId; + } + + @Override + public boolean equals(final Object object) + { + if (object instanceof ProtectedLocation) + { + final ProtectedLocation pLoc = (ProtectedLocation)object; + return x == pLoc.x && y == pLoc.y && z == pLoc.z && w == pLoc.w; + } + return false; + } + + @Override + public int hashCode() + { + return x ^ y ^ z ^ w; + } + } + + + static class ProtectedBy + { + private transient int playerId = -1; + private transient Set<Integer> playerIds; + + public void add(final int playerId) + { + if (this.playerId == -1 || this.playerId == playerId) + { + this.playerId = playerId; + } + else + { + if (playerIds == null) + { + playerIds = new HashSet<Integer>(4); + playerIds.add(this.playerId); + } + playerIds.add(playerId); + } + } + + public boolean contains(final int playerId) + { + if (playerIds == null) + { + return this.playerId == playerId; + } + return playerIds.contains(playerId); + } + + public List<String> getPlayers(final List<String> playerNames) + { + final List<String> list = new ArrayList<String>(2); + if (playerIds == null) + { + list.add(playerNames.get(playerId)); + } + else + { + for (Integer integer : playerIds) + { + list.add(playerNames.get(integer)); + } + } + return list; + } + + public int size() + { + if (playerIds == null) + { + return 1; + } + return playerIds.size(); + } + } + private final transient Map<ProtectedLocation, ProtectedBy> blocks = new HashMap<ProtectedLocation, ProtectedBy>(); + + public ProtectedBlockMemory(final IProtectedBlock storage, final Plugin plugin) + { + this.storage = storage; + this.plugin = plugin; + importProtections(storage.exportProtections()); + } + + public void clearProtections() + { + blocks.clear(); + } + + public final void importProtections(final List<OwnedBlock> blocks) + { + for (OwnedBlock ownedBlock : blocks) + { + final ProtectedLocation pl = new ProtectedLocation(ownedBlock, getWorldId(ownedBlock.world)); + if (ownedBlock.playerName == null) + { + continue; + } + protectBlock(pl, ownedBlock.playerName); + } + } + + public List<OwnedBlock> exportProtections() + { + final List<OwnedBlock> blockList = new ArrayList<OwnedBlock>(blocks.size()); + for (Entry<ProtectedLocation, ProtectedBy> entry : blocks.entrySet()) + { + for (String name : entry.getValue().getPlayers(playerNames)) + { + final OwnedBlock ob = new OwnedBlock( + entry.getKey().x, + entry.getKey().y, + entry.getKey().z, + worlds.get(entry.getKey().w), + name); + blockList.add(ob); + } + } + return blockList; + } + + public void protectBlock(final Block block, final String playerName) + { + final ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + protectBlock(pl, playerName); + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() + { + public void run() + { + storage.protectBlock(block, playerName); + } + }); + } + + private final void protectBlock(ProtectedLocation pl, String playerName) + { + int playerId = getPlayerId(playerName); + ProtectedBy pb = blocks.get(pl); + if (pb == null) + { + pb = new ProtectedBy(); + blocks.put(pl, pb); + } + pb.add(playerId); + } + + public boolean isProtected(Block block, String playerName) + { + int playerId = getPlayerId(playerName); + ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + ProtectedBy pb = blocks.get(pl); + return !pb.contains(playerId); + } + + public List<String> getOwners(Block block) + { + ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + ProtectedBy pb = blocks.get(pl); + return pb.getPlayers(playerNames); + } + + public int unprotectBlock(final Block block) + { + ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + ProtectedBy pb = blocks.remove(pl); + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() + { + public void run() + { + storage.unprotectBlock(block); + } + }); + return pb.size(); + } + + private int getPlayerId(String playername) + { + int id = playerNames.indexOf(playername); + if (id < 0) + { + playerNames.add(playername); + id = playerNames.indexOf(playername); + } + return id; + } + + private int getWorldId(World world) + { + return getWorldId(world.getName()); + } + + private int getWorldId(String name) + { + int id = worlds.indexOf(name); + if (id < 0) + { + worlds.add(name); + id = worlds.indexOf(name); + } + return id; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java new file mode 100644 index 000000000..8e50ce248 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java @@ -0,0 +1,140 @@ +package com.earth2me.essentials.protect.data; + +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ProtectedBlockMySQL extends ProtectedBlockJDBC { + + public ProtectedBlockMySQL(String url, String username, String password) throws PropertyVetoException { + super("com.mysql.jdbc.Driver", url, username, password); + } + + private static final String QueryCreateTable = + "CREATE TABLE IF NOT EXISTS `EssentialsProtect` (" + + "`worldName` varchar(60) NOT NULL," + + "`x` int(11) NOT NULL, `y` int(11) NOT NULL, `z` int(11) NOT NULL," + + "`playerName` varchar(150) DEFAULT NULL," + + "KEY `pos` (`worldName`,`x`,`z`,`y`)" + + ") ENGINE=MyISAM DEFAULT CHARSET=utf8"; + + @Override + protected PreparedStatement getStatementCreateTable(Connection conn) throws SQLException { + return conn.prepareStatement(QueryCreateTable); + } + + private static final String QueryUpdateFrom2_0TableCheck = + "SHOW COLUMNS FROM `EssentialsProtect` LIKE 'id';"; + private static final String QueryUpdateFrom2_0Table = + "ALTER TABLE `EssentialsProtect` " + + "CHARACTER SET = utf8, ENGINE = MyISAM," + + "DROP COLUMN `id`," + + "CHANGE COLUMN `playerName` `playerName` VARCHAR(150) NULL AFTER `z`," + + "CHANGE COLUMN `worldName` `worldName` VARCHAR(60) NOT NULL," + + "ADD INDEX `position` (`worldName` ASC, `x` ASC, `z` ASC, `y` ASC)," + + "DROP PRIMARY KEY ;"; + + @Override + protected PreparedStatement getStatementUpdateFrom2_0Table(Connection conn) throws SQLException { + PreparedStatement testPS = null; + ResultSet testRS = null; + try { + testPS = conn.prepareStatement(QueryUpdateFrom2_0TableCheck); + testRS = testPS.executeQuery(); + if (testRS.first()) { + return conn.prepareStatement(QueryUpdateFrom2_0Table); + } else { + return conn.prepareStatement("SELECT 1;"); + } + } finally { + if (testRS != null) { + try + { + testRS.close(); + } + catch (SQLException ex) + { + Logger.getLogger(ProtectedBlockMySQL.class.getName()).log(Level.SEVERE, null, ex); + } + } + if (testPS != null) { + try + { + testPS.close(); + } + catch (SQLException ex) + { + Logger.getLogger(ProtectedBlockMySQL.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + } + private static final String QueryDeleteAll = "DELETE FROM EssentialsProtect;"; + + @Override + protected PreparedStatement getStatementDeleteAll(Connection conn) throws SQLException { + return conn.prepareStatement(QueryDeleteAll); + } + private static final String QueryInsert = + "INSERT INTO EssentialsProtect (worldName, x, y, z, playerName) VALUES (?, ?, ?, ?, ?);"; + + @Override + protected PreparedStatement getStatementInsert(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryInsert); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + ps.setString(5, playerName); + return ps; + } + private static final String QueryCountByPlayer = + "SELECT COUNT(playerName), SUM(playerName = ?) FROM EssentialsProtect " + + "WHERE worldName = ? AND x = ? AND y = ? AND z = ? GROUP BY x;"; + + @Override + protected PreparedStatement getStatementPlayerCountByLocation(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryCountByPlayer); + ps.setString(1, playerName); + ps.setString(2, world); + ps.setInt(3, x); + ps.setInt(4, y); + ps.setInt(5, z); + return ps; + } + private static final String QueryPlayersByLocation = + "SELECT playerName FROM EssentialsProtect WHERE worldname = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementPlayersByLocation(Connection conn, String world, int x, int y, int z) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryPlayersByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryDeleteByLocation = + "DELETE FROM EssentialsProtect WHERE worldName = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementDeleteByLocation(Connection conn, String world, int x, int y, int z) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryDeleteByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryAllBlocks = + "SELECT worldName, x, y, z, playerName FROM EssentialsProtect;"; + + @Override + protected PreparedStatement getStatementAllBlocks(Connection conn) throws SQLException { + return conn.prepareStatement(QueryAllBlocks); + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java new file mode 100644 index 000000000..444c657eb --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java @@ -0,0 +1,96 @@ +package com.earth2me.essentials.protect.data; + +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class ProtectedBlockSQLite extends ProtectedBlockJDBC { + + public ProtectedBlockSQLite(String url) throws PropertyVetoException { + super("org.sqlite.JDBC", url); + } + + private static final String QueryCreateTable = + "CREATE TABLE IF NOT EXISTS EssentialsProtect (" + + "worldName TEXT ,playerName TEXT, " + + "x NUMERIC, y NUMERIC, z NUMERIC)"; + + @Override + protected PreparedStatement getStatementCreateTable(Connection conn) throws SQLException { + return conn.prepareStatement(QueryCreateTable); + } + + private static final String QueryUpdateFrom2_0Table = + "CREATE INDEX IF NOT EXISTS position ON EssentialsProtect (" + + "worldName, x, z, y)"; + + @Override + protected PreparedStatement getStatementUpdateFrom2_0Table(Connection conn) throws SQLException { + return conn.prepareStatement(QueryUpdateFrom2_0Table); + } + private static final String QueryDeleteAll = "DELETE FROM EssentialsProtect;"; + + @Override + protected PreparedStatement getStatementDeleteAll(Connection conn) throws SQLException { + return conn.prepareStatement(QueryDeleteAll); + } + private static final String QueryInsert = + "INSERT INTO EssentialsProtect (worldName, x, y, z, playerName) VALUES (?, ?, ?, ?, ?);"; + + @Override + protected PreparedStatement getStatementInsert(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryInsert); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + ps.setString(5, playerName); + return ps; + } + private static final String QueryPlayerCountByLocation = + "SELECT COUNT(playerName), SUM(playerName = ?) FROM EssentialsProtect " + + "WHERE worldName = ? AND x = ? AND y = ? AND z = ? GROUP BY x;"; + + @Override + protected PreparedStatement getStatementPlayerCountByLocation(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryPlayerCountByLocation); + ps.setString(1, playerName); + ps.setString(2, world); + ps.setInt(3, x); + ps.setInt(4, y); + ps.setInt(5, z); + return ps; + } + private static final String QueryPlayersByLocation = + "SELECT playerName FROM EssentialsProtect WHERE worldname = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementPlayersByLocation(Connection conn, String world, int x, int y, int z) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryPlayersByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryDeleteByLocation = + "DELETE FROM EssentialsProtect WHERE worldName = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementDeleteByLocation(Connection conn, String world, int x, int y, int z) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryDeleteByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryAllBlocks = + "SELECT worldName, x, y, z, playerName FROM EssentialsProtect;"; + + @Override + protected PreparedStatement getStatementAllBlocks(Connection conn) throws SQLException { + return conn.prepareStatement(QueryAllBlocks); + } +} |