[trunk] Protect refactors (formally known as 3.0) needs ***EXTENSIVE*** testing

git-svn-id: https://svn.java.net/svn/essentials~svn/trunk@1574 e251c2fe-e539-e718-e476-b85c1f46cddb
This commit is contained in:
ementalo 2011-06-02 23:09:59 +00:00
parent 3dab3d8df8
commit f6cedda1e2
16 changed files with 971 additions and 870 deletions

View file

@ -198,20 +198,21 @@ public class Settings implements IConf
return config.getBoolean("non-ess-in-help", true); return config.getBoolean("non-ess-in-help", true);
} }
public Map<String, Boolean> getEpSettings() public HashMap<String, Boolean> getEpSettings()
{ {
Map<String, Boolean> epSettings = new HashMap<String, Boolean>(); HashMap<String, Boolean> epSettings = new HashMap<String, Boolean>();
epSettings.put("protect.protect.signs", config.getBoolean("protect.protect.signs", true)); epSettings.put("protect.protect.signs", config.getBoolean("protect.protect.signs", true));
epSettings.put("protect.protect.rails", config.getBoolean("protect.protect.rails", true)); epSettings.put("protect.protect.rails", config.getBoolean("protect.protect.rails", true));
epSettings.put("protect.protect.block-below", config.getBoolean("protect.protect.block-below", true)); epSettings.put("protect.protect.block-below", config.getBoolean("protect.protect.block-below", true));
epSettings.put("protect.protect.prevent-block-on-rails", config.getBoolean("protect.protect.prevent-block-on-rails", false)); epSettings.put("protect.protect.prevent-block-on-rails", config.getBoolean("protect.protect.prevent-block-on-rails", false));
epSettings.put("protect.memstore", config.getBoolean("protect.memstore", false));
return epSettings; return epSettings;
} }
public Map<String, String> getEpDBSettings() public HashMap<String, String> getEpDBSettings()
{ {
Map<String, String> epSettings = new HashMap<String, String>(); HashMap<String, String> epSettings = new HashMap<String, String>();
epSettings.put("protect.datatype", config.getString("protect.datatype", "sqlite")); epSettings.put("protect.datatype", config.getString("protect.datatype", "sqlite"));
epSettings.put("protect.username", config.getString("protect.username", "root")); epSettings.put("protect.username", config.getString("protect.username", "root"));
epSettings.put("protect.password", config.getString("protect.password", "root")); epSettings.put("protect.password", config.getString("protect.password", "root"));
@ -219,9 +220,9 @@ public class Settings implements IConf
return epSettings; return epSettings;
} }
public List<Integer> getEpAlertOnPlacement() public ArrayList getEpAlertOnPlacement()
{ {
final List<Integer> epAlertPlace = new ArrayList<Integer>(); final ArrayList epAlertPlace = new ArrayList();
for (String itemName : config.getString("protect.alert.on-placement", "").split(",")) { for (String itemName : config.getString("protect.alert.on-placement", "").split(",")) {
itemName = itemName.trim(); itemName = itemName.trim();
if (itemName.isEmpty()) { if (itemName.isEmpty()) {
@ -238,9 +239,9 @@ public class Settings implements IConf
return epAlertPlace; return epAlertPlace;
} }
public List<Integer> getEpAlertOnUse() public ArrayList getEpAlertOnUse()
{ {
final List<Integer> epAlertUse = new ArrayList<Integer>(); final ArrayList epAlertUse = new ArrayList();
for (String itemName : config.getString("protect.alert.on-use", "").split(",")) { for (String itemName : config.getString("protect.alert.on-use", "").split(",")) {
itemName = itemName.trim(); itemName = itemName.trim();
if (itemName.isEmpty()) { if (itemName.isEmpty()) {
@ -257,9 +258,9 @@ public class Settings implements IConf
return epAlertUse; return epAlertUse;
} }
public List<Integer> getEpAlertOnBreak() public ArrayList getEpAlertOnBreak()
{ {
final List<Integer> epAlertPlace = new ArrayList<Integer>(); final ArrayList epAlertPlace = new ArrayList();
for (String itemName : config.getString("protect.alert.on-break", "").split(",")) { for (String itemName : config.getString("protect.alert.on-break", "").split(",")) {
itemName = itemName.trim(); itemName = itemName.trim();
if (itemName.isEmpty()) { if (itemName.isEmpty()) {
@ -276,9 +277,9 @@ public class Settings implements IConf
return epAlertPlace; return epAlertPlace;
} }
public List<Integer> epBlackListPlacement() public ArrayList epBlackListPlacement()
{ {
final List<Integer> epBlacklistPlacement = new ArrayList<Integer>(); final ArrayList epBlacklistPlacement = new ArrayList();
for (String itemName : config.getString("protect.blacklist.placement", "").split(",")) { for (String itemName : config.getString("protect.blacklist.placement", "").split(",")) {
itemName = itemName.trim(); itemName = itemName.trim();
if (itemName.isEmpty()) { if (itemName.isEmpty()) {
@ -295,9 +296,9 @@ public class Settings implements IConf
return epBlacklistPlacement; return epBlacklistPlacement;
} }
public List<Integer> epBlackListUsage() public ArrayList epBlackListUsage()
{ {
final List<Integer> epBlackListUsage = new ArrayList<Integer>(); final ArrayList epBlackListUsage = new ArrayList();
for (String itemName : config.getString("protect.blacklist.usage", "").split(",")) { for (String itemName : config.getString("protect.blacklist.usage", "").split(",")) {
itemName = itemName.trim(); itemName = itemName.trim();
if (itemName.isEmpty()) { if (itemName.isEmpty()) {
@ -314,9 +315,9 @@ public class Settings implements IConf
return epBlackListUsage; return epBlackListUsage;
} }
public Map<String, Boolean> getEpGuardSettings() public HashMap<String, Boolean> getEpGuardSettings()
{ {
final Map<String, Boolean> epSettings = new HashMap<String, Boolean>(); final HashMap<String, Boolean> epSettings = new HashMap<String, Boolean>();
epSettings.put("protect.prevent.lava-flow", config.getBoolean("protect.prevent.lava-flow", false)); epSettings.put("protect.prevent.lava-flow", config.getBoolean("protect.prevent.lava-flow", false));
epSettings.put("protect.prevent.water-flow", config.getBoolean("protect.prevent.water-flow", false)); epSettings.put("protect.prevent.water-flow", config.getBoolean("protect.prevent.water-flow", false));
epSettings.put("protect.prevent.water-bucket-flow", config.getBoolean("protect.prevent.water-bucket-flow", false)); epSettings.put("protect.prevent.water-bucket-flow", config.getBoolean("protect.prevent.water-bucket-flow", false));
@ -337,9 +338,9 @@ public class Settings implements IConf
return epSettings; return epSettings;
} }
public Map<String, Boolean> getEpPlayerSettings() public HashMap<String, Boolean> getEpPlayerSettings()
{ {
final Map<String, Boolean> epPlayerSettings = new HashMap<String, Boolean>(); final HashMap<String, Boolean> epPlayerSettings = new HashMap<String, Boolean>();
epPlayerSettings.put("protect.disable.fall", config.getBoolean("protect.disable.fall", false)); epPlayerSettings.put("protect.disable.fall", config.getBoolean("protect.disable.fall", false));
epPlayerSettings.put("protect.disable.pvp", config.getBoolean("protect.disable.pvp", false)); epPlayerSettings.put("protect.disable.pvp", config.getBoolean("protect.disable.pvp", false));
epPlayerSettings.put("protect.disable.drown", config.getBoolean("protect.disable.drown", false)); epPlayerSettings.put("protect.disable.drown", config.getBoolean("protect.disable.drown", false));
@ -421,9 +422,9 @@ public class Settings implements IConf
config.load(); config.load();
} }
public ArrayList<Integer> itemSpawnBlacklist() public ArrayList itemSpawnBlacklist()
{ {
ArrayList<Integer> epItemSpwn = new ArrayList<Integer>(); ArrayList epItemSpwn = new ArrayList();
for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) { for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) {
itemName = itemName.trim(); itemName = itemName.trim();
if (itemName.isEmpty()) { if (itemName.isEmpty()) {
@ -440,9 +441,9 @@ public class Settings implements IConf
return epItemSpwn; return epItemSpwn;
} }
public ArrayList<Integer> epBlockBreakingBlacklist() public ArrayList epBlockBreakingBlacklist()
{ {
ArrayList<Integer> epBreakList = new ArrayList<Integer>(); ArrayList epBreakList = new ArrayList();
for (String itemName : config.getString("protect.blacklist.break", "").split(",")) { for (String itemName : config.getString("protect.blacklist.break", "").split(",")) {
itemName = itemName.trim(); itemName = itemName.trim();
if (itemName.isEmpty()) { if (itemName.isEmpty()) {

View file

@ -362,6 +362,9 @@ protect:
# Prevent placing blocks above protected rails, this is to stop a potential griefing # Prevent placing blocks above protected rails, this is to stop a potential griefing
prevent-block-on-rails: false prevent-block-on-rails: false
#Store blocks / signs in memory before writing
memstore: false
# Disable various default physics and behaviors # Disable various default physics and behaviors
disable: disable:

View file

@ -73,14 +73,13 @@
--> -->
<!--target name="-post-jar"> <target name="-post-jar">
<jar jarfile="${dist.dir}/EssentialsProtect.jar"> <jar jarfile="${dist.dir}/EssentialsProtect.jar">
<zipfileset src="${dist.jar}" excludes="META-INF/*" /> <zipfileset src="${dist.jar}" excludes="META-INF/*" />
<zipfileset src="../lib/mysql.jar" excludes="META-INF/*" /> <zipfileset src="../lib/c3p0-0.9.1.2.jar" excludes="META-INF/*" />
<zipfileset src="../lib/sqlite.jar" excludes="META-INF/*" />
<manifest> <manifest>
<attribute name="Classpath" value="Essentials.jar"/> <attribute name="Classpath" value="Essentials.jar"/>
</manifest> </manifest>
</jar> </jar>
</target--> </target>
</project> </project>

View file

@ -2,10 +2,16 @@ package com.earth2me.essentials.protect;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.IConf; import com.earth2me.essentials.IConf;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.Util; import com.earth2me.essentials.Util;
import java.util.List; import com.earth2me.essentials.protect.data.IProtectedBlock;
import java.util.Map; 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.ArrayList;
import java.util.HashMap;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Location; import org.bukkit.Location;
@ -22,19 +28,21 @@ public class EssentialsProtect extends JavaPlugin implements IConf
private EssentialsProtectPlayerListener playerListener = null; private EssentialsProtectPlayerListener playerListener = null;
private EssentialsProtectEntityListener entityListener = null; private EssentialsProtectEntityListener entityListener = null;
private EssentialsProtectWeatherListener weatherListener = null; private EssentialsProtectWeatherListener weatherListener = null;
private EssentialsProtectServerListener serverListener = null;
public static final String AUTHORS = Essentials.AUTHORS; public static final String AUTHORS = Essentials.AUTHORS;
private static final Logger logger = Logger.getLogger("Minecraft"); private static final Logger logger = Logger.getLogger("Minecraft");
public static Map<String, Boolean> genSettings = null; public static HashMap<String, Boolean> genSettings = null;
public static Map<String, String> dataSettings = null; public static HashMap<String, String> dataSettings = null;
public static Map<String, Boolean> guardSettings = null; public static HashMap<String, Boolean> guardSettings = null;
public static Map<String, Boolean> playerSettings = null; public static HashMap<String, Boolean> playerSettings = null;
public static List<Integer> usageList = null; public static ArrayList usageList = null;
public static List<Integer> blackListPlace = null; public static ArrayList blackListPlace = null;
public static List<Integer> breakBlackList = null; public static ArrayList breakBlackList = null;
public static List<Integer> onPlaceAlert = null; public static ArrayList onPlaceAlert = null;
public static List<Integer> onUseAlert = null; public static ArrayList onUseAlert = null;
public static List<Integer> onBreakAlert = null; public static ArrayList onBreakAlert = null;
private IProtectedBlock storage = null;
IEssentials ess = null;
private static EssentialsProtect instance = null;
public EssentialsProtect() public EssentialsProtect()
{ {
@ -42,48 +50,44 @@ public class EssentialsProtect extends JavaPlugin implements IConf
public void onEnable() public void onEnable()
{ {
ess = Essentials.getStatic();
PluginManager pm = this.getServer().getPluginManager(); PluginManager pm = this.getServer().getPluginManager();
Essentials ess = (Essentials)pm.getPlugin("Essentials");
if (!ess.isEnabled())
{
pm.enablePlugin(ess);
}
instance = this;
reloadConfig();
playerListener = new EssentialsProtectPlayerListener(this); playerListener = new EssentialsProtectPlayerListener(this);
blockListener = new EssentialsProtectBlockListener(this); blockListener = new EssentialsProtectBlockListener(this);
entityListener = new EssentialsProtectEntityListener(this); entityListener = new EssentialsProtectEntityListener(this);
weatherListener = new EssentialsProtectWeatherListener(this); weatherListener = new EssentialsProtectWeatherListener(this);
serverListener = new EssentialsProtectServerListener(this);
pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.Low, this); pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.Low, this);
//blocklistener
pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Highest, this); pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Highest, this);
pm.registerEvent(Type.BLOCK_FROMTO, 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_IGNITE, blockListener, Priority.Highest, this);
pm.registerEvent(Type.BLOCK_BURN, blockListener, Priority.Highest, this); pm.registerEvent(Type.BLOCK_BURN, blockListener, Priority.Highest, this);
pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Highest, this);
//entitylistener
pm.registerEvent(Type.ENTITY_EXPLODE, entityListener, Priority.Highest, this); pm.registerEvent(Type.ENTITY_EXPLODE, entityListener, Priority.Highest, this);
pm.registerEvent(Type.ENTITY_DAMAGE, 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.BLOCK_BREAK, blockListener, Priority.Highest, this);
pm.registerEvent(Type.CREATURE_SPAWN, entityListener, Priority.Highest, this); pm.registerEvent(Type.CREATURE_SPAWN, entityListener, Priority.Highest, this);
//weatherlistener
pm.registerEvent(Type.WEATHER_CHANGE, weatherListener, Priority.Highest, this);
pm.registerEvent(Type.THUNDER_CHANGE, weatherListener, Priority.Highest, this);
pm.registerEvent(Type.LIGHTNING_STRIKE, weatherListener, Priority.Highest, this); pm.registerEvent(Type.LIGHTNING_STRIKE, weatherListener, Priority.Highest, this);
pm.registerEvent(Type.THUNDER_CHANGE, weatherListener, Priority.Highest, this);
pm.registerEvent(Type.WEATHER_CHANGE, weatherListener, Priority.Highest, this);
//serverlistener if (!this.getDescription().getVersion().equals(Essentials.getStatic().getDescription().getVersion()))
pm.registerEvent(Type.PLUGIN_ENABLE, serverListener, Priority.Highest, this); {
logger.log(Level.WARNING, "Version mismatch! Please update all Essentials jars to the same version.");
reloadConfig();
Essentials.getStatic().addReloadListener(this);
if (!this.getDescription().getVersion().equals(Essentials.getStatic().getDescription().getVersion())) {
logger.log(Level.WARNING, Util.i18n("versionMismatchAll"));
} }
logger.info(Util.format("loadinfo", this.getDescription().getName(), this.getDescription().getVersion(), Essentials.AUTHORS)); logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS);
} }
public static boolean checkProtectionItems(List<Integer> itemList, int id) public static boolean checkProtectionItems(ArrayList itemList, int id)
{ {
return !itemList.isEmpty() && itemList.contains(id); return !itemList.isEmpty() && itemList.contains(String.valueOf(id));
} }
@Override @Override
@ -106,29 +110,65 @@ public class EssentialsProtect extends JavaPlugin implements IConf
onBreakAlert = null; onBreakAlert = null;
} }
public void reloadConfig()
{
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();
}
public void alert(User user, String item, String type) public void alert(User user, String item, String type)
{ {
Location loc = user.getLocation(); Location loc = user.getLocation();
for (Player p : this.getServer().getOnlinePlayers()) for (Player p : this.getServer().getOnlinePlayers())
{ {
User alertUser = Essentials.getStatic().getUser(p); User alertUser = ess.getUser(p);
if (alertUser.isAuthorized("essentials.protect.alerts")) if (alertUser.isAuthorized("essentials.protect.alerts"))
alertUser.sendMessage(Util.format("alertFormat", user.getName(), type, item, EssentialsProtectData.formatCoords(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()))); alertUser.sendMessage(Util.format("alertFormat", user.getName(), type, item, formatCoords(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())));
} }
} }
public static String formatCoords(int x, int y, int z)
{
return x + "," + y + "," + z;
}
public void reloadConfig()
{
dataSettings = ess.getSettings().getEpDBSettings();
genSettings = ess.getSettings().getEpSettings();
guardSettings = ess.getSettings().getEpGuardSettings();
usageList = ess.getSettings().epBlackListUsage();
blackListPlace = ess.getSettings().epBlackListPlacement();
breakBlackList = ess.getSettings().epBlockBreakingBlacklist();
onPlaceAlert = ess.getSettings().getEpAlertOnPlacement();
onUseAlert = ess.getSettings().getEpAlertOnUse();
onBreakAlert = ess.getSettings().getEpAlertOnBreak();
playerSettings = ess.getSettings().getEpPlayerSettings();
if (dataSettings.get("protect.datatype").equals("mysql"))
{
try
{
storage = new ProtectedBlockMySQL(dataSettings.get("protect.mysqlDb"), dataSettings.get("protect.username"), dataSettings.get("protect.password"));
}
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 (genSettings.get("protect.memstore"))
{
storage = new ProtectedBlockMemory(storage);
}
}
public static IProtectedBlock getStorage()
{
return EssentialsProtect.instance.storage;
}
} }

View file

@ -3,6 +3,8 @@ package com.earth2me.essentials.protect;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.Util; import com.earth2me.essentials.Util;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
@ -18,41 +20,25 @@ import org.bukkit.inventory.ItemStack;
public class EssentialsProtectBlockListener extends BlockListener public class EssentialsProtectBlockListener extends BlockListener
{ {
private EssentialsProtect parent; private EssentialsProtect parent;
private int railBlockX;
private int railBlockY;
private int railBlockZ;
private EssentialsProtectData spData;
public EssentialsProtectBlockListener(EssentialsProtect parent) public EssentialsProtectBlockListener(EssentialsProtect parent)
{ {
this.parent = parent; this.parent = parent;
} }
private void initialize()
{
if (spData != null) return;
spData = new EssentialsProtectData();
}
@Override @Override
public void onBlockPlace(BlockPlaceEvent event) public void onBlockPlace(BlockPlaceEvent event)
{ {
if (event.isCancelled()) return; if (event.isCancelled()) return;
initialize(); final ItemStack item = event.getItemInHand();
ItemStack item = event.getItemInHand(); final User user = parent.ess.getUser(event.getPlayer());
User user = Essentials.getStatic().getUser(event.getPlayer());
if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild())
{ {
if(Essentials.getStatic().getSettings().warnOnBuildDisallow())
{
user.sendMessage(Util.i18n("buildAlert"));
}
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
Block blockPlaced = event.getBlockPlaced();
int id = event.getBlockPlaced().getTypeId(); int id = event.getBlockPlaced().getTypeId();
if (EssentialsProtect.checkProtectionItems(EssentialsProtect.blackListPlace, id) && !user.isAuthorized("essentials.protect.exemptplacement")) if (EssentialsProtect.checkProtectionItems(EssentialsProtect.blackListPlace, id) && !user.isAuthorized("essentials.protect.exemptplacement"))
@ -61,34 +47,33 @@ public class EssentialsProtectBlockListener extends BlockListener
return; return;
} }
if (EssentialsProtect.checkProtectionItems(EssentialsProtect.onPlaceAlert, id)) if (!EssentialsProtect.onPlaceAlert.isEmpty() && EssentialsProtect.onPlaceAlert.contains(String.valueOf(item.getTypeId())))
{ {
parent.alert(user, item.getType().toString(), Util.i18n("alertPlaced")); parent.alert(user, item.getType().toString(), Util.i18n("alertPlaced"));
} }
if (spData.isBlockAboveProtectedRail(blockPlaced.getFace(BlockFace.DOWN))) Block blockPlaced = event.getBlockPlaced();
{ Block below = blockPlaced.getFace(BlockFace.DOWN);
if (EssentialsProtect.genSettings.get("protect.protect.prevent-block-on-rails")) if (below.getType() == Material.RAILS) {
if (EssentialsProtect.genSettings.get("protect.protect.prevent.block-on-rail"))
{ {
event.setCancelled(true); if (EssentialsProtect.getStorage().isProtected(below, user.getName())) {
return; event.setCancelled(true);
return;
}
} }
} }
if (blockPlaced.getType() == Material.RAILS) List<Block> protect = new ArrayList<Block>();
{ if (blockPlaced.getType() == Material.RAILS) {
if (EssentialsProtect.genSettings.get("protect.protect.rails")) if (EssentialsProtect.genSettings.get("protect.protect.rails"))
{ {
if (user.isAuthorized("essentials.protect")) if (user.isAuthorized("essentials.protect"))
{ {
railBlockX = blockPlaced.getX(); protect.add(blockPlaced);
railBlockY = blockPlaced.getY();
railBlockZ = blockPlaced.getZ();
spData.insertProtectionIntoDb(user.getWorld().getName(), user.getName(), railBlockX, railBlockY, railBlockZ);
if (EssentialsProtect.genSettings.get("protect.protect.block-below")) 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));
} }
} }
} }
@ -98,25 +83,17 @@ public class EssentialsProtectBlockListener extends BlockListener
{ {
if (user.isAuthorized("essentials.protect")) if (user.isAuthorized("essentials.protect"))
{ {
int signBlockX = blockPlaced.getX(); protect.add(blockPlaced);
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")) if (EssentialsProtect.genSettings.get("protect.protect.block-below"))
{ {
signBlockX = event.getBlockAgainst().getX(); protect.add(event.getBlockAgainst());
signBlockY = event.getBlockAgainst().getY();
signBlockZ = event.getBlockAgainst().getZ();
spData.insertProtectionIntoDb(user.getWorld().getName(), user.getName(), signBlockX,
signBlockY, signBlockZ);
} }
} }
} }
} }
for (Block block : protect) {
EssentialsProtect.getStorage().protectBlock(block, user.getName());
}
} }
@Override @Override
@ -133,14 +110,6 @@ public class EssentialsProtectBlockListener extends BlockListener
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (event.getBlock().getType() == Material.OBSIDIAN ||
event.getBlock().getFace(BlockFace.DOWN).getType() == Material.OBSIDIAN)
{
event.setCancelled(EssentialsProtect.guardSettings.get("protect.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(EssentialsProtect.guardSettings.get("protect.prevent.fire-spread"));
@ -158,12 +127,6 @@ public class EssentialsProtectBlockListener extends BlockListener
event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.lava-fire-spread")); event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.lava-fire-spread"));
return; return;
} }
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LIGHTNING))
{
event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.lightning-fire-spread"));
return;
}
} }
@Override @Override
@ -226,8 +189,7 @@ public class EssentialsProtectBlockListener extends BlockListener
public void onBlockBreak(BlockBreakEvent event) public void onBlockBreak(BlockBreakEvent event)
{ {
if (event.isCancelled()) return; if (event.isCancelled()) return;
initialize(); User user = parent.ess.getUser(event.getPlayer());
User user = Essentials.getStatic().getUser(event.getPlayer());
Block block = event.getBlock(); Block block = event.getBlock();
if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild())
{ {
@ -235,13 +197,13 @@ public class EssentialsProtectBlockListener extends BlockListener
return; return;
} }
if (EssentialsProtect.checkProtectionItems(EssentialsProtect.breakBlackList, block.getTypeId()) && !user.isAuthorized("essentials.protect.exemptbreak")) if(EssentialsProtect.breakBlackList.contains(String.valueOf(block.getTypeId())) && !user.isAuthorized("essentials.protect.exemptbreak"))
{ {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (EssentialsProtect.checkProtectionItems(EssentialsProtect.onBreakAlert, block.getTypeId())) if (!EssentialsProtect.onBreakAlert.isEmpty() && EssentialsProtect.onBreakAlert.contains(String.valueOf(block.getTypeId())))
{ {
parent.alert(user, block.getType().toString(), Util.i18n("alertBroke")); parent.alert(user, block.getType().toString(), Util.i18n("alertBroke"));
} }
@ -250,28 +212,57 @@ public class EssentialsProtectBlockListener extends BlockListener
{ {
if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST || block.getType() == Material.RAILS) if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST || block.getType() == Material.RAILS)
{ {
spData.removeProtectionFromDB(block, true); EssentialsProtect.getStorage().unprotectBlock(block);
if (block.getType() == Material.RAILS || block.getType() == Material.SIGN_POST) {
Block below = block.getFace(BlockFace.DOWN);
EssentialsProtect.getStorage().unprotectBlock(below);
} else {
BlockFace[] faces = new BlockFace[] {
BlockFace.NORTH,
BlockFace.EAST,
BlockFace.SOUTH,
BlockFace.WEST
};
for (BlockFace blockFace : faces) {
Block against = block.getFace(blockFace);
EssentialsProtect.getStorage().unprotectBlock(against);
}
}
} }
else else
{ {
spData.removeProtectionFromDB(block); EssentialsProtect.getStorage().unprotectBlock(block);
} }
return; return;
} }
else else
{ {
boolean canDestroy = spData.canDestroy(user.getWorld().getName(), user.getName(), block);
if (canDestroy) boolean isProtected = EssentialsProtect.getStorage().isProtected(block, user.getName());
{ if (!isProtected) {
if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST || block.getType() == Material.RAILS) if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST || block.getType() == Material.RAILS)
{ {
spData.removeProtectionFromDB(block, true); EssentialsProtect.getStorage().unprotectBlock(block);
if (block.getType() == Material.RAILS || block.getType() == Material.SIGN_POST) {
Block below = block.getFace(BlockFace.DOWN);
EssentialsProtect.getStorage().unprotectBlock(below);
} else {
BlockFace[] faces = new BlockFace[] {
BlockFace.NORTH,
BlockFace.EAST,
BlockFace.SOUTH,
BlockFace.WEST
};
for (BlockFace blockFace : faces) {
Block against = block.getFace(blockFace);
EssentialsProtect.getStorage().unprotectBlock(against);
}
}
} }
else else
{ {
spData.removeProtectionFromDB(block); EssentialsProtect.getStorage().unprotectBlock(block);
} }
return;
} }
event.setCancelled(true); event.setCancelled(true);
return; return;

View file

@ -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;
}
}

View file

@ -1,7 +1,6 @@
package com.earth2me.essentials.protect; package com.earth2me.essentials.protect;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.EssentialsBlockListener;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
@ -9,9 +8,7 @@ import java.util.List;
import net.minecraft.server.ChunkPosition; import net.minecraft.server.ChunkPosition;
import net.minecraft.server.Packet60Explosion; import net.minecraft.server.Packet60Explosion;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.entity.CraftPlayer;
@ -28,8 +25,6 @@ import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityListener; import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.EntityTargetEvent.TargetReason;
public class EssentialsProtectEntityListener extends EntityListener public class EssentialsProtectEntityListener extends EntityListener
@ -44,34 +39,22 @@ public class EssentialsProtectEntityListener extends EntityListener
@Override @Override
public void onEntityDamage(EntityDamageEvent event) public void onEntityDamage(EntityDamageEvent event)
{ {
if (event.isCancelled()) if (event.isCancelled()) return;
{
return;
}
if (event instanceof EntityDamageByBlockEvent) if (event instanceof EntityDamageByBlockEvent)
{ {
DamageCause cause = event.getCause(); DamageCause cause = event.getCause();
if (EssentialsProtect.playerSettings.get("protect.disable.contactdmg") && cause == DamageCause.CONTACT 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")))
{ {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (EssentialsProtect.playerSettings.get("protect.disable.lavadmg") && cause == DamageCause.LAVA 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")))
{ {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (EssentialsProtect.guardSettings.get("protect.prevent.tnt-explosion") && cause == DamageCause.BLOCK_EXPLOSION 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")))
{ {
event.setCancelled(true); event.setCancelled(true);
return; return;
@ -89,8 +72,8 @@ public class EssentialsProtectEntityListener extends EntityListener
{ {
if (EssentialsProtect.playerSettings.get("protect.disable.pvp")) if (EssentialsProtect.playerSettings.get("protect.disable.pvp"))
{ {
User defender = Essentials.getStatic().getUser(eDefend); User defender = parent.ess.getUser(eDefend);
User attacker = Essentials.getStatic().getUser(eAttack); User attacker = parent.ess.getUser(eAttack);
if (!defender.isAuthorized("essentials.protect.pvp") || !attacker.isAuthorized("essentials.protect.pvp")) if (!defender.isAuthorized("essentials.protect.pvp") || !attacker.isAuthorized("essentials.protect.pvp"))
{ {
@ -102,19 +85,13 @@ public class EssentialsProtectEntityListener extends EntityListener
//Creeper explode prevention //Creeper explode prevention
if (eAttack != null && eAttack instanceof Monster) if (eAttack != null && eAttack instanceof Monster)
{ {
if (eAttack instanceof Creeper && EssentialsProtect.guardSettings.get("protect.prevent.creeper-explosion") 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); event.setCancelled(true);
return; return;
} }
if (eAttack instanceof Creeper && EssentialsProtect.guardSettings.get("protect.prevent.creeper-playerdamage") 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); event.setCancelled(true);
return; return;
@ -124,12 +101,9 @@ public class EssentialsProtectEntityListener extends EntityListener
if (event instanceof EntityDamageByProjectileEvent) if (event instanceof EntityDamageByProjectileEvent)
{ {
if (event.getEntity() instanceof Player 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"))
{ {
event.setCancelled(true); event.setCancelled(EssentialsProtect.playerSettings.get("protect.disable.projectiles"));
return; return;
} }
} }
@ -138,39 +112,24 @@ public class EssentialsProtectEntityListener extends EntityListener
Entity casualty = event.getEntity(); Entity casualty = event.getEntity();
if (casualty instanceof Player) if (casualty instanceof Player)
{ {
if (EssentialsProtect.playerSettings.get("protect.disable.fall") && cause == DamageCause.FALL 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); event.setCancelled(true);
return; return;
} }
if (EssentialsProtect.playerSettings.get("protect.disable.suffocate") && cause == DamageCause.SUFFOCATION 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")))
{ {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (EssentialsProtect.playerSettings.get("protect.disable.firedmg") && (cause == DamageCause.FIRE if (EssentialsProtect.playerSettings.get("protect.disable.firedmg") && (cause == DamageCause.FIRE
|| cause == DamageCause.FIRE_TICK) || cause == DamageCause.FIRE_TICK))
&& !(Essentials.getStatic().getUser(casualty).isAuthorized("essentials.protect.damage.fire")
&& !Essentials.getStatic().getUser(event.getEntity()).isAuthorized("essentials.protect.damage.disable")))
{ {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (EssentialsProtect.playerSettings.get("protect.disable.drown") && cause == DamageCause.DROWNING 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")))
{
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")))
{ {
event.setCancelled(true); event.setCancelled(true);
return; return;
@ -181,14 +140,11 @@ public class EssentialsProtectEntityListener extends EntityListener
@Override @Override
public void onEntityExplode(EntityExplodeEvent event) public void onEntityExplode(EntityExplodeEvent event)
{ {
if (event.isCancelled()) if (event.isCancelled()) return;
{
return;
}
if (event.getEntity() instanceof LivingEntity) if (event.getEntity() instanceof LivingEntity)
{ {
//Nicccccccccce plaaacccccccccce.. //Nicccccccccce plaaacccccccccce..
int maxHeight = Essentials.getStatic().getSettings().getEpCreeperMaxHeight(); int maxHeight = parent.ess.getSettings().getEpCreeperMaxHeight();
if (EssentialsProtect.guardSettings.get("protect.prevent.creeper-explosion") if (EssentialsProtect.guardSettings.get("protect.prevent.creeper-explosion")
|| EssentialsProtect.guardSettings.get("protect.prevent.creeper-blockdamage") || EssentialsProtect.guardSettings.get("protect.prevent.creeper-blockdamage")
|| (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight)) || (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight))
@ -196,7 +152,7 @@ public class EssentialsProtectEntityListener extends EntityListener
HashSet<ChunkPosition> set = new HashSet<ChunkPosition>(event.blockList().size()); HashSet<ChunkPosition> set = new HashSet<ChunkPosition>(event.blockList().size());
Player[] players = parent.getServer().getOnlinePlayers(); Player[] players = parent.getServer().getOnlinePlayers();
List<ChunkPosition> blocksUnderPlayers = new ArrayList<ChunkPosition>(players.length); List<ChunkPosition> blocksUnderPlayers = new ArrayList<ChunkPosition>(players.length);
Location loc = event.getLocation(); final Location loc = event.getLocation();
for (Player player : players) for (Player player : players)
{ {
if (player.getWorld().equals(loc.getWorld())) if (player.getWorld().equals(loc.getWorld()))
@ -208,9 +164,10 @@ public class EssentialsProtectEntityListener extends EntityListener
player.getLocation().getBlockZ())); player.getLocation().getBlockZ()));
} }
} }
ChunkPosition cp;
for (Block block : event.blockList()) for (Block block : event.blockList())
{ {
ChunkPosition cp = new ChunkPosition(block.getX(), block.getY(), block.getZ()); cp = new ChunkPosition(block.getX(), block.getY(), block.getZ());
if (!blocksUnderPlayers.contains(cp)) if (!blocksUnderPlayers.contains(cp))
{ {
set.add(cp); set.add(cp);
@ -231,71 +188,18 @@ public class EssentialsProtectEntityListener extends EntityListener
return; 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"))
{
event.setCancelled(true);
return;
}
if ((block.getType() == Material.WALL_SIGN
|| block.getFace(BlockFace.NORTH).getType() == Material.WALL_SIGN
|| block.getFace(BlockFace.EAST).getType() == Material.WALL_SIGN
|| block.getFace(BlockFace.SOUTH).getType() == Material.WALL_SIGN
|| 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"))
{
event.setCancelled(true);
return;
}
if (EssentialsBlockListener.protectedBlocks.contains(block.getType())
&& EssentialsBlockListener.isBlockProtected(block))
{
event.setCancelled(true);
return;
}
}
} }
@Override @Override
public void onCreatureSpawn(CreatureSpawnEvent event) public void onCreatureSpawn(CreatureSpawnEvent event)
{ {
if (event.getEntity() instanceof CraftPlayer) if (event.getEntity() instanceof CraftPlayer || event.isCancelled()){ return;}
{ final String creatureName = event.getCreatureType().toString().toLowerCase();
return;
}
if (event.isCancelled())
{
return;
}
String creatureName = event.getCreatureType().toString().toLowerCase();
if (creatureName == null || creatureName.isEmpty()) if (creatureName == null || creatureName.isEmpty())
{ {
return; return;
} }
if (EssentialsProtect.guardSettings.get("protect.prevent.spawn." + creatureName)) if (EssentialsProtect.guardSettings.get("protect.prevent.spawn." + creatureName))
{
event.setCancelled(true);
}
}
@Override
public void onEntityTarget(EntityTargetEvent event)
{
if (!(event.getTarget() instanceof Player))
{
return;
}
User user = Essentials.getStatic().getUser(event.getTarget());
if ((event.getReason() == TargetReason.CLOSEST_PLAYER
|| event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY
|| event.getReason() == TargetReason.PIG_ZOMBIE_TARGET)
&& EssentialsProtect.guardSettings.get("protect.prevent.entitytarget")
&& !user.isAuthorized("essentials.protect.entitytarget.bypass"))
{ {
event.setCancelled(true); event.setCancelled(true);
return; return;

View file

@ -1,46 +1,33 @@
package com.earth2me.essentials.protect; package com.earth2me.essentials.protect;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerListener;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class EssentialsProtectPlayerListener extends PlayerListener public class EssentialsProtectPlayerListener extends PlayerListener
{ {
private EssentialsProtect parent; private EssentialsProtect parent;
private EssentialsProtectData spData = null;
public EssentialsProtectPlayerListener(EssentialsProtect parent) public EssentialsProtectPlayerListener(EssentialsProtect parent)
{ {
this.parent = parent; this.parent = parent;
} }
public void initialize()
{
if (spData != null) return;
spData = new EssentialsProtectData();
}
@Override @Override
public void onPlayerInteract(PlayerInteractEvent event) public void onPlayerInteract(PlayerInteractEvent event)
{ {
initialize();
if (event.isCancelled()) return; if (event.isCancelled()) return;
ItemStack item = event.getItem(); ItemStack item = event.getItem();
User user = Essentials.getStatic().getUser(event.getPlayer()); User user = parent.ess.getUser(event.getPlayer());
Block blockClicked = event.getClickedBlock(); Block blockClicked = event.getClickedBlock();
if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild())
{ {
if(Essentials.getStatic().getSettings().warnOnBuildDisallow())
{
user.sendMessage(Util.i18n("buildAlert"));
}
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@ -52,16 +39,26 @@ public class EssentialsProtectPlayerListener extends PlayerListener
return; return;
} }
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && user.isAuthorized("essentials.protect.ownerinfo")) if (user.isAuthorized("essentials.protect.admin"))
{ {
String ownerName = spData.getBlockOwner(user.getWorld().getName(), user.getName(), StringBuilder sb = new StringBuilder();
blockClicked); boolean first = true;
if (ownerName != null) for (String owner : EssentialsProtect.getStorage().getOwners(blockClicked))
{ {
user.sendMessage(Util.format("protectionOwner", ownerName)); if (!first)
{
sb.append(", ");
}
first = false;
sb.append(owner);
}
String ownerNames = sb.toString();
if (ownerNames != null && !ownerNames.isEmpty())
{
user.sendMessage(Util.format("protectionOwner", ownerNames));
} }
} }
if (item != null && EssentialsProtect.checkProtectionItems(EssentialsProtect.onUseAlert, item.getTypeId())) if (item != null && EssentialsProtect.onUseAlert.contains(String.valueOf(item.getTypeId())))
{ {
parent.alert(user, item.getType().toString(), Util.i18n("alertUsed")); parent.alert(user, item.getType().toString(), Util.i18n("alertUsed"));
} }

View file

@ -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);
}
}
}
}

View file

@ -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";
}

View file

@ -0,0 +1,15 @@
package com.earth2me.essentials.protect.data;
import java.util.List;
import java.util.Set;
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);
}

View file

@ -0,0 +1,9 @@
package com.earth2me.essentials.protect.data;
public class OwnedBlock {
int x;
int y;
int z;
String world;
String playerName;
}

View file

@ -0,0 +1,296 @@
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 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();
ob.world = rs.getString(1);
ob.x = rs.getInt(2);
ob.y = rs.getInt(3);
ob.z = rs.getInt(4);
ob.playerName = 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();
rs.next();
return 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);
}
}
}
}
}

View file

@ -0,0 +1,205 @@
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.Entry;
import java.util.Set;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.plugin.Plugin;
public class ProtectedBlockMemory implements IProtectedBlock {
List<String> worlds = new ArrayList<String>();
List<String> playerNames = new ArrayList<String>();
IProtectedBlock storage;
Plugin plugin;
class ProtectedLocation {
int x;
int y;
int z;
int w;
private ProtectedLocation(Block block, int worldId) {
this.x = block.getX();
this.y = block.getY();
this.z = block.getZ();
this.w = worldId;
}
private ProtectedLocation(OwnedBlock ownedBlock, int worldId) {
this.x = ownedBlock.x;
this.y = ownedBlock.y;
this.z = ownedBlock.z;
this.w = worldId;
}
@Override
public boolean equals(Object o) {
if (o instanceof ProtectedLocation) {
ProtectedLocation pl = (ProtectedLocation) o;
return x == pl.x && y == pl.y && z == pl.z && w == pl.w;
}
return false;
}
@Override
public int hashCode() {
return x ^ y ^ z ^ w;
}
}
class ProtectedBy {
private int playerId = -1;
private Set<Integer> playerIds;
private ProtectedBy() {
}
private void add(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);
}
}
private boolean contains(int playerId) {
if (playerIds == null) {
return this.playerId == playerId;
}
return playerIds.contains(playerId);
}
private List<String> getPlayers(List<String> playerNames) {
if (playerIds == null) {
List<String> list = new ArrayList<String>(2);
list.add(playerNames.get(playerId));
return list;
}
List<String> list = new ArrayList<String>(playerIds.size());
for (Integer integer : playerIds) {
list.add(playerNames.get(integer));
}
return list;
}
private int size() {
if (playerIds == null) {
return 1;
}
return playerIds.size();
}
}
HashMap<ProtectedLocation, ProtectedBy> blocks = new HashMap<ProtectedLocation, ProtectedBy>();
public ProtectedBlockMemory(IProtectedBlock storage) {
this.storage = storage;
importProtections(storage.exportProtections());
}
public void clearProtections() {
blocks.clear();
}
public final void importProtections(List<OwnedBlock> blocks) {
for (OwnedBlock ownedBlock : blocks) {
ProtectedLocation pl = new ProtectedLocation(ownedBlock, getWorldId(ownedBlock.world));
if (ownedBlock.playerName == null) {
continue;
}
protectBlock(pl, ownedBlock.playerName);
}
}
public List<OwnedBlock> exportProtections() {
List<OwnedBlock> blockList = new ArrayList<OwnedBlock>(blocks.size());
for (Entry<ProtectedLocation, ProtectedBy> entry : blocks.entrySet()) {
for (String name : entry.getValue().getPlayers(playerNames)) {
OwnedBlock ob = new OwnedBlock();
ob.x = entry.getKey().x;
ob.y = entry.getKey().y;
ob.z = entry.getKey().z;
ob.world = worlds.get(entry.getKey().w);
ob.playerName = name;
blockList.add(ob);
}
}
return blockList;
}
public void protectBlock(final Block block, final String playerName) {
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 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;
}
}

View file

@ -0,0 +1,124 @@
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;
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) {
testRS.close();
}
if (testPS != null) {
testPS.close();
}
}
}
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);
}
}

View file

@ -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);
}
}