Merge branch 'refs/heads/master' into release

This commit is contained in:
snowleo 2011-12-08 05:41:00 +01:00
commit 8d0230d6a8
217 changed files with 4828 additions and 4157 deletions

View File

@ -81,9 +81,7 @@ javac.source=1.6
javac.target=1.6
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}:\
${libs.junit.classpath}:\
${libs.junit_4.classpath}
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=

View File

@ -70,7 +70,6 @@ file.reference.craftbukkit-1.0.0-SNAPSHOT.jar=../lib/craftbukkit-1.0.0-SNAPSHOT.
file.reference.iCo4.jar=../lib/iCo4.jar
file.reference.iCo5.jar=../lib/iCo5.jar
file.reference.iCo6.jar=../lib/iCo6.jar
file.reference.junit-4.5.jar=../lib/junit_4/junit-4.5.jar
file.reference.lombok-0.10.1.jar=../lib/lombok-0.10.1.jar
file.reference.MultiCurrency.jar=../lib/MultiCurrency.jar
file.reference.Permissions3.jar=../lib/Permissions3.jar
@ -103,7 +102,7 @@ javac.target=1.6
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}:\
${file.reference.junit-4.5.jar}
${libs.junit_4.10.classpath}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=

View File

@ -1,6 +1,8 @@
package com.earth2me.essentials;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.command.Command;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.PluginCommandYamlParser;
@ -9,8 +11,9 @@ import org.bukkit.plugin.Plugin;
public class AlternativeCommandsHandler
{
private static final Logger LOGGER = Logger.getLogger("Minecraft");
private final transient Map<String, List<PluginCommand>> altcommands = new HashMap<String, List<PluginCommand>>();
private final transient Map<String, String> executed = new HashMap<String, String>();
private final transient Map<String, String> disabledList = new HashMap<String, String>();
private final transient IEssentials ess;
public AlternativeCommandsHandler(final IEssentials ess)
@ -118,13 +121,17 @@ public class AlternativeCommandsHandler
return commands.get(0);
}
public void executed(final String label, final String otherlabel)
public void executed(final String label, final String otherLabel)
{
executed.put(label, otherlabel);
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + otherLabel);
}
disabledList.put(label, otherLabel);
}
public Map<String, String> disabledCommands()
{
return executed;
return disabledList;
}
}

View File

@ -0,0 +1,77 @@
package com.earth2me.essentials;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import org.bukkit.enchantments.Enchantment;
public class Enchantments
{
private static final transient Pattern NUMPATTERN = Pattern.compile("\\d+");
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>();
static
{
ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD);
ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD);
ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED);
ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED);
ENCHANTMENTS.put("durability", Enchantment.DURABILITY);
ENCHANTMENTS.put("dura", Enchantment.DURABILITY);
ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY);
ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT);
ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT);
ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK);
ENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS);
ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS);
ENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("oxygen", Enchantment.OXYGEN);
ENCHANTMENTS.put("respiration", Enchantment.OXYGEN);
ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL);
ENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL);
ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE);
ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE);
ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE);
ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE);
ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH);
ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER);
ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER);
}
public static Enchantment getByName(String name) {
Enchantment enchantment;
if (NUMPATTERN.matcher(name).matches()) {
enchantment = Enchantment.getById(Integer.parseInt(name));
} else {
enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH));
}
if (enchantment == null)
{
enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH));
}
return enchantment;
}
public static Set<Entry<String, Enchantment>> entrySet()
{
return ENCHANTMENTS.entrySet();
}
}

View File

@ -19,6 +19,7 @@ package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.Economy;
import com.earth2me.essentials.api.IJails;
import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
@ -47,22 +48,24 @@ import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.yaml.snakeyaml.error.YAMLException;
public class Essentials extends JavaPlugin implements IEssentials
{
public static final int BUKKIT_VERSION = 1522;
public static final int BUKKIT_VERSION = 1566;
private static final Logger LOGGER = Logger.getLogger("Minecraft");
private transient ISettings settings;
private final transient TNTExplodeListener tntListener = new TNTExplodeListener(this);
private transient Spawn spawn;
private transient Jail jail;
private transient Jails jails;
private transient Warps warps;
private transient Worth worth;
private transient List<IConf> confList;
@ -112,32 +115,6 @@ public class Essentials extends JavaPlugin implements IEssentials
i18n = new I18n(this);
i18n.onEnable();
execTimer.mark("I18n1");
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings();
execTimer.mark("Upgrade");
confList = new ArrayList<IConf>();
settings = new Settings(this);
confList.add(settings);
execTimer.mark("Settings");
upgrade.afterSettings();
execTimer.mark("Upgrade2");
i18n.updateLocale(settings.getLocale());
userMap = new UserMap(this);
confList.add(userMap);
execTimer.mark("Init(Usermap)");
spawn = new Spawn(getServer(), this.getDataFolder());
confList.add(spawn);
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
execTimer.mark("Init(Spawn/Warp)");
worth = new Worth(this.getDataFolder());
confList.add(worth);
itemDb = new ItemDb(this);
confList.add(itemDb);
execTimer.mark("Init(Worth/ItemDB)");
reload();
backup = new Backup(this);
final PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins())
{
@ -153,7 +130,10 @@ public class Essentials extends JavaPlugin implements IEssentials
final int versionNumber = Integer.parseInt(versionMatch.group(4));
if (versionNumber < BUKKIT_VERSION)
{
LOGGER.log(Level.WARNING, _("notRecommendedBukkit"));
LOGGER.log(Level.SEVERE, _("notRecommendedBukkit"));
LOGGER.log(Level.SEVERE, _("requiredBukkit", Integer.toString(BUKKIT_VERSION)));
this.setEnabled(false);
return;
}
}
else
@ -162,7 +142,59 @@ public class Essentials extends JavaPlugin implements IEssentials
LOGGER.log(Level.INFO, getServer().getVersion());
LOGGER.log(Level.INFO, getServer().getBukkitVersion());
}
execTimer.mark("BukkitCheck");
try
{
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings();
execTimer.mark("Upgrade");
confList = new ArrayList<IConf>();
settings = new Settings(this);
confList.add(settings);
execTimer.mark("Settings");
upgrade.afterSettings();
execTimer.mark("Upgrade2");
i18n.updateLocale(settings.getLocale());
userMap = new UserMap(this);
confList.add(userMap);
execTimer.mark("Init(Usermap)");
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
execTimer.mark("Init(Spawn/Warp)");
worth = new Worth(this.getDataFolder());
confList.add(worth);
itemDb = new ItemDb(this);
confList.add(itemDb);
execTimer.mark("Init(Worth/ItemDB)");
reload();
}
catch (YAMLException exception)
{
if (pm.getPlugin("EssentialsUpdate") != null)
{
LOGGER.log(Level.SEVERE, _("essentialsHelp2"));
}
else
{
LOGGER.log(Level.SEVERE, _("essentialsHelp1"));
}
LOGGER.log(Level.SEVERE, exception.toString());
pm.registerEvent(Type.PLAYER_JOIN, new PlayerListener()
{
@Override
public void onPlayerJoin(PlayerJoinEvent event)
{
event.getPlayer().sendMessage("Essentials failed to load, read the log file.");
}
}, Priority.Low, this);
for (Player player : getServer().getOnlinePlayers())
{
player.sendMessage("Essentials failed to load, read the log file.");
}
this.setEnabled(false);
return;
}
backup = new Backup(this);
permissionsHandler = new PermissionsHandler(this, settings.useBukkitPermissions());
alternativeCommandsHandler = new AlternativeCommandsHandler(this);
final EssentialsPluginListener serverListener = new EssentialsPluginListener(this);
@ -182,6 +214,8 @@ public class Essentials extends JavaPlugin implements IEssentials
pm.registerEvent(Type.PLAYER_BUCKET_EMPTY, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_ANIMATION, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_CHANGED_WORLD, playerListener, Priority.Normal, this);
pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_PICKUP_ITEM, playerListener, Priority.Low, this);
pm.registerEvent(Type.PLAYER_TELEPORT, new ItemDupeFix(), Priority.Monitor, this);
final EssentialsBlockListener blockListener = new EssentialsBlockListener(this);
@ -211,16 +245,8 @@ public class Essentials extends JavaPlugin implements IEssentials
pm.registerEvent(Type.FOOD_LEVEL_CHANGE, entityListener, Priority.Lowest, this);
//TODO: Check if this should be here, and not above before reload()
jail = new Jail(this);
final JailPlayerListener jailPlayerListener = new JailPlayerListener(this);
confList.add(jail);
pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.Low, this);
pm.registerEvent(Type.BLOCK_DAMAGE, jail, Priority.Low, this);
pm.registerEvent(Type.BLOCK_PLACE, jail, Priority.Low, this);
pm.registerEvent(Type.PLAYER_INTERACT, jailPlayerListener, Priority.Low, this);
pm.registerEvent(Type.PLAYER_RESPAWN, jailPlayerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_TELEPORT, jailPlayerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_JOIN, jailPlayerListener, Priority.High, this);
jails = new Jails(this);
confList.add(jails);
pm.registerEvent(Type.ENTITY_EXPLODE, tntListener, Priority.High, this);
@ -261,11 +287,11 @@ public class Essentials extends JavaPlugin implements IEssentials
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args)
{
return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.");
return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.", null);
}
@Override
public boolean onCommandEssentials(final CommandSender sender, final Command command, final String commandLabel, final String[] args, final ClassLoader classLoader, final String commandPath, final String permissionPrefix)
public boolean onCommandEssentials(final CommandSender sender, final Command command, final String commandLabel, final String[] args, final ClassLoader classLoader, final String commandPath, final String permissionPrefix, final IEssentialsModule module)
{
// Allow plugins to override the command via onCommand
if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e"))
@ -274,7 +300,6 @@ public class Essentials extends JavaPlugin implements IEssentials
if (pc != null)
{
alternativeCommandsHandler.executed(commandLabel, pc.getLabel());
LOGGER.log(Level.FINE,"Essentials: Alternative command " + commandLabel + " found, using " + pc.getLabel());
return pc.execute(sender, commandLabel, args);
}
}
@ -309,6 +334,7 @@ public class Essentials extends JavaPlugin implements IEssentials
{
cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance();
cmd.setEssentials(this);
cmd.setEssentialsModule(module);
}
catch (Exception ex)
{
@ -369,11 +395,9 @@ public class Essentials extends JavaPlugin implements IEssentials
public void showError(final CommandSender sender, final Throwable exception, final String commandLabel)
{
sender.sendMessage(_("errorWithMessage", exception.getMessage()));
final LogRecord logRecord = new LogRecord(Level.WARNING, _("errorCallingCommand", commandLabel));
logRecord.setThrown(exception);
if (getSettings().isDebug())
{
LOGGER.log(logRecord);
LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception);
}
}
@ -384,9 +408,9 @@ public class Essentials extends JavaPlugin implements IEssentials
}
@Override
public Jail getJail()
public IJails getJails()
{
return jail;
return jails;
}
@Override
@ -407,12 +431,6 @@ public class Essentials extends JavaPlugin implements IEssentials
return backup;
}
@Override
public Spawn getSpawn()
{
return spawn;
}
@Override
public User getUser(final Object base)
{
@ -443,7 +461,9 @@ public class Essentials extends JavaPlugin implements IEssentials
if (user == null)
{
user = new User(base, this);
} else {
}
else
{
user.update(base);
}
return user;
@ -559,4 +579,10 @@ public class Essentials extends JavaPlugin implements IEssentials
{
return userMap;
}
@Override
public I18n getI18n()
{
return i18n;
}
}

View File

@ -28,69 +28,9 @@ public class EssentialsBlockListener extends BlockListener
final User user = ess.getUser(event.getPlayer());
// Do not rely on getItemInHand();
// http://leaky.bukkit.org/issues/663
final ItemStack is = new ItemStack(event.getBlockPlaced().getType(), 1, (short)0, event.getBlockPlaced().getData());
switch (is.getType())
final ItemStack is = Util.convertBlockToItem(event.getBlockPlaced());
if (is == null)
{
case WOODEN_DOOR:
is.setType(Material.WOOD_DOOR);
is.setDurability((short)0);
break;
case IRON_DOOR_BLOCK:
is.setType(Material.IRON_DOOR);
is.setDurability((short)0);
break;
case SIGN_POST:
case WALL_SIGN:
is.setType(Material.SIGN);
is.setDurability((short)0);
break;
case CROPS:
is.setType(Material.SEEDS);
is.setDurability((short)0);
break;
case CAKE_BLOCK:
is.setType(Material.CAKE);
is.setDurability((short)0);
break;
case BED_BLOCK:
is.setType(Material.BED);
is.setDurability((short)0);
break;
case REDSTONE_WIRE:
is.setType(Material.REDSTONE);
is.setDurability((short)0);
break;
case REDSTONE_TORCH_OFF:
case REDSTONE_TORCH_ON:
is.setType(Material.REDSTONE_TORCH_ON);
is.setDurability((short)0);
break;
case DIODE_BLOCK_OFF:
case DIODE_BLOCK_ON:
is.setType(Material.DIODE);
is.setDurability((short)0);
break;
case DOUBLE_STEP:
is.setType(Material.STEP);
break;
case TORCH:
case RAILS:
case LADDER:
case WOOD_STAIRS:
case COBBLESTONE_STAIRS:
case LEVER:
case STONE_BUTTON:
case FURNACE:
case DISPENSER:
case PUMPKIN:
case JACK_O_LANTERN:
case WOOD_PLATE:
case STONE_PLATE:
case PISTON_STICKY_BASE:
case PISTON_BASE:
is.setDurability((short)0);
break;
case FIRE:
return;
}
boolean unlimitedForUser = user.hasUnlimited(is);
@ -99,7 +39,7 @@ public class EssentialsBlockListener extends BlockListener
ess.scheduleSyncDelayedTask(
new Runnable()
{
@Override
@Override
public void run()
{
user.getInventory().addItem(is);

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import java.io.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@ -112,7 +111,7 @@ public class EssentialsConf extends Configuration
}
catch (RuntimeException e)
{
LOGGER.log(Level.INFO, "File: " + configFile.toString());
LOGGER.log(Level.SEVERE, "File broken: " + configFile.toString());
throw e;
}

View File

@ -1,7 +1,7 @@
package com.earth2me.essentials;
import com.earth2me.essentials.craftbukkit.EnchantmentFix;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.craftbukkit.SetBed;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput;
@ -17,8 +17,11 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.*;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
@ -115,7 +118,7 @@ public class EssentialsPlayerListener extends PlayerListener
}
if (user.getSavedInventory() != null)
{
EnchantmentFix.setContents(user.getInventory(), user.getSavedInventory());
user.getInventory().setContents(user.getSavedInventory());
user.setSavedInventory(null);
}
user.updateActivity(false);
@ -229,7 +232,14 @@ public class EssentialsPlayerListener extends PlayerListener
{
return;
}
final User user = ess.getUser(event.getPlayer());
//There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports.
if ((event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND) && ess.getSettings().registerBackInListener())
{
user.setLastLocation();
}
if (ess.getSettings().changeDisplayName())
{
user.setDisplayNick();
@ -354,4 +364,36 @@ public class EssentialsPlayerListener extends PlayerListener
}
}
}
@Override
public void onPlayerInteract(final PlayerInteractEvent event)
{
if (event.isCancelled())
{
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
{
return;
}
if (ess.getSettings().getUpdateBedAtDaytime() && event.getClickedBlock().getType() == Material.BED_BLOCK)
{
SetBed.setBed(event.getPlayer(), event.getClickedBlock());
}
}
@Override
public void onPlayerPickupItem(PlayerPickupItemEvent event)
{
if (event.isCancelled() || !ess.getSettings().getDisableItemPickupWhileAfk())
{
return;
}
final User user = ess.getUser(event.getPlayer());
if (user.isAfk())
{
event.setCancelled(true);
}
}
}

View File

@ -1,5 +1,8 @@
package com.earth2me.essentials;
import com.earth2me.essentials.craftbukkit.FakeWorld;
import com.earth2me.essentials.settings.Spawns;
import com.earth2me.essentials.storage.YamlStorageWriter;
import static com.earth2me.essentials.I18n._;
import java.io.*;
import java.math.BigInteger;
@ -681,6 +684,100 @@ public class EssentialsUpgrade
}
}
private void updateSpawnsToNewSpawnsConfig()
{
if (doneFile.getBoolean("updateSpawnsToNewSpawnsConfig", false))
{
return;
}
final File configFile = new File(ess.getDataFolder(), "spawn.yml");
if (configFile.exists())
{
final EssentialsConf config = new EssentialsConf(configFile);
try
{
config.load();
if (!config.hasProperty("spawns"))
{
final Spawns spawns = new Spawns();
List<String> keys = config.getKeys();
for (String group : keys)
{
Location loc = getFakeLocation(config, group);
spawns.getSpawns().put(group.toLowerCase(Locale.ENGLISH), loc);
}
if (!configFile.renameTo(new File(ess.getDataFolder(), "spawn.yml.old")))
{
throw new Exception(_("fileRenameError", "spawn.yml"));
}
PrintWriter writer = new PrintWriter(configFile);
try
{
new YamlStorageWriter(writer).save(spawns);
}
finally
{
writer.close();
}
}
}
catch (Exception ex)
{
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
doneFile.setProperty("updateSpawnsToNewSpawnsConfig", true);
doneFile.save();
}
private void updateJailsToNewJailsConfig()
{
if (doneFile.getBoolean("updateJailsToNewJailsConfig", false))
{
return;
}
final File configFile = new File(ess.getDataFolder(), "jail.yml");
if (configFile.exists())
{
final EssentialsConf config = new EssentialsConf(configFile);
try
{
config.load();
if (!config.hasProperty("jails"))
{
final com.earth2me.essentials.settings.Jails jails = new com.earth2me.essentials.settings.Jails();
List<String> keys = config.getKeys();
for (String jailName : keys)
{
Location loc = getFakeLocation(config, jailName);
jails.getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc);
}
if (!configFile.renameTo(new File(ess.getDataFolder(), "jail.yml.old")))
{
throw new Exception(_("fileRenameError", "jail.yml"));
}
PrintWriter writer = new PrintWriter(configFile);
try
{
new YamlStorageWriter(writer).save(jails);
}
finally
{
writer.close();
}
}
}
catch (Exception ex)
{
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
doneFile.setProperty("updateJailsToNewJailsConfig", true);
doneFile.save();
}
public void beforeSettings()
{
if (!ess.getDataFolder().exists())
@ -701,5 +798,7 @@ public class EssentialsUpgrade
updateUsersPowerToolsFormat();
updateUsersHomesFormat();
deleteOldItemsCsv();
updateSpawnsToNewSpawnsConfig();
updateJailsToNewJailsConfig();
}
}

View File

@ -1,5 +1,6 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.II18n;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@ -12,7 +13,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
public class I18n
public class I18n implements II18n
{
private static I18n instance;
private static final String MESSAGES = "messages";
@ -27,7 +28,7 @@ public class I18n
public I18n(final IEssentials ess)
{
this.ess = ess;
customBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale);
customBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
localeBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale);
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH);
}

View File

@ -1,5 +1,9 @@
package com.earth2me.essentials;
/**
* @deprecated New interface will be IReload in api package
*/
@Deprecated
public interface IConf {
public void reloadConfig();
}

View File

@ -1,5 +1,6 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IJails;
import com.earth2me.essentials.perm.PermissionsHandler;
import com.earth2me.essentials.register.payment.Methods;
import org.bukkit.World;
@ -8,17 +9,22 @@ import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitScheduler;
/**
* @deprecated This will be moved to the api package soon
*/
@Deprecated
public interface IEssentials extends Plugin
{
void addReloadListener(IConf listener);
void reload();
boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath, String permissionPrefix);
boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module);
User getUser(Object base);
I18n getI18n();
User getOfflineUser(String name);
World getWorld(String name);
@ -29,7 +35,7 @@ public interface IEssentials extends Plugin
BukkitScheduler getScheduler();
Jail getJail();
IJails getJails();
Warps getWarps();
@ -37,8 +43,6 @@ public interface IEssentials extends Plugin
Backup getBackup();
Spawn getSpawn();
Methods getPaymentMethod();
int scheduleAsyncDelayedTask(Runnable run);
@ -52,7 +56,7 @@ public interface IEssentials extends Plugin
TNTExplodeListener getTNTListener();
PermissionsHandler getPermissionsHandler();
AlternativeCommandsHandler getAlternativeCommandsHandler();
void showError(final CommandSender sender, final Throwable exception, final String commandLabel);

View File

@ -0,0 +1,6 @@
package com.earth2me.essentials;
public interface IEssentialsModule
{
}

View File

@ -5,6 +5,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.event.Event.Priority;
public interface ISettings extends IConf
@ -32,6 +33,8 @@ public interface ISettings extends IConf
String getCurrencySymbol();
int getOversizedStackSize();
int getDefaultStackSize();
double getHealCooldown();
@ -136,4 +139,16 @@ public interface ISettings extends IConf
public void setDebug(boolean debug);
Set<String> getNoGodWorlds();
boolean getUpdateBedAtDaytime();
boolean getRepairEnchanted();
boolean getIsWorldTeleportPermissions();
boolean registerBackInListener();
public boolean getDisableItemPickupWhileAfk();
public Priority getRespawnPriority();
}

View File

@ -7,6 +7,10 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;
/**
* @deprecated This will be moved to the api package soon
*/
@Deprecated
public interface IUser
{
int getHealth();
@ -56,4 +60,12 @@ public interface IUser
String getDisplayName();
boolean isHidden();
Teleport getTeleport();
void setJail(String jail);
public int getTotalExperience();
public void setTotalExperience(int l);
}

View File

@ -1,5 +1,6 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IItemDb;
import static com.earth2me.essentials.I18n._;
import java.util.HashMap;
import java.util.List;
@ -9,7 +10,7 @@ import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class ItemDb implements IConf
public class ItemDb implements IConf, IItemDb
{
private final transient IEssentials ess;

View File

@ -1,100 +0,0 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPlaceEvent;
public class Jail extends BlockListener implements IConf
{
private static final Logger logger = Logger.getLogger("Minecraft");
private final EssentialsConf config;
private final IEssentials ess;
public Jail(IEssentials ess)
{
this.ess = ess;
config = new EssentialsConf(new File(ess.getDataFolder(), "jail.yml"));
config.load();
}
public void setJail(Location loc, String jailName) throws Exception
{
config.setProperty(jailName.toLowerCase(Locale.ENGLISH), loc);
config.save();
}
public Location getJail(String jailName) throws Exception
{
if (jailName == null || config.getProperty(jailName.toLowerCase(Locale.ENGLISH)) == null)
{
throw new Exception(_("jailNotExist"));
}
Location loc = config.getLocation(jailName.toLowerCase(Locale.ENGLISH), ess.getServer());
return loc;
}
public void sendToJail(User user, String jail) throws Exception
{
if (!(user.getBase() instanceof OfflinePlayer))
{
user.getTeleport().now(getJail(jail));
}
user.setJail(jail);
}
public void delJail(String jail) throws Exception
{
config.removeProperty(jail.toLowerCase(Locale.ENGLISH));
config.save();
}
public List<String> getJails() throws Exception
{
return config.getKeys(null);
}
@Override
public void reloadConfig()
{
config.load();
}
@Override
public void onBlockBreak(BlockBreakEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
@Override
public void onBlockPlace(BlockPlaceEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
@Override
public void onBlockDamage(BlockDamageEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
}

View File

@ -1,81 +0,0 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.event.player.*;
public class JailPlayerListener extends PlayerListener
{
private static final Logger LOGGER = Logger.getLogger("Minecraft");
private final IEssentials ess;
public JailPlayerListener(IEssentials parent)
{
this.ess = parent;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
@Override
public void onPlayerRespawn(PlayerRespawnEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed() && user.getJail() != null && !user.getJail().isEmpty())
{
try
{
event.setRespawnLocation(ess.getJail().getJail(user.getJail()));
}
catch (Exception ex)
{
}
}
}
@Override
public void onPlayerTeleport(PlayerTeleportEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
{
return;
}
try
{
event.setTo(ess.getJail().getJail(user.getJail()));
}
catch (Exception ex)
{
LOGGER.log(Level.WARNING, _("returnPlayerToJailError"), ex);
}
user.sendMessage(_("jailMessage"));
}
@Override
public void onPlayerJoin(final PlayerJoinEvent event)
{
User u = ess.getUser(event.getPlayer());
if (u.isJailed())
{
try
{
ess.getJail().sendToJail(u, u.getJail());
}
catch (Exception ex)
{
LOGGER.log(Level.WARNING, _("returnPlayerToJailError"), ex);
}
u.sendMessage(_("jailMessage"));
}
}
}

View File

@ -0,0 +1,248 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IJails;
import com.earth2me.essentials.storage.AsyncStorageObjectHolder;
import static com.earth2me.essentials.I18n._;
import java.io.File;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.event.block.*;
import org.bukkit.event.player.*;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.plugin.PluginManager;
public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Jails> implements IJails
{
private static final transient Logger LOGGER = Bukkit.getLogger();
public Jails(final IEssentials ess)
{
super(ess, com.earth2me.essentials.settings.Jails.class);
reloadConfig();
registerListeners();
}
private void registerListeners()
{
final PluginManager pluginManager = ess.getServer().getPluginManager();
final JailBlockListener blockListener = new JailBlockListener();
final JailPlayerListener playerListener = new JailPlayerListener();
pluginManager.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Low, ess);
pluginManager.registerEvent(Type.BLOCK_DAMAGE, blockListener, Priority.Low, ess);
pluginManager.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Low, ess);
pluginManager.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.Low, ess);
pluginManager.registerEvent(Type.PLAYER_RESPAWN, playerListener, Priority.High, ess);
pluginManager.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, ess);
pluginManager.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.High, ess);
}
@Override
public File getStorageFile()
{
return new File(ess.getDataFolder(), "jail.yml");
}
@Override
public Location getJail(final String jailName) throws Exception
{
acquireReadLock();
try
{
if (getData().getJails() == null || jailName == null
|| !getData().getJails().containsKey(jailName.toLowerCase(Locale.ENGLISH)))
{
throw new Exception(_("jailNotExist"));
}
return getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH));
}
finally
{
unlock();
}
}
@Override
public Collection<String> getList() throws Exception
{
acquireReadLock();
try
{
if (getData().getJails() == null)
{
return Collections.emptyList();
}
return new ArrayList<String>(getData().getJails().keySet());
}
finally
{
unlock();
}
}
@Override
public void removeJail(final String jail) throws Exception
{
acquireWriteLock();
try
{
if (getData().getJails() == null)
{
return;
}
getData().getJails().remove(jail.toLowerCase(Locale.ENGLISH));
}
finally
{
unlock();
}
}
@Override
public void sendToJail(final IUser user, final String jail) throws Exception
{
acquireReadLock();
try
{
if (!(user.getBase() instanceof OfflinePlayer))
{
user.getTeleport().now(getJail(jail), false, TeleportCause.COMMAND);
}
user.setJail(jail);
}
finally
{
unlock();
}
}
@Override
public void setJail(final String jailName, final Location loc) throws Exception
{
acquireWriteLock();
try
{
if (getData().getJails() == null)
{
getData().setJails(new HashMap<String, Location>());
}
getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc);
}
finally
{
unlock();
}
}
private class JailBlockListener extends BlockListener
{
@Override
public void onBlockBreak(final BlockBreakEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
@Override
public void onBlockPlace(final BlockPlaceEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
@Override
public void onBlockDamage(final BlockDamageEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
}
private class JailPlayerListener extends PlayerListener
{
@Override
public void onPlayerInteract(final PlayerInteractEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
@Override
public void onPlayerRespawn(final PlayerRespawnEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
{
return;
}
try
{
event.setRespawnLocation(getJail(user.getJail()));
}
catch (Exception ex)
{
LOGGER.log(Level.WARNING, _("returnPlayerToJailError"), ex);
}
}
@Override
public void onPlayerTeleport(final PlayerTeleportEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
{
return;
}
try
{
event.setTo(getJail(user.getJail()));
}
catch (Exception ex)
{
LOGGER.log(Level.WARNING, _("returnPlayerToJailError"), ex);
}
user.sendMessage(_("jailMessage"));
}
@Override
public void onPlayerJoin(final PlayerJoinEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
{
return;
}
try
{
sendToJail(user, user.getJail());
}
catch (Exception ex)
{
LOGGER.log(Level.WARNING, _("returnPlayerToJailError"), ex);
}
user.sendMessage(_("jailMessage"));
}
}
}

View File

@ -1,10 +1,10 @@
package com.earth2me.essentials;
import com.earth2me.essentials.craftbukkit.OfflineBedLocation;
import static com.earth2me.essentials.I18n._;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import lombok.Delegate;
@ -12,6 +12,7 @@ import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.map.MapView;
@ -741,7 +742,7 @@ public class OfflinePlayer implements Player
@Override
public Location getBedSpawnLocation()
{
throw new UnsupportedOperationException("Not supported yet.");
return OfflineBedLocation.getBedLocation(base.getName(), ess);
}
@Override
@ -785,4 +786,34 @@ public class OfflinePlayer implements Player
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void giveExp(int i)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public float getExp()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setExp(float f)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean teleport(Location lctn, TeleportCause tc)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean teleport(Entity entity, TeleportCause tc)
{
throw new UnsupportedOperationException("Not supported yet.");
}
}

View File

@ -3,16 +3,11 @@ package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.commands.IEssentialsCommand;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.event.Event.Priority;
import org.bukkit.inventory.ItemStack;
@ -36,6 +31,12 @@ public class Settings implements ISettings
return config.getBoolean("respawn-at-home", false);
}
@Override
public boolean getUpdateBedAtDaytime()
{
return config.getBoolean("update-bed-at-daytime", true);
}
@Override
public List<String> getMultipleHomes()
{
@ -87,6 +88,12 @@ public class Settings implements ISettings
return config.getInt("oversized-stacksize", 64);
}
@Override
public int getDefaultStackSize()
{
return config.getInt("default-stack-size", -1);
}
@Override
public int getStartingBalance()
{
@ -332,7 +339,7 @@ public class Settings implements ISettings
public void reloadConfig()
{
config.load();
noGodWorlds = new HashSet<String>(config.getStringList("no-god-in-worlds",Collections.<String>emptyList()));
noGodWorlds = new HashSet<String>(config.getStringList("no-god-in-worlds", Collections.<String>emptyList()));
}
@Override
@ -535,13 +542,12 @@ public class Settings implements ISettings
{
return config.getBoolean("death-messages", true);
}
Set <String> noGodWorlds = new HashSet<String>();
Set<String> noGodWorlds = new HashSet<String>();
@Override
public Set<String> getNoGodWorlds()
{
return noGodWorlds;
}
@Override
@ -549,4 +555,55 @@ public class Settings implements ISettings
{
this.debug = debug;
}
@Override
public boolean getRepairEnchanted()
{
return config.getBoolean("repair-enchanted", true);
}
@Override
public boolean getIsWorldTeleportPermissions()
{
return config.getBoolean("world-teleport-permissions", false);
}
@Override
public boolean registerBackInListener()
{
return config.getBoolean("register-back-in-listener", false);
}
@Override
public boolean getDisableItemPickupWhileAfk()
{
return config.getBoolean("disable-item-pickup-while-afk", true);
}
@Override
public Priority getRespawnPriority()
{
String priority = config.getString("respawn-listener-priority", "normal").toLowerCase(Locale.ENGLISH);
if ("lowest".equals(priority))
{
return Priority.Lowest;
}
if ("low".equals(priority))
{
return Priority.Low;
}
if ("normal".equals(priority))
{
return Priority.Normal;
}
if ("high".equals(priority))
{
return Priority.High;
}
if ("highest".equals(priority))
{
return Priority.Highest;
}
return Priority.Normal;
}
}

View File

@ -1,103 +0,0 @@
package com.earth2me.essentials;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.World.Environment;
public class Spawn implements IConf
{
private static final Logger logger = Logger.getLogger("Minecraft");
private final EssentialsConf config;
private final Server server;
public Spawn(Server server, File dataFolder)
{
File configFile = new File(dataFolder, "spawn.yml");
this.server = server;
config = new EssentialsConf(configFile);
config.load();
}
public void setSpawn(Location loc, String group)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("world", loc.getWorld().getName());
map.put("x", loc.getX());
map.put("y", loc.getY());
map.put("z", loc.getZ());
map.put("yaw", loc.getYaw());
map.put("pitch", loc.getPitch());
config.setProperty(group, map);
config.save();
if ("default".equals(group))
{
loc.getWorld().setSpawnLocation(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
}
public Location getSpawn(String group)
{
if (config.getProperty(group) == null)
{
group = "default";
}
if (config.getProperty(group) == null)
{
for (World w : server.getWorlds())
{
if (w.getEnvironment() != Environment.NORMAL)
{
continue;
}
return w.getSpawnLocation();
}
}
String worldId = config.getString(group + ".world", "");
World world = server.getWorlds().get(server.getWorlds().size() > 1 ? 1 : 0);
for (World w : server.getWorlds())
{
if (w.getEnvironment() != Environment.NORMAL)
{
continue;
}
world = w;
break;
}
for (World w : server.getWorlds())
{
if (!w.getName().equals(worldId))
{
continue;
}
world = w;
break;
}
double x = config.getDouble(group + ".x", config.getDouble("default.x", 0));
double y = config.getDouble(group + ".y", config.getDouble("default.y", 0));
double z = config.getDouble(group + ".z", config.getDouble("default.z", 0));
float yaw = (float)config.getDouble(group + ".yaw", config.getDouble("default.yaw", 0));
float pitch = (float)config.getDouble(group + ".pitch", config.getDouble("default.pitch", 0));
Location retval = new Location(world, x, y, z, yaw, pitch);
if (y < 1)
{
retval.setY(world.getHighestBlockYAt(retval));
}
return retval;
}
@Override
public void reloadConfig()
{
config.load();
}
}

View File

@ -1,527 +0,0 @@
package com.earth2me.essentials;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
/**
* Original authors: toi & Raphfrk
*/
@Deprecated
public class TargetBlock
{
private transient final Location location;
private transient final double viewHeight;
private transient final int maxDistance;
private transient final int[] blockToIgnore;
private transient final double checkDistance;
private transient double curDistance;
private transient double targetPositionX;
private transient double targetPositionY;
private transient double targetPositionZ;
private transient int itargetPositionX;
private transient int itargetPositionY;
private transient int itargetPositionZ;
private transient int prevPositionX;
private transient int prevPositionY;
private transient int prevPositionZ;
private transient final double offsetX;
private transient final double offsetY;
private transient final double offsetZ;
/**
* Constructor requiring a player, uses default values
*
* @param player Player to work with
*/
public TargetBlock(final Player player)
{
this(player.getLocation(), 300, 1.65, 0.2, null);
}
/**
* Constructor requiring a location, uses default values
*
* @param loc Location to work with
*/
public TargetBlock(final Location loc)
{
this(loc, 300, 0, 0.2, null);
}
/**
* Constructor requiring a player, max distance and a checking distance
*
* @param player Player to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
*/
public TargetBlock(final Player player, final int maxDistance, final double checkDistance)
{
this(player.getLocation(), maxDistance, 1.65, checkDistance, null);
}
/**
* Constructor requiring a location, max distance and a checking distance
*
* @param loc What location to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
*/
public TargetBlock(final Location loc, final int maxDistance, final double checkDistance)
{
this(loc, maxDistance, 0, checkDistance, null);
}
/**
* Constructor requiring a player, max distance, checking distance and an array of blocks to ignore
*
* @param player What player to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore Integer array of what block ids to ignore while checking for viable targets
*/
public TargetBlock(final Player player, final int maxDistance, final double checkDistance, final int[] blocksToIgnore)
{
this(player.getLocation(), maxDistance, 1.65, checkDistance, blocksToIgnore);
}
/**
* Constructor requiring a location, max distance, checking distance and an array of blocks to ignore
*
* @param loc What location to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore Array of what block ids to ignore while checking for viable targets
*/
public TargetBlock(final Location loc, final int maxDistance, final double checkDistance, final int[] blocksToIgnore)
{
this(loc, maxDistance, 0, checkDistance, blocksToIgnore);
}
/**
* Constructor requiring a player, max distance, checking distance and an array of blocks to ignore
*
* @param player What player to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore String ArrayList of what block ids to ignore while checking for viable targets
*/
public TargetBlock(final Player player, final int maxDistance, final double checkDistance, final List<String> blocksToIgnore)
{
this(player.getLocation(), maxDistance, 1.65, checkDistance, TargetBlock.convertStringArraytoIntArray(blocksToIgnore));
}
/**
* Constructor requiring a location, max distance, checking distance and an array of blocks to ignore
*
* @param loc What location to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore String ArrayList of what block ids to ignore while checking for viable targets
*/
public TargetBlock(final Location loc, final int maxDistance, final double checkDistance, final List<String> blocksToIgnore)
{
this(loc, maxDistance, 0, checkDistance, TargetBlock.convertStringArraytoIntArray(blocksToIgnore));
}
/**
* Set the values, all constructors uses this function
*
* @param loc Location of the view
* @param maxDistance How far it checks for blocks
* @param viewPos Where the view is positioned in y-axis
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore Ids of blocks to ignore while checking for viable targets
*/
private TargetBlock(final Location loc, final int maxDistance, final double viewHeight, final double checkDistance, final int[] blocksToIgnore)
{
this.location = loc;
this.maxDistance = maxDistance;
this.viewHeight = viewHeight;
this.checkDistance = checkDistance;
if (blocksToIgnore == null || blocksToIgnore.length == 0)
{
this.blockToIgnore = new int[0];
}
else
{
this.blockToIgnore = new int[blocksToIgnore.length];
System.arraycopy(blocksToIgnore, 0, this.blockToIgnore, 0, this.blockToIgnore.length);
}
final double xRotation = (loc.getYaw() + 90) % 360;
final double yRotation = loc.getPitch() * -1;
final double hypotenuse = (checkDistance * Math.cos(Math.toRadians(yRotation)));
offsetX = hypotenuse * Math.cos(Math.toRadians(xRotation));
offsetY = checkDistance * Math.sin(Math.toRadians(yRotation));
offsetZ = hypotenuse * Math.sin(Math.toRadians(xRotation));
reset();
}
/**
* Call this to reset checking position to allow you to check for a new target with the same TargetBlock instance.
*/
public final void reset()
{
targetPositionX = location.getX();
targetPositionY = location.getY() + viewHeight;
targetPositionZ = location.getZ();
itargetPositionX = (int)Math.floor(targetPositionX);
itargetPositionY = (int)Math.floor(targetPositionY);
itargetPositionZ = (int)Math.floor(targetPositionZ);
prevPositionX = itargetPositionX;
prevPositionY = itargetPositionY;
prevPositionZ = itargetPositionZ;
this.curDistance = 0;
}
/**
* Gets the distance to a block. Measures from the block underneath the player to the targetblock
* Should only be used when passing player as an constructor parameter
*
* @return double
*/
public double getDistanceToBlock()
{
final double blockUnderPlayerX = Math.floor(location.getX() + 0.5);
final double blockUnderPlayerY = Math.floor(location.getY() - 0.5);
final double blockUnderPlayerZ = Math.floor(location.getZ() + 0.5);
final Block block = getTargetBlock();
final double distX = block.getX() - blockUnderPlayerX;
final double distY = block.getY() - blockUnderPlayerY;
final double distZ = block.getZ() - blockUnderPlayerZ;
return Math.sqrt(distX*distX + distY*distY + distZ*distZ);
}
/**
* Gets the rounded distance to a block. Measures from the block underneath the player to the targetblock
* Should only be used when passing player as an constructor parameter
*
* @return int
*/
public int getDistanceToBlockRounded()
{
return (int)Math.round(getDistanceToBlock());
}
/**
* Gets the floored x distance to a block.
*
* @return int
*/
public int getXDistanceToBlock()
{
return (int)Math.floor(getTargetBlock().getX() - location.getBlockX() + 0.5);
}
/**
* Gets the floored y distance to a block
*
* @return int
*/
public int getYDistanceToBlock()
{
return (int)Math.floor(getTargetBlock().getY() - location.getBlockY() + viewHeight);
}
/**
* Gets the floored z distance to a block
*
* @return int
*/
public int getZDistanceToBlock()
{
return (int)Math.floor(getTargetBlock().getZ() - location.getBlockZ() + 0.5);
}
/**
* Returns the block at the sight. Returns null if out of range or if no viable target was found
*
* @return Block
*/
public Block getTargetBlock()
{
this.reset();
Block block;
do
{
block = getNextBlock();
}
while (block != null && ((block.getTypeId() == 0) || this.blockIsIgnored(block.getTypeId())));
return block;
}
/**
* Sets the type of the block at the sight. Returns false if the block wasn't set.
*
* @param typeID ID of type to set the block to
* @return boolean
*/
public boolean setTargetBlock(final int typeID)
{
return setTargetBlock(Material.getMaterial(typeID));
}
/**
* Sets the type of the block at the sight. Returns false if the block wasn't set.
*
* @param type Material to set the block to
* @return boolean
*/
@SuppressWarnings("empty-statement")
public boolean setTargetBlock(final Material type)
{
if (type == null)
{
return false;
}
final Block block = getTargetBlock();
if (block != null)
{
block.setType(type);
return true;
}
return false;
}
/**
* Sets the type of the block at the sight. Returns false if the block wasn't set.
* Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented
*
* @param type Name of type to set the block to
* @return boolean
*/
public boolean setTargetBlock(final String type)
{
return setTargetBlock(Material.valueOf(type));
}
/**
* Returns the block attached to the face at the sight. Returns null if out of range or if no viable target was found
*
* @return Block
*/
public Block getFaceBlock()
{
final Block block = getTargetBlock();
if (block == null)
{
return null;
}
return getPreviousBlock();
}
/**
* Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set.
*
* @param typeID
* @return boolean
*/
public boolean setFaceBlock(final int typeID)
{
return setFaceBlock(Material.getMaterial(typeID));
}
/**
* Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set.
*
* @param type
* @return boolean
*/
public boolean setFaceBlock(final Material type)
{
if (type == null)
{
return false;
}
if (getCurrentBlock() != null)
{
final Block blk = location.getWorld().getBlockAt(prevPositionX, prevPositionY, prevPositionZ);
blk.setType(type);
return true;
}
return false;
}
/**
* Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set.
* Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented
*
* @param type
* @return boolean
*/
public boolean setFaceBlock(final String type)
{
return setFaceBlock(Material.valueOf(type));
}
/**
* Get next block
*
* @return Block
*/
public Block getNextBlock()
{
prevPositionX = itargetPositionX;
prevPositionY = itargetPositionY;
prevPositionZ = itargetPositionZ;
do
{
curDistance += checkDistance;
targetPositionX += offsetX;
targetPositionY += offsetY;
targetPositionZ += offsetZ;
itargetPositionX = (int)Math.floor(targetPositionX);
itargetPositionY = (int)Math.floor(targetPositionY);
itargetPositionZ = (int)Math.floor(targetPositionZ);
}
while (curDistance <= maxDistance && itargetPositionX == prevPositionX && itargetPositionY == prevPositionY && itargetPositionZ == prevPositionZ);
if (curDistance > maxDistance)
{
return null;
}
return this.location.getWorld().getBlockAt(itargetPositionX, itargetPositionY, itargetPositionZ);
}
/**
* Returns the current block along the line of vision
*
* @return Block
*/
public Block getCurrentBlock()
{
Block block;
if (curDistance <= maxDistance)
{
block = this.location.getWorld().getBlockAt(itargetPositionX, itargetPositionY, itargetPositionZ);
}
else
{
block = null;
}
return block;
}
/**
* Sets current block type. Returns false if the block wasn't set.
*
* @param typeID
*/
public boolean setCurrentBlock(final int typeID)
{
return setCurrentBlock(Material.getMaterial(typeID));
}
/**
* Sets current block type. Returns false if the block wasn't set.
*
* @param type
*/
public boolean setCurrentBlock(final Material type)
{
final Block blk = getCurrentBlock();
if (blk != null && type != null)
{
blk.setType(type);
return true;
}
return false;
}
/**
* Sets current block type. Returns false if the block wasn't set.
* Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented
*
* @param type
*/
public boolean setCurrentBlock(final String type)
{
return setCurrentBlock(Material.valueOf(type));
}
/**
* Returns the previous block in the aimed path
*
* @return Block
*/
public Block getPreviousBlock()
{
return this.location.getWorld().getBlockAt(prevPositionX, prevPositionY, prevPositionZ);
}
/**
* Sets previous block type id. Returns false if the block wasn't set.
*
* @param typeID
*/
public boolean setPreviousBlock(final int typeID)
{
return setPreviousBlock(Material.getMaterial(typeID));
}
/**
* Sets previous block type id. Returns false if the block wasn't set.
*
* @param type
*/
public boolean setPreviousBlock(final Material type)
{
final Block blk = getPreviousBlock();
if (blk != null && type != null)
{
blk.setType(type);
return true;
}
return false;
}
/**
* Sets previous block type id. Returns false if the block wasn't set.
* Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented
*
* @param type
*/
public boolean setPreviousBlock(final String type)
{
return setPreviousBlock(Material.valueOf(type));
}
private static int[] convertStringArraytoIntArray(final List<String> array)
{
final int intarray[] = new int[array == null ? 0 : array.size()];
for (int i = 0; i < intarray.length; i++)
{
try
{
intarray[i] = Integer.parseInt(array.get(i));
}
catch (NumberFormatException nfe)
{
}
}
return intarray;
}
private boolean blockIsIgnored(final int value)
{
for (int i : this.blockToIgnore)
{
if (i == value)
{
return true;
}
}
return false;
}
}

View File

@ -1,5 +1,6 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.ITeleport;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import java.util.Calendar;
@ -7,9 +8,12 @@ import java.util.GregorianCalendar;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Teleport implements Runnable
public class Teleport implements Runnable, ITeleport
{
private static final double MOVE_CONSTANT = 0.3;
@ -55,8 +59,9 @@ public class Teleport implements Runnable
private Trade chargeFor;
private final IEssentials ess;
private static final Logger logger = Logger.getLogger("Minecraft");
private TeleportCause cause;
private void initTimer(long delay, Target target, Trade chargeFor)
private void initTimer(long delay, Target target, Trade chargeFor, TeleportCause cause)
{
this.started = System.currentTimeMillis();
this.delay = delay;
@ -66,6 +71,7 @@ public class Teleport implements Runnable
this.initZ = Math.round(user.getLocation().getZ() * MOVE_CONSTANT);
this.teleportTarget = target;
this.chargeFor = chargeFor;
this.cause = cause;
}
@Override
@ -98,7 +104,7 @@ public class Teleport implements Runnable
try
{
now(teleportTarget);
now(teleportTarget, cause);
if (chargeFor != null)
{
chargeFor.charge(user);
@ -122,15 +128,19 @@ public class Teleport implements Runnable
this.ess = ess;
}
public void respawn(Spawn spawn, Trade chargeFor) throws Exception
public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception
{
teleport(new Target(spawn.getSpawn(user.getGroup())), chargeFor);
final Player player = user.getBase();
final Location bed = player.getBedSpawnLocation();
final PlayerRespawnEvent pre = new PlayerRespawnEvent(player, bed == null ? player.getWorld().getSpawnLocation() : bed, bed != null);
ess.getServer().getPluginManager().callEvent(pre);
teleport(new Target(pre.getRespawnLocation()), chargeFor, cause);
}
public void warp(String warp, Trade chargeFor) throws Exception
public void warp(String warp, Trade chargeFor, TeleportCause cause) throws Exception
{
Location loc = ess.getWarps().getWarp(warp);
teleport(new Target(loc), chargeFor);
teleport(new Target(loc), chargeFor, cause);
user.sendMessage(_("warpingTo", warp));
}
@ -180,18 +190,23 @@ public class Teleport implements Runnable
{
cancel(false);
}
public void teleport(Location loc, Trade chargeFor) throws Exception
{
teleport(new Target(loc), chargeFor);
teleport(new Target(loc), chargeFor, TeleportCause.PLUGIN);
}
public void teleport(Entity entity, Trade chargeFor) throws Exception
public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception
{
teleport(new Target(entity), chargeFor);
teleport(new Target(loc), chargeFor, cause);
}
private void teleport(Target target, Trade chargeFor) throws Exception
public void teleport(Entity entity, Trade chargeFor, TeleportCause cause) throws Exception
{
teleport(new Target(entity), chargeFor, cause);
}
private void teleport(Target target, Trade chargeFor, TeleportCause cause) throws Exception
{
double delay = ess.getSettings().getTeleportDelay();
@ -203,7 +218,7 @@ public class Teleport implements Runnable
if (delay <= 0 || user.isAuthorized("essentials.teleport.timer.bypass"))
{
cooldown(false);
now(target);
now(target, cause);
if (chargeFor != null)
{
chargeFor.charge(user);
@ -216,48 +231,51 @@ public class Teleport implements Runnable
c.add(Calendar.SECOND, (int)delay);
c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0));
user.sendMessage(_("dontMoveMessage", Util.formatDateDiff(c.getTimeInMillis())));
initTimer((long)(delay * 1000.0), target, chargeFor);
initTimer((long)(delay * 1000.0), target, chargeFor, cause);
teleTimer = ess.scheduleSyncRepeatingTask(this, 10, 10);
}
private void now(Target target) throws Exception
private void now(Target target, TeleportCause cause) throws Exception
{
cancel();
user.setLastLocation();
user.getBase().teleport(Util.getSafeDestination(target.getLocation()));
user.getBase().teleport(Util.getSafeDestination(target.getLocation()), cause);
}
public void now(Location loc) throws Exception
{
cooldown(false);
now(new Target(loc));
}
public void now(Location loc, Trade chargeFor) throws Exception
{
cooldown(false);
chargeFor.charge(user);
now(new Target(loc));
}
public void now(Entity entity, boolean cooldown) throws Exception
public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception
{
if (cooldown)
{
cooldown(false);
}
now(new Target(entity));
now(new Target(loc), cause);
}
public void now(Location loc, Trade chargeFor, TeleportCause cause) throws Exception
{
cooldown(false);
chargeFor.charge(user);
now(new Target(loc), cause);
}
public void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception
{
if (cooldown)
{
cooldown(false);
}
now(new Target(entity), cause);
}
public void back(Trade chargeFor) throws Exception
{
teleport(new Target(user.getLastLocation()), chargeFor);
teleport(new Target(user.getLastLocation()), chargeFor, TeleportCause.COMMAND);
}
public void back() throws Exception
{
now(new Target(user.getLastLocation()));
now(new Target(user.getLastLocation()), TeleportCause.COMMAND);
}
public void home(IUser user, String home, Trade chargeFor) throws Exception
@ -267,6 +285,6 @@ public class Teleport implements Runnable
{
throw new NotEnoughArgumentsException();
}
teleport(new Target(loc), chargeFor);
teleport(new Target(loc), chargeFor, TeleportCause.COMMAND);
}
}

View File

@ -1,5 +1,6 @@
package com.earth2me.essentials;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import static com.earth2me.essentials.I18n._;
import java.io.File;
import java.io.FileWriter;
@ -19,28 +20,35 @@ public class Trade
private final transient String command;
private final transient Double money;
private final transient ItemStack itemStack;
private final transient Integer exp;
private final transient IEssentials ess;
public Trade(final String command, final IEssentials ess)
{
this(command, null, null, ess);
this(command, null, null, null, ess);
}
public Trade(final double money, final IEssentials ess)
{
this(null, money, null, ess);
this(null, money, null, null, ess);
}
public Trade(final ItemStack items, final IEssentials ess)
{
this(null, null, items, ess);
this(null, null, items, null, ess);
}
public Trade(final int exp, final IEssentials ess)
{
this(null, null, null, exp, ess);
}
private Trade(final String command, final Double money, final ItemStack item, final IEssentials ess)
private Trade(final String command, final Double money, final ItemStack item, final Integer exp, final IEssentials ess)
{
this.command = command;
this.money = money;
this.itemStack = item;
this.exp = exp;
this.ess = ess;
}
@ -56,7 +64,7 @@ public class Trade
}
if (getItemStack() != null
&& !InventoryWorkaround.containsItem(user.getInventory(), true, itemStack))
&& !InventoryWorkaround.containsItem(user.getInventory(), true, true, itemStack))
{
throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
}
@ -70,6 +78,11 @@ public class Trade
{
throw new ChargeException(_("notEnoughMoney"));
}
if (exp != null && exp > 0
&& user.getTotalExperience() < exp) {
throw new ChargeException(_("notEnoughExperience"));
}
}
public void pay(final IUser user)
@ -100,6 +113,10 @@ public class Trade
}
user.updateInventory();
}
if (getExperience() != null)
{
user.setTotalExperience(user.getTotalExperience() + getExperience());
}
return success;
}
@ -116,11 +133,11 @@ public class Trade
}
if (getItemStack() != null)
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, itemStack))
if (!InventoryWorkaround.containsItem(user.getInventory(), true, true, itemStack))
{
throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
}
InventoryWorkaround.removeItem(user.getInventory(), true, getItemStack());
InventoryWorkaround.removeItem(user.getInventory(), true, true, getItemStack());
user.updateInventory();
}
if (command != null && !command.isEmpty()
@ -135,6 +152,15 @@ public class Trade
}
user.takeMoney(cost);
}
if (getExperience() != null)
{
final int experience = user.getTotalExperience();
if (experience < getExperience() && getExperience() > 0)
{
throw new ChargeException(_("notEnoughExperience"));
}
user.setTotalExperience(experience - getExperience());
}
}
public Double getMoney()
@ -146,6 +172,11 @@ public class Trade
{
return itemStack;
}
public Integer getExperience()
{
return exp;
}
private static FileWriter fw = null;
public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess)
@ -192,6 +223,12 @@ public class Trade
sb.append("money").append(",");
sb.append(ess.getSettings().getCurrencySymbol());
}
if (charge.getExperience() != null)
{
sb.append(charge.getExperience()).append(",");
sb.append("exp").append(",");
sb.append("\"\"");
}
}
sb.append(",\"");
if (receiver != null)
@ -217,6 +254,12 @@ public class Trade
sb.append("money").append(",");
sb.append(ess.getSettings().getCurrencySymbol());
}
if (pay.getExperience() != null)
{
sb.append(pay.getExperience()).append(",");
sb.append("exp").append(",");
sb.append("\"\"");
}
}
if (loc == null)
{

View File

@ -468,10 +468,11 @@ public class User extends UserData implements Comparable<User>, IReplyTo, IUser
public void checkActivity()
{
final long autoafkkick = ess.getSettings().getAutoAfkKick();
if (autoafkkick > 0 && lastActivity + autoafkkick * 1000 < System.currentTimeMillis()
if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
&& !isHidden() && !isAuthorized("essentials.kick.exempt") && !isAuthorized("essentials.afk.kickexempt"))
{
final String kickReason = _("autoAfkKickReason", autoafkkick / 60.0);
lastActivity = 0;
kickPlayer(kickReason);

View File

@ -3,15 +3,13 @@ package com.earth2me.essentials;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.collect.ConcurrentHashMultiset;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.io.File;
import java.util.Collections;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.entity.Player;
@ -19,7 +17,7 @@ public class UserMap extends CacheLoader<String, User> implements IConf
{
private final transient IEssentials ess;
private final transient Cache<String, User> users = CacheBuilder.newBuilder().softValues().build(this);
private final transient ConcurrentHashMultiset<String> keys = ConcurrentHashMultiset.create();
private final transient ConcurrentSkipListSet<String> keys = new ConcurrentSkipListSet<String>();
public UserMap(final IEssentials ess)
{
@ -87,8 +85,7 @@ public class UserMap extends CacheLoader<String, User> implements IConf
return new User(player, ess);
}
}
final File userFolder = new File(ess.getDataFolder(), "userdata");
final File userFile = new File(userFolder, Util.sanitizeFileName(name) + ".yml");
final File userFile = getUserFile(name);
if (userFile.exists())
{
keys.add(name.toLowerCase(Locale.ENGLISH));
@ -111,11 +108,17 @@ public class UserMap extends CacheLoader<String, User> implements IConf
public Set<String> getAllUniqueUsers()
{
return Collections.unmodifiableSet(keys.elementSet());
return Collections.unmodifiableSet(keys);
}
public int getUniqueUsers()
{
return keys.size();
}
public File getUserFile(final String name)
{
final File userFolder = new File(ess.getDataFolder(), "userdata");
return new File(userFolder, Util.sanitizeFileName(name) + ".yml");
}
}

View File

@ -12,6 +12,7 @@ import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;
public class Util
@ -331,6 +332,88 @@ public class Util
}
return isBlockAboveAir(world, x, y, z);
}
public static ItemStack convertBlockToItem(final Block block)
{
final ItemStack is = new ItemStack(block.getType(), 1, (short)0, block.getData());
switch (is.getType())
{
case WOODEN_DOOR:
is.setType(Material.WOOD_DOOR);
is.setDurability((short)0);
break;
case IRON_DOOR_BLOCK:
is.setType(Material.IRON_DOOR);
is.setDurability((short)0);
break;
case SIGN_POST:
case WALL_SIGN:
is.setType(Material.SIGN);
is.setDurability((short)0);
break;
case CROPS:
is.setType(Material.SEEDS);
is.setDurability((short)0);
break;
case CAKE_BLOCK:
is.setType(Material.CAKE);
is.setDurability((short)0);
break;
case BED_BLOCK:
is.setType(Material.BED);
is.setDurability((short)0);
break;
case REDSTONE_WIRE:
is.setType(Material.REDSTONE);
is.setDurability((short)0);
break;
case REDSTONE_TORCH_OFF:
case REDSTONE_TORCH_ON:
is.setType(Material.REDSTONE_TORCH_ON);
is.setDurability((short)0);
break;
case DIODE_BLOCK_OFF:
case DIODE_BLOCK_ON:
is.setType(Material.DIODE);
is.setDurability((short)0);
break;
case DOUBLE_STEP:
is.setType(Material.STEP);
break;
case TORCH:
case RAILS:
case LADDER:
case WOOD_STAIRS:
case COBBLESTONE_STAIRS:
case LEVER:
case STONE_BUTTON:
case FURNACE:
case DISPENSER:
case PUMPKIN:
case JACK_O_LANTERN:
case WOOD_PLATE:
case STONE_PLATE:
case PISTON_STICKY_BASE:
case PISTON_BASE:
case IRON_FENCE:
case THIN_GLASS:
case TRAP_DOOR:
case FENCE:
case FENCE_GATE:
case NETHER_FENCE:
is.setDurability((short)0);
break;
case FIRE:
return null;
case PUMPKIN_STEM:
is.setType(Material.PUMPKIN_SEEDS);
break;
case MELON_STEM:
is.setType(Material.MELON_SEEDS);
break;
}
return is;
}
private static DecimalFormat df = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US));
public static String formatCurrency(final double value, final IEssentials ess)

View File

@ -0,0 +1,10 @@
package com.earth2me.essentials.api;
import java.util.Map;
import org.bukkit.command.PluginCommand;
public interface IAlternativeCommandsHandler
{
Map<String, String> disabledCommands();
}

View File

@ -0,0 +1,51 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.perm.IPermissionsHandler;
import com.earth2me.essentials.register.payment.Methods;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
public interface IEssentials extends Plugin, IReload
{
void addReloadListener(IReload listener);
IUser getUser(Object base);
int broadcastMessage(IUser sender, String message);
II18n getI18n();
ISettings getSettings();
IJails getJail();
IWarps getWarps();
IWorth getWorth();
IItemDb getItemDb();
IUserMap getUserMap();
IEssentialsEconomy getEconomy();
World getWorld(String name);
Methods getPaymentMethod();
int scheduleAsyncDelayedTask(Runnable run);
int scheduleSyncDelayedTask(Runnable run);
int scheduleSyncDelayedTask(Runnable run, long delay);
int scheduleSyncRepeatingTask(Runnable run, long delay, long period);
IPermissionsHandler getPermissionsHandler();
IAlternativeCommandsHandler getAlternativeCommandsHandler();
void showCommandError(CommandSender sender, String commandLabel, Throwable exception);
}

View File

@ -0,0 +1,37 @@
package com.earth2me.essentials.api;
public interface IEssentialsEconomy
{
double getMoney(String name) throws UserDoesNotExistException;
void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException;
void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException;
void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException;
void divide(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException;
void multiply(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException;
void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException;
boolean hasEnough(String name, double amount) throws UserDoesNotExistException;
boolean hasMore(String name, double amount) throws UserDoesNotExistException;
boolean hasLess(String name, double amount) throws UserDoesNotExistException;
boolean isNegative(String name) throws UserDoesNotExistException;
String format(double amount);
boolean playerExists(String name);
boolean isNPC(String name) throws UserDoesNotExistException;
boolean createNPC(String name);
void removeNPC(String name) throws UserDoesNotExistException;
}

View File

@ -0,0 +1,9 @@
package com.earth2me.essentials.api;
import java.util.Locale;
public interface II18n
{
Locale getCurrentLocale();
}

View File

@ -0,0 +1,11 @@
package com.earth2me.essentials.api;
import org.bukkit.inventory.ItemStack;
public interface IItemDb
{
ItemStack get(final String name, final int quantity) throws Exception;
ItemStack get(final String name) throws Exception;
}

View File

@ -0,0 +1,18 @@
package com.earth2me.essentials.api;
import java.util.Collection;
import org.bukkit.Location;
public interface IJails extends IReload
{
Location getJail(String jailName) throws Exception;
Collection<String> getList() throws Exception;
void removeJail(String jail) throws Exception;
void sendToJail(com.earth2me.essentials.IUser user, String jail) throws Exception;
void setJail(String jailName, Location loc) throws Exception;
}

View File

@ -0,0 +1,7 @@
package com.earth2me.essentials.api;
public interface IReload
{
void onReload();
}

View File

@ -0,0 +1,10 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.settings.Settings;
import com.earth2me.essentials.storage.IStorageObjectHolder;
public interface ISettings extends IStorageObjectHolder<Settings>
{
}

View File

@ -0,0 +1,10 @@
package com.earth2me.essentials.api;
import org.bukkit.Location;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public interface ITeleport
{
void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception;
}

View File

@ -0,0 +1,43 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.commands.IEssentialsCommand;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public interface IUser extends Player, IReload
{
long getLastTeleportTimestamp();
boolean isAuthorized(String node);
boolean isAuthorized(IEssentialsCommand cmd);
boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix);
void setLastTeleportTimestamp(long time);
Location getLastLocation();
Player getBase();
double getMoney();
void takeMoney(double value);
void giveMoney(double value);
String getGroup();
void setLastLocation();
Location getHome(String name) throws Exception;
Location getHome(Location loc) throws Exception;
boolean isHidden();
ITeleport getTeleport();
void setJail(String jail);
}

View File

@ -0,0 +1,20 @@
package com.earth2me.essentials.api;
import java.io.File;
import java.util.Set;
public interface IUserMap
{
boolean userExists(final String name);
IUser getUser(final String name);
void removeUser(final String name);
Set<String> getAllUniqueUsers();
int getUniqueUsers();
File getUserFile(final String name);
}

View File

@ -0,0 +1,16 @@
package com.earth2me.essentials.api;
import java.util.Collection;
import org.bukkit.Location;
public interface IWarps extends IReload
{
Location getWarp(String warp) throws Exception;
Collection<String> getWarps();
void removeWarp(String name) throws Exception;
void setWarp(String name, Location loc) throws Exception;
}

View File

@ -0,0 +1,11 @@
package com.earth2me.essentials.api;
import org.bukkit.inventory.ItemStack;
public interface IWorth extends IReload
{
double getPrice(ItemStack itemStack);
void setPrice(ItemStack itemStack, double price);
}

View File

@ -3,6 +3,9 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Util;
import com.earth2me.essentials.textreader.ArrayListInput;
import com.earth2me.essentials.textreader.TextPager;
import java.text.DateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@ -16,38 +19,39 @@ public class Commandbalancetop extends EssentialsCommand
{
super("balancetop");
}
private static final int CACHETIME = 5 * 60 * 1000;
private static final int CACHETIME = 2 * 60 * 1000;
public static final int MINUSERS = 50;
private static List<String> cache = new ArrayList<String>();
private static ArrayListInput cache = new ArrayListInput();
private static long cacheage = 0;
private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
@Override
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
int max = 10;
int page = 0;
boolean force = false;
if (args.length > 0)
{
try
{
if (Integer.parseInt(args[0]) < 19)
{
max = Integer.parseInt(args[0]);
}
page = Integer.parseInt(args[0]);
}
catch (NumberFormatException ex)
{
//catch it because they tried to enter a string not number.
if (args[0].equalsIgnoreCase("force") && sender.isOp())
{
force = true;
}
}
}
if (lock.readLock().tryLock())
if (!force && lock.readLock().tryLock())
{
try
{
if (cacheage > System.currentTimeMillis() - CACHETIME)
{
outputCache(sender, max);
outputCache(sender, page);
return;
}
if (ess.getUserMap().getUniqueUsers() > MINUSERS)
@ -59,7 +63,7 @@ public class Commandbalancetop extends EssentialsCommand
{
lock.readLock().unlock();
}
ess.scheduleAsyncDelayedTask(new Viewer(sender, max));
ess.scheduleAsyncDelayedTask(new Viewer(sender, page, force));
}
else
{
@ -67,33 +71,30 @@ public class Commandbalancetop extends EssentialsCommand
{
sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers()));
}
ess.scheduleAsyncDelayedTask(new Viewer(sender, max));
ess.scheduleAsyncDelayedTask(new Viewer(sender, page, force));
}
}
private static void outputCache(final CommandSender sender, int max)
private static void outputCache(final CommandSender sender, int page)
{
sender.sendMessage(_("balanceTop", max));
for (String line : cache)
{
if (max == 0)
{
break;
}
max--;
sender.sendMessage(line);
}
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cacheage);
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
sender.sendMessage(_("balanceTop", format.format(cal.getTime())));
new TextPager(cache).showPage(Integer.toString(page), "", "balancetop", sender);
}
private class Calculator implements Runnable
{
private final transient Viewer viewer;
private final boolean force;
public Calculator(final Viewer viewer)
public Calculator(final Viewer viewer, final boolean force)
{
this.viewer = viewer;
this.force = force;
}
@Override
@ -102,8 +103,9 @@ public class Commandbalancetop extends EssentialsCommand
lock.writeLock().lock();
try
{
if (cacheage < System.currentTimeMillis() - 5 * 60 * 1000)
if (force || cacheage <= System.currentTimeMillis() - CACHETIME)
{
cache.getLines().clear();
final Map<String, Double> balances = new HashMap<String, Double>();
for (String u : ess.getUserMap().getAllUniqueUsers())
{
@ -123,15 +125,11 @@ public class Commandbalancetop extends EssentialsCommand
return -entry1.getValue().compareTo(entry2.getValue());
}
});
int count = 0;
int pos = 1;
for (Map.Entry<String, Double> entry : sortedEntries)
{
if (count == 20)
{
break;
}
cache.add(entry.getKey() + ", " + Util.formatCurrency(entry.getValue(), ess));
count++;
cache.getLines().add(pos + ". " + entry.getKey() + ", " + Util.formatCurrency(entry.getValue(), ess));
pos++;
}
cacheage = System.currentTimeMillis();
}
@ -148,12 +146,14 @@ public class Commandbalancetop extends EssentialsCommand
private class Viewer implements Runnable
{
private final transient CommandSender sender;
private final transient int max;
private final transient int page;
private final transient boolean force;
public Viewer(final CommandSender sender, final int max)
public Viewer(final CommandSender sender, final int page, final boolean force)
{
this.sender = sender;
this.max = max;
this.page = page;
this.force = force;
}
@Override
@ -162,9 +162,9 @@ public class Commandbalancetop extends EssentialsCommand
lock.readLock().lock();
try
{
if (cacheage > System.currentTimeMillis() - 5 * 60 * 1000)
if (!force && cacheage > System.currentTimeMillis() - CACHETIME)
{
outputCache(sender, max);
outputCache(sender, page);
return;
}
}
@ -172,7 +172,7 @@ public class Commandbalancetop extends EssentialsCommand
{
lock.readLock().unlock();
}
ess.scheduleAsyncDelayedTask(new Calculator(new Viewer(sender, max)));
ess.scheduleAsyncDelayedTask(new Calculator(new Viewer(sender, page, force), force));
}
}
}

View File

@ -0,0 +1,44 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.event.block.BlockBreakEvent;
public class Commandbreak extends EssentialsCommand
{
public Commandbreak()
{
super("break");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final Block block = user.getTargetBlock(null, 20);
if (block == null)
{
throw new NoChargeException();
}
if (block.getType() == Material.AIR)
{
throw new NoChargeException();
}
if (block.getType() == Material.BEDROCK && !user.isAuthorized("essentials.break.bedrock"))
{
throw new Exception("You are not allowed to destroy bedrock."); //TODO: Translation
}
final BlockBreakEvent event = new BlockBreakEvent(block, user);
server.getPluginManager().callEvent(event);
if (event.isCancelled())
{
throw new NoChargeException();
}
else
{
block.setType(Material.AIR);
}
}
}

View File

@ -0,0 +1,149 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Mob;
import static com.earth2me.essentials.I18n._;
import java.util.Collections;
import org.bukkit.Chunk;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Animals;
import org.bukkit.entity.ComplexLivingEntity;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Flying;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.NPC;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Snowman;
import org.bukkit.entity.WaterMob;
import org.bukkit.entity.Wolf;
import org.bukkit.event.entity.EntityDeathEvent;
public class Commandbutcher extends EssentialsCommand
{
public Commandbutcher()
{
super("butcher");
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
String type = "all";
int radius = -1;
World world;
if (sender instanceof Player)
{
world = ((Player)sender).getWorld();
if (args.length == 1)
{
try
{
radius = Integer.parseInt(args[0]);
}
catch (NumberFormatException e1)
{
type = args[0];
}
}
else if (args.length > 1)
{
type = args[0];
try
{
radius = Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
throw new Exception(_("numberRequired"));
}
}
}
else
{
if (args.length == 0)
{
throw new NotEnoughArgumentsException();
}
else if (args.length == 1)
{
world = ess.getWorld(args[0]);
}
else
{
type = args[0];
world = ess.getWorld(args[1]);
}
}
if (radius >=0) {
radius *= radius;
}
String killType = type.toLowerCase();
int numKills = 0;
for (Chunk chunk : world.getLoadedChunks())
{
for (Entity entity : chunk.getEntities())
{
if (sender instanceof Player)
{
if (((Player)sender).getLocation().distanceSquared(entity.getLocation()) > radius && radius >= 0)
{
continue;
}
}
if (entity instanceof LivingEntity == false || entity instanceof HumanEntity)
{
continue;
}
if (entity instanceof Wolf)
{
if (((Wolf)entity).isTamed())
{
continue;
}
}
if (killType.contains("animal"))
{
if (entity instanceof Animals || entity instanceof NPC || entity instanceof Snowman || entity instanceof WaterMob)
{
EntityDeathEvent event = new EntityDeathEvent(entity, Collections.EMPTY_LIST);
ess.getServer().getPluginManager().callEvent(event);
entity.remove();
numKills++;
}
}
else if (killType.contains("monster"))
{
if (entity instanceof Monster || entity instanceof ComplexLivingEntity || entity instanceof Flying || entity instanceof Slime)
{
EntityDeathEvent event = new EntityDeathEvent(entity, Collections.EMPTY_LIST);
ess.getServer().getPluginManager().callEvent(event);
entity.remove();
numKills++;
}
}
else if (killType.contains("all"))
{
EntityDeathEvent event = new EntityDeathEvent(entity, Collections.EMPTY_LIST);
ess.getServer().getPluginManager().callEvent(event);
entity.remove();
numKills++;
}
else
{
if (Mob.fromName(killType).getType().getEntityClass().isAssignableFrom(entity.getClass()))
{
EntityDeathEvent event = new EntityDeathEvent(entity, Collections.EMPTY_LIST);
ess.getServer().getPluginManager().callEvent(event);
entity.remove();
numKills++;
}
}
}
}
sender.sendMessage(_("kill", numKills));
}
}

View File

@ -19,7 +19,7 @@ public class Commanddeljail extends EssentialsCommand
{
throw new NotEnoughArgumentsException();
}
ess.getJail().delJail(args[0]);
ess.getJails().removeJail(args[0]);
sender.sendMessage(_("deleteJail", args[0]));
}
}

View File

@ -1,73 +1,22 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Enchantments;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import com.earth2me.essentials.craftbukkit.EnchantmentFix;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.*;
import org.bukkit.Server;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import static com.earth2me.essentials.I18n._;
public class Commandenchant extends EssentialsCommand
{
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>();
private static final transient Pattern NUMPATTERN = Pattern.compile("\\d+");
static
{
ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD);
ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD);
ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED);
ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED);
ENCHANTMENTS.put("durability", Enchantment.DURABILITY);
ENCHANTMENTS.put("dura", Enchantment.DURABILITY);
ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY);
ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT);
ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT);
ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK);
ENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS);
ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS);
ENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("oxygen", Enchantment.OXYGEN);
ENCHANTMENTS.put("respiration", Enchantment.OXYGEN);
ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL);
ENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL);
ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE);
ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE);
ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE);
ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE);
ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH);
ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER);
ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER);
}
public Commandenchant()
{
super("enchant");
}
//TODO: Implement charge costs: final Trade charge = new Trade("enchant-" + enchantmentName, ess);
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
@ -80,7 +29,7 @@ public class Commandenchant extends EssentialsCommand
if (args.length == 0)
{
final Set<String> enchantmentslist = new TreeSet<String>();
for (Map.Entry<String, Enchantment> entry : ENCHANTMENTS.entrySet())
for (Map.Entry<String, Enchantment> entry : Enchantments.entrySet())
{
final String enchantmentName = entry.getValue().getName().toLowerCase(Locale.ENGLISH);
if (enchantmentslist.contains(enchantmentName) || user.isAuthorized("essentials.enchant." + enchantmentName))
@ -103,39 +52,36 @@ public class Commandenchant extends EssentialsCommand
level = -1;
}
}
Enchantment enchantment = getEnchantment(args[0], user);
final Enchantment enchantment = getEnchantment(args[0], user);
if (level < 0 || level > enchantment.getMaxLevel())
{
level = enchantment.getMaxLevel();
}
if (level == 0) {
if (level == 0)
{
stack.removeEnchantment(enchantment);
} else {
}
else
{
stack.addEnchantment(enchantment, level);
}
EnchantmentFix.setItemInHand(user.getInventory(), stack);
user.getInventory().setItemInHand(stack);
user.updateInventory();
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
if (level == 0) {
if (level == 0)
{
user.sendMessage(_("enchantmentRemoved", enchantmentName.replace('_', ' ')));
} else {
}
else
{
user.sendMessage(_("enchantmentApplied", enchantmentName.replace('_', ' ')));
}
}
public static Enchantment getEnchantment(final String name, final User user) throws Exception
{
Enchantment enchantment;
if (NUMPATTERN.matcher(name).matches()) {
enchantment = Enchantment.getById(Integer.parseInt(name));
} else {
enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH));
}
if (enchantment == null)
{
enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH));
}
final Enchantment enchantment = Enchantments.getByName(name);
if (enchantment == null)
{
throw new Exception(_("enchantmentNotFound"));

View File

@ -44,7 +44,7 @@ public class Commandessentials extends EssentialsCommand
{
sender.sendMessage("Essentials " + ess.getDescription().getVersion());
sender.sendMessage("/<command> <reload/debug>");
sender.sendMessage("Essentials blocked the following commands, due to command conflicts:");
sender.sendMessage(_("blockList"));
final StringBuilder disabledCommands = new StringBuilder();
for (Map.Entry<String, String> entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet())
{

View File

@ -0,0 +1,52 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import java.util.List;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandfeed extends EssentialsCommand
{
public Commandfeed()
{
super("feed");
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length > 0 && user.isAuthorized("essentials.feed.others"))
{
feedOtherPlayers(server,user,args[0]);
}
else
{
user.setFoodLevel(20);
user.setSaturation(10);
user.sendMessage(_("feed"));
}
}
private void feedOtherPlayers(final Server server, final CommandSender sender, final String name)
{
final List<Player> players = server.matchPlayer(name);
if (players.isEmpty())
{
sender.sendMessage(_("playerNotFound"));
return;
}
for (Player player : players)
{
if (ess.getUser(player).isHidden())
{
continue;
}
player.setFoodLevel(20);
player.setSaturation(10);
sender.sendMessage(_("feedOther", player.getDisplayName()));
}
}
}

View File

@ -30,7 +30,7 @@ public class Commandgamemode extends EssentialsCommand
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length > 0 && user.isAuthorized("essentials.gamemode.others"))
if (args.length > 0 && !args[0].trim().isEmpty() && user.isAuthorized("essentials.gamemode.others"))
{
gamemodeOtherPlayers(server, user, args[0]);
return;

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
public class Commandgetpos extends EssentialsCommand
@ -11,15 +12,44 @@ public class Commandgetpos extends EssentialsCommand
{
super("getpos");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final Location coords = user.getLocation();
user.sendMessage("§7X: " + coords.getBlockX() + " (+East <-> -West)");
user.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)");
user.sendMessage("§7Z: " + coords.getBlockZ() + " (+South <-> -North)");
user.sendMessage("§7Yaw: " + (coords.getYaw() + 180 + 360) % 360 + " (Rotation)");
user.sendMessage("§7Pitch: " + coords.getPitch() + " (Head angle)");
if (args.length > 0 && user.isAuthorized("essentials.getpos.others"))
{
final User otherUser = getPlayer(server, args, 0);
outputPosition(user, otherUser.getLocation(), user.getLocation());
}
else
{
outputPosition(user, user.getLocation(), null);
}
}
@Override
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
final User user = getPlayer(server, args, 0);
outputPosition(sender, user.getLocation(), null);
}
//TODO: Translate
private void outputPosition(final CommandSender sender, final Location coords, final Location distance)
{
sender.sendMessage("§7World: " + coords.getWorld().getName());
sender.sendMessage("§7X: " + coords.getBlockX() + " (+East <-> -West)");
sender.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)");
sender.sendMessage("§7Z: " + coords.getBlockZ() + " (+South <-> -North)");
sender.sendMessage("§7Yaw: " + (coords.getYaw() + 180 + 360) % 360 + " (Rotation)");
sender.sendMessage("§7Pitch: " + coords.getPitch() + " (Head angle)");
if (distance != null && coords.getWorld().equals(distance.getWorld()))
{
sender.sendMessage("§7Distance: " + coords.distance(distance));
}
}
}

View File

@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.InventoryWorkaround;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.User;
import java.util.Locale;
import org.bukkit.ChatColor;
@ -41,10 +41,21 @@ public class Commandgive extends EssentialsCommand
{
throw new Exception(ChatColor.RED + "You are not allowed to spawn the item " + itemname);
}
final User giveTo = getPlayer(server, args, 0);
if (args.length > 2 && Integer.parseInt(args[2]) > 0)
{
stack.setAmount(Integer.parseInt(args[2]));
}
else if (ess.getSettings().getDefaultStackSize() > 0)
{
stack.setAmount(ess.getSettings().getDefaultStackSize());
}
else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks"))
{
stack.setAmount(ess.getSettings().getOversizedStackSize());
}
if (args.length > 3)
{
@ -74,12 +85,14 @@ public class Commandgive extends EssentialsCommand
throw new Exception(ChatColor.RED + "You can't give air.");
}
final User giveTo = getPlayer(server, args, 0);
final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + ".");
if (giveTo.isAuthorized("essentials.oversizedstacks")) {
if (giveTo.isAuthorized("essentials.oversizedstacks"))
{
InventoryWorkaround.addItem(giveTo.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack);
} else {
}
else
{
InventoryWorkaround.addItem(giveTo.getInventory(), true, stack);
}
giveTo.updateInventory();

View File

@ -28,7 +28,7 @@ public class Commandgod extends EssentialsCommand
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length > 0 && user.isAuthorized("essentials.god.others"))
if (args.length > 0 && !args[0].trim().isEmpty() && user.isAuthorized("essentials.god.others"))
{
godOtherPlayers(server, user, args[0]);
return;

View File

@ -8,6 +8,7 @@ import java.util.List;
import java.util.Locale;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandhome extends EssentialsCommand
@ -43,11 +44,13 @@ public class Commandhome extends EssentialsCommand
}
try
{
if ("bed".equalsIgnoreCase(homeName)) {
if ("bed".equalsIgnoreCase(homeName))
{
final Location bed = player.getBedSpawnLocation();
if (bed != null)
{
user.getTeleport().teleport(bed, charge);
user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND);
return;
}
}
user.getTeleport().home(player, homeName.toLowerCase(Locale.ENGLISH), charge);
@ -57,18 +60,14 @@ public class Commandhome extends EssentialsCommand
final List<String> homes = player.getHomes();
if (homes.isEmpty() && player.equals(user))
{
final Location loc = player.getBedSpawnLocation();
if (loc == null)
final Location bed = player.getBedSpawnLocation();
if (bed != null)
{
if (ess.getSettings().spawnIfNoHome())
{
user.getTeleport().respawn(ess.getSpawn(), charge);
}
}
else
{
user.getTeleport().teleport(loc, charge);
user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND);
return;
}
user.getTeleport().respawn(charge, TeleportCause.COMMAND);
return;
}
else if (homes.isEmpty())
{
@ -77,6 +76,7 @@ public class Commandhome extends EssentialsCommand
else if (homes.size() == 1 && player.equals(user))
{
user.getTeleport().home(player, homes.get(0), charge);
return;
}
else
{

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.EnchantmentFix;
import java.util.Arrays;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
@ -30,7 +29,7 @@ public class Commandinvsee extends EssentialsCommand
}
if (invUser == user && user.getSavedInventory() != null)
{
EnchantmentFix.setContents(invUser.getInventory(), user.getSavedInventory());
invUser.getInventory().setContents(user.getSavedInventory());
user.setSavedInventory(null);
user.sendMessage(_("invRestored"));
throw new NoChargeException();
@ -50,7 +49,7 @@ public class Commandinvsee extends EssentialsCommand
{
throw new Exception(_("invBigger"));
}
EnchantmentFix.setContents(user.getInventory(), invUserStack);
user.getInventory().setContents(invUserStack);
user.sendMessage(_("invSee", invUser.getDisplayName()));
user.sendMessage(_("invSeeHelp"));
throw new NoChargeException();

View File

@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.InventoryWorkaround;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import java.util.Locale;
@ -41,6 +41,14 @@ public class Commanditem extends EssentialsCommand
{
stack.setAmount(Integer.parseInt(args[1]));
}
else if (ess.getSettings().getDefaultStackSize() > 0)
{
stack.setAmount(ess.getSettings().getDefaultStackSize());
}
else if (ess.getSettings().getOversizedStackSize() > 0 && user.isAuthorized("essentials.oversizedstacks"))
{
stack.setAmount(ess.getSettings().getOversizedStackSize());
}
if (args.length > 2)
{
@ -72,9 +80,12 @@ public class Commanditem extends EssentialsCommand
final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
user.sendMessage(_("itemSpawn", stack.getAmount(), displayName));
if (user.isAuthorized("essentials.oversizedstacks")) {
if (user.isAuthorized("essentials.oversizedstacks"))
{
InventoryWorkaround.addItem(user.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack);
} else {
}
else
{
InventoryWorkaround.addItem(user.getInventory(), true, stack);
}
user.updateInventory();

View File

@ -0,0 +1,37 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class Commanditemdb extends EssentialsCommand
{
public Commanditemdb()
{
super("find");
}
@Override
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
ItemStack itemStack = null;
if (args.length < 1)
{
if (sender instanceof Player)
{
itemStack = ((Player)sender).getItemInHand();
}
if (itemStack == null)
{
throw new NotEnoughArgumentsException();
}
}
else
{
itemStack = ess.getItemDb().get(args[0]);
}
sender.sendMessage(itemStack.getType().toString() + "- " + itemStack.getTypeId() + ":" + Integer.toString(itemStack.getData().getData()));
}
}

View File

@ -15,6 +15,6 @@ public class Commandjails extends EssentialsCommand
@Override
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
sender.sendMessage("§7" + Util.joinList(" ", ess.getJail().getJails()));
sender.sendMessage("§7" + Util.joinList(" ", ess.getJails().getList()));
}
}

View File

@ -1,11 +1,12 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.TargetBlock;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandjump extends EssentialsCommand
@ -15,7 +16,6 @@ public class Commandjump extends EssentialsCommand
super("jump");
}
//TODO: Update to use new target methods
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
@ -24,10 +24,7 @@ public class Commandjump extends EssentialsCommand
try
{
loc = new TargetBlock(user, 100, 2.65).getTargetBlock().getLocation();
loc.setYaw(cloc.getYaw());
loc.setPitch(cloc.getPitch());
loc = new TargetBlock(loc).getPreviousBlock().getLocation();
loc = Util.getTarget(user);
loc.setYaw(cloc.getYaw());
loc.setPitch(cloc.getPitch());
loc.setY(loc.getY() + 1);
@ -39,6 +36,6 @@ public class Commandjump extends EssentialsCommand
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
user.getTeleport().teleport(loc, charge);
user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND);
}
}

View File

@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.InventoryWorkaround;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
@ -114,7 +114,15 @@ public class Commandkit extends EssentialsCommand
final int id = Material.getMaterial(Integer.parseInt(parts[0])).getId();
final int amount = parts.length > 1 ? Integer.parseInt(parts[parts.length > 2 ? 2 : 1]) : 1;
final short data = parts.length > 2 ? Short.parseShort(parts[1]) : 0;
final Map<Integer, ItemStack> overfilled = InventoryWorkaround.addItem(user.getInventory(), true, new ItemStack(id, amount, data));
final Map<Integer, ItemStack> overfilled;
if (user.isAuthorized("essentials.oversizedstacks"))
{
overfilled = InventoryWorkaround.addItem(user.getInventory(), true, ess.getSettings().getOversizedStackSize(), new ItemStack(id, amount, data));
}
else
{
overfilled = InventoryWorkaround.addItem(user.getInventory(), true, new ItemStack(id, amount, data));
}
for (ItemStack itemStack : overfilled.values())
{
user.getWorld().dropItemNaturally(user.getLocation(), itemStack);

View File

@ -4,6 +4,7 @@ import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.LightningStrike;
import org.bukkit.entity.Player;
@ -34,10 +35,30 @@ public class Commandlightning extends EssentialsCommand
throw new Exception(_("playerNotFound"));
}
int power = 1;
if (args.length > 1)
{
try
{
power = Integer.parseInt(args[1]);
}
catch (NumberFormatException ex)
{
}
}
for (Player matchPlayer : server.matchPlayer(args[0]))
{
sender.sendMessage(_("lightningUse", matchPlayer.getDisplayName()));
matchPlayer.getWorld().strikeLightning(matchPlayer.getLocation());
if (power <= 0)
{
matchPlayer.getWorld().strikeLightningEffect(matchPlayer.getLocation());
}
else
{
LightningStrike strike = matchPlayer.getWorld().strikeLightning(matchPlayer.getLocation());
matchPlayer.damage(power - 1, strike);
}
if (!ess.getUser(matchPlayer).isGodModeEnabled())
{
matchPlayer.setHealth(matchPlayer.getHealth() < 5 ? 0 : matchPlayer.getHealth() - 5);

View File

@ -39,7 +39,7 @@ public class Commandmail extends EssentialsCommand
{
if (!user.isAuthorized("essentials.mail.send"))
{
throw new Exception(_("noMailSendPerm"));
throw new Exception(_("noPerm","essentials.mail.send"));
}
Player player = server.getPlayer(args[1]);
@ -63,6 +63,16 @@ public class Commandmail extends EssentialsCommand
user.sendMessage(_("mailSent"));
return;
}
if (args.length > 1 && "sendall".equalsIgnoreCase(args[0]))
{
if (!user.isAuthorized("essentials.mail.sendall"))
{
throw new Exception(_("noPerm","essentials.mail.sendall"));
}
ess.scheduleAsyncDelayedTask(new SendAll(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 1)));
user.sendMessage(_("mailSent"));
return;
}
if (args.length >= 1 && "clear".equalsIgnoreCase(args[0]))
{
user.setMails(null);
@ -103,6 +113,10 @@ public class Commandmail extends EssentialsCommand
sender.sendMessage(_("mailSent"));
return;
}
else if (args.length >= 1 && "sendall".equalsIgnoreCase(args[0]))
{
ess.scheduleAsyncDelayedTask(new SendAll("Server: " + getFinalArg(args, 2)));
}
else if (args.length >= 2)
{
//allow sending from console without "send" argument, since it's the only thing the console can do
@ -126,4 +140,28 @@ public class Commandmail extends EssentialsCommand
}
throw new NotEnoughArgumentsException();
}
private class SendAll implements Runnable
{
String message;
public SendAll(String message)
{
this.message = message;
}
@Override
public void run()
{
for (String username : ess.getUserMap().getAllUniqueUsers())
{
User user = ess.getUserMap().getUser(username);
if (user != null)
{
user.addMail(message);
}
}
}
}
}

View File

@ -0,0 +1,50 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import java.util.Locale;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
public class Commandmore extends EssentialsCommand
{
public Commandmore()
{
super("more");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final ItemStack stack = user.getItemInHand();
if (stack == null)
{
throw new Exception(_("cantSpawnItem", "Air"));
}
if (stack.getAmount() >= ((user.isAuthorized("essentials.oversizedstacks"))
? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize()))
{
throw new NoChargeException();
}
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (ess.getSettings().permissionBasedItemSpawn()
? (!user.isAuthorized("essentials.itemspawn.item-all")
&& !user.isAuthorized("essentials.itemspawn.item-" + itemname)
&& !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId()))
: (!user.isAuthorized("essentials.itemspawn.exempt")
&& !user.canSpawnItem(stack.getTypeId())))
{
throw new Exception(_("cantSpawnItem", itemname));
}
if (user.isAuthorized("essentials.oversizedstacks"))
{
stack.setAmount(ess.getSettings().getOversizedStackSize());
}
else
{
stack.setAmount(stack.getMaxStackSize());
}
user.updateInventory();
}
}

View File

@ -0,0 +1,120 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandnear extends EssentialsCommand
{
public Commandnear()
{
super("near");
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
long radius = 100;
User otherUser = null;
if (args.length > 0)
{
try
{
otherUser = getPlayer(server, args, 0);
}
catch (Exception ex)
{
try
{
radius = Long.parseLong(args[0]);
}
catch (NumberFormatException e)
{
}
}
}
if (args.length > 1 && otherUser != null)
{
try
{
radius = Long.parseLong(args[1]);
}
catch (NumberFormatException e)
{
}
}
if (otherUser == null || user.isAuthorized("essentials.near.others"))
{
user.sendMessage(_("nearbyPlayers", getLocal(server, otherUser == null ? user : otherUser, radius)));
}
else
{
user.sendMessage(_("noAccessCommand"));
}
}
@Override
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
User otherUser = null;
if (args.length > 0)
{
otherUser = getPlayer(server, args, 0);
}
else
{
throw new NotEnoughArgumentsException();
}
long radius = 100;
if (args.length > 1)
{
try
{
radius = Long.parseLong(args[1]);
}
catch (NumberFormatException e)
{
}
}
sender.sendMessage(_("nearbyPlayers", getLocal(server, otherUser, radius)));
}
private String getLocal(final Server server, final User user, final long radius)
{
final Location loc = user.getLocation();
final World world = loc.getWorld();
final StringBuilder output = new StringBuilder();
final long radiusSquared = radius * radius;
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User player = ess.getUser(onlinePlayer);
if (!player.equals(user) && !player.isHidden())
{
final Location playerLoc = player.getLocation();
if (playerLoc.getWorld() != world)
{
continue;
}
final long delta = (long)playerLoc.distanceSquared(loc);
if (delta < radiusSquared)
{
if (output.length() > 0)
{
output.append(", ");
}
output.append(player.getDisplayName()).append("§f(§4").append(Math.sqrt(delta)).append("m§f)");
}
}
}
return output.length() > 1 ? output.toString() : _("none");
}
}

View File

@ -50,7 +50,14 @@ public class Commandnick extends EssentialsCommand
{
throw new Exception(_("nickDisplayName"));
}
setNickname(server, getPlayer(server, args, 0), formatNickname(null, args[1]));
if ((args[0].equalsIgnoreCase("*") || args[0].equalsIgnoreCase("all")) && args[1].equalsIgnoreCase("off"))
{
resetAllNicknames(server);
}
else
{
setNickname(server, getPlayer(server, args, 0), formatNickname(null, args[1]));
}
sender.sendMessage(_("nickChanged"));
}
@ -63,6 +70,20 @@ public class Commandnick extends EssentialsCommand
return nick;
}
private void resetAllNicknames(final Server server)
{
for (Player player : server.getOnlinePlayers())
{
try
{
setNickname(server, ess.getUser(player), "off");
}
catch (Exception ex)
{
}
}
}
private void setNickname(final Server server, final User target, final String nick) throws Exception
{
if (nick.matches("[^a-zA-Z_0-9]"))

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.entity.Player;
@ -32,6 +33,7 @@ public class Commandpay extends EssentialsCommand
continue;
}
user.payUser(u, amount);
Trade.log("Command", "Pay", "Player", user.getName(), new Trade(amount, ess), u.getName(), new Trade(amount, ess), user.getLocation(), ess);
foundUser = true;
}

View File

@ -17,18 +17,18 @@ public class Commandr extends EssentialsCommand
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
String message = getFinalArg(args, 0);
IReplyTo replyTo = sender instanceof Player ? ess.getUser((Player)sender) : Console.getConsoleReplyTo();
String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
CommandSender target = replyTo.getReplyTo();
String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME;
final String message = getFinalArg(args, 0);
final IReplyTo replyTo = sender instanceof Player ? ess.getUser((Player)sender) : Console.getConsoleReplyTo();
final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
final CommandSender target = replyTo.getReplyTo();
final String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME;
if (target == null)
{
@ -38,8 +38,8 @@ public class Commandr extends EssentialsCommand
sender.sendMessage(_("msgFormat", _("me"), targetName, message));
if (target instanceof Player)
{
User u = ess.getUser(target);
if (u.isIgnoredPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME))
User player = ess.getUser(target);
if (player.isIgnoredPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME))
{
return;
}

View File

@ -17,16 +17,16 @@ public class Commandrealname extends EssentialsCommand
}
@Override
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
final String whois = args[0].toLowerCase(Locale.ENGLISH);
for (Player p : server.getOnlinePlayers())
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User u = ess.getUser(p);
final User u = ess.getUser(onlinePlayer);
if (u.isHidden())
{
continue;

View File

@ -0,0 +1,161 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import java.util.Locale;
import org.bukkit.Chunk;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.*;
public class Commandremove extends EssentialsCommand
{
public Commandremove()
{
super("remove");
}
private enum ToRemove
{
DROPS,
ARROWS,
BOATS,
MINECARTS,
XP,
PAINTINGS
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
ToRemove toRemove;
final World world = user.getWorld();
int radius = 0;
if (args.length < 2)
{
try
{
radius = Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
throw new Exception(_("numberRequired"));
}
}
try
{
toRemove = ToRemove.valueOf(args[0].toUpperCase(Locale.ENGLISH));
}
catch (IllegalArgumentException e)
{
throw new NotEnoughArgumentsException(); //TODO: translate and list types
}
removeEntities(user, world, toRemove, radius);
}
@Override
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
World world;
world = ess.getWorld(args[1]);
if (world == null)
{
throw new Exception(_("invalidWorld"));
}
ToRemove toRemove;
try
{
toRemove = ToRemove.valueOf(args[0].toUpperCase(Locale.ENGLISH));
}
catch (IllegalArgumentException e)
{
throw new NotEnoughArgumentsException(); //TODO: translate and list types
}
removeEntities(sender, world, toRemove, 0);
}
protected void removeEntities(final CommandSender sender, final World world, final ToRemove toRemove, int radius) throws Exception
{
int removed = 0;
if (radius > 0) {
radius*=radius;
}
for (Chunk chunk : world.getLoadedChunks())
{
for (Entity e : chunk.getEntities())
{
if (radius > 0)
{
if (((Player)sender).getLocation().distanceSquared(e.getLocation()) > radius)
{
continue;
}
}
if (toRemove == ToRemove.DROPS)
{
if (e instanceof Item)
{
e.remove();
removed++;
}
}
else if (toRemove == ToRemove.ARROWS)
{
if (e instanceof Projectile)
{
e.remove();
removed++;
}
}
else if (toRemove == ToRemove.BOATS)
{
if (e instanceof Boat)
{
e.remove();
removed++;
}
}
else if (toRemove == ToRemove.DROPS)
{
if (e instanceof Minecart)
{
e.remove();
removed++;
}
}
else if (toRemove == ToRemove.XP)
{
if (e instanceof ExperienceOrb)
{
e.remove();
removed++;
}
}
else if (toRemove == ToRemove.PAINTINGS)
{
if (e instanceof Painting)
{
e.remove();
removed++;
}
}
}
}
sender.sendMessage(_("removed", removed));
}
}

View File

@ -32,6 +32,14 @@ public class Commandrepair extends EssentialsCommand
{
throw new Exception(_("repairInvalidType"));
}
if (!item.getEnchantments().isEmpty()
&& !ess.getSettings().getRepairEnchanted()
&& !user.isAuthorized("essentials.repair.enchanted"))
{
throw new Exception(_("repairEnchanted"));
}
final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH);
final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), ess);
@ -104,6 +112,12 @@ public class Commandrepair extends EssentialsCommand
user.sendMessage(ex.getMessage());
continue;
}
if (!item.getEnchantments().isEmpty()
&& !ess.getSettings().getRepairEnchanted()
&& !user.isAuthorized("essentials.repair.enchanted"))
{
continue;
}
try
{

View File

@ -16,7 +16,7 @@ public class Commandrules extends EssentialsCommand
}
@Override
public void run(final Server server, final CommandSender sender, final String commandLabel, String[] args) throws Exception
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
final IText input = new TextInput(sender, "rules", true, ess);
final IText output = new KeywordReplacer(input, sender, ess);

View File

@ -15,7 +15,7 @@ public class Commandseen extends EssentialsCommand
}
@Override
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
@ -34,6 +34,10 @@ public class Commandseen extends EssentialsCommand
throw new Exception(_("playerNotFound"));
}
sender.sendMessage(_("seenOffline", u.getDisplayName(), Util.formatDateDiff(u.getLastLogout())));
if (u.isBanned())
{
sender.sendMessage(_("whoisBanned", _("true")));
}
}
}
}

View File

@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.InventoryWorkaround;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
@ -20,7 +20,7 @@ public class Commandsell extends EssentialsCommand
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
@ -156,7 +156,7 @@ public class Commandsell extends EssentialsCommand
//TODO: Prices for Enchantments
final ItemStack ris = is.clone();
ris.setAmount(amount);
InventoryWorkaround.removeItem(user.getInventory(), true, ris);
InventoryWorkaround.removeItem(user.getInventory(), true, true, ris);
user.updateInventory();
Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(worth * amount, ess), user.getLocation(), ess);
user.giveMoney(worth * amount);

View File

@ -14,7 +14,7 @@ public class Commandsethome extends EssentialsCommand
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
public void run(final Server server, final User user, final String commandLabel, String[] args) throws Exception
{
if (args.length > 0)
{

View File

@ -13,13 +13,13 @@ public class Commandsetjail extends EssentialsCommand
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
ess.getJail().setJail(user.getLocation(), args[0]);
ess.getJails().setJail(args[0], user.getLocation());
user.sendMessage(_("jailSet", args[0]));
}

View File

@ -14,14 +14,14 @@ public class Commandsetwarp extends EssentialsCommand
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
Location loc = user.getLocation();
final Location loc = user.getLocation();
ess.getWarps().setWarp(args[0], loc);
user.sendMessage(_("warpSet", args[0]));
}

View File

@ -14,7 +14,7 @@ public class Commandsetworth extends EssentialsCommand
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 2)
{

View File

@ -13,7 +13,7 @@ public class Commandsocialspy extends EssentialsCommand
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
user.sendMessage("§7SocialSpy " + (user.toggleSocialSpy() ? _("enabled") : _("disabled")));
}

View File

@ -8,7 +8,6 @@ import java.util.Locale;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.block.CreatureSpawner;
@ -20,7 +19,7 @@ public class Commandspawner extends EssentialsCommand
}
@Override
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1 || args[0].length() < 2)
{

View File

@ -22,7 +22,7 @@ public class Commandspawnmob extends EssentialsCommand
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
@ -30,7 +30,7 @@ public class Commandspawnmob extends EssentialsCommand
}
String[] mountparts = args[0].split(",");
final String[] mountparts = args[0].split(",");
String[] parts = mountparts[0].split(":");
String mobType = parts[0];
String mobData = null;
@ -64,11 +64,11 @@ public class Commandspawnmob extends EssentialsCommand
if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH)))
{
throw new Exception(_("unableToSpawnMob"));
throw new Exception(_("disabledToSpawnMob"));
}
if (!user.isAuthorized("essentials.spawnmob." + mob.name.toLowerCase()))
{
throw new Exception(_("unableToSpawnMob"));
throw new Exception(_("noPermToSpawnMob"));
}
final Block block = Util.getTarget(user).getBlock();
@ -76,8 +76,13 @@ public class Commandspawnmob extends EssentialsCommand
{
throw new Exception(_("unableToSpawnMob"));
}
Location loc = block.getLocation();
Location sloc = Util.getSafeDestination(loc);
User otherUser = null;
if (args.length >= 3)
{
otherUser = getPlayer(ess.getServer(), args, 2);
}
final Location loc = (otherUser == null) ? block.getLocation() : otherUser.getLocation();
final Location sloc = Util.getSafeDestination(loc);
try
{
spawnedMob = mob.spawn(user, server, sloc);
@ -98,11 +103,11 @@ public class Commandspawnmob extends EssentialsCommand
if (ess.getSettings().getProtectPreventSpawn(mobMount.getType().toString().toLowerCase(Locale.ENGLISH)))
{
throw new Exception(_("unableToSpawnMob"));
throw new Exception(_("disabledToSpawnMob"));
}
if (!user.isAuthorized("essentials.spawnmob." + mobMount.name.toLowerCase()))
{
throw new Exception(_("unableToSpawnMob"));
throw new Exception(_("noPermToSpawnMob"));
}
try
{
@ -122,7 +127,7 @@ public class Commandspawnmob extends EssentialsCommand
{
changeMobData(mobMount.getType(), spawnedMount, mountData, user);
}
if (args.length == 2)
if (args.length >= 2)
{
int mobCount = Integer.parseInt(args[1]);
int serverLimit = ess.getSettings().getSpawnMobLimit();
@ -179,7 +184,7 @@ public class Commandspawnmob extends EssentialsCommand
}
}
private void changeMobData(CreatureType type, Entity spawned, String data, User user) throws Exception
private void changeMobData(final CreatureType type, final Entity spawned, final String data, final User user) throws Exception
{
if (type == CreatureType.SLIME || type == CreatureType.MAGMA_CUBE)
{
@ -194,6 +199,7 @@ public class Commandspawnmob extends EssentialsCommand
}
if ((type == CreatureType.SHEEP
|| type == CreatureType.COW
|| type == CreatureType.MUSHROOM_COW
|| type == CreatureType.CHICKEN
|| type == CreatureType.PIG
|| type == CreatureType.WOLF)
@ -204,16 +210,22 @@ public class Commandspawnmob extends EssentialsCommand
}
if (type == CreatureType.SHEEP)
{
if (data.toLowerCase(Locale.ENGLISH).contains("baby"))
{
((Sheep)spawned).setAge(-24000);
}
final String color = data.toUpperCase(Locale.ENGLISH).replace("BABY", "");
try
{
if (data.equalsIgnoreCase("random"))
if (color.equalsIgnoreCase("random"))
{
Random rand = new Random();
((Sheep)spawned).setColor(DyeColor.values()[rand.nextInt(DyeColor.values().length)]);
}
else
{
((Sheep)spawned).setColor(DyeColor.valueOf(data.toUpperCase(Locale.ENGLISH)));
((Sheep)spawned).setColor(DyeColor.valueOf(color));
}
}
catch (Exception e)

View File

@ -47,12 +47,12 @@ public class Commandtogglejail extends EssentialsCommand
}
if (!(player.getBase() instanceof OfflinePlayer))
{
ess.getJail().sendToJail(player, args[1]);
ess.getJails().sendToJail(player, args[1]);
}
else
{
// Check if jail exists
ess.getJail().getJail(args[1]);
ess.getJails().getJail(args[1]);
}
player.setJailed(true);
player.sendMessage(_("userJailed"));

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandtop extends EssentialsCommand
@ -20,7 +21,7 @@ public class Commandtop extends EssentialsCommand
final int topX = user.getLocation().getBlockX();
final int topZ = user.getLocation().getBlockZ();
final int topY = user.getWorld().getHighestBlockYAt(topX, topZ);
user.getTeleport().teleport(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), new Trade(this.getName(), ess));
user.getTeleport().teleport(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), new Trade(this.getName(), ess), TeleportCause.COMMAND);
user.sendMessage(_("teleportTop"));
}
}

View File

@ -6,6 +6,7 @@ import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandtp extends EssentialsCommand
@ -32,7 +33,7 @@ public class Commandtp extends EssentialsCommand
user.sendMessage(_("teleporting"));
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
user.getTeleport().teleport(player, charge);
user.getTeleport().teleport(player, charge, TeleportCause.COMMAND);
throw new NoChargeException();
default:
@ -44,7 +45,7 @@ public class Commandtp extends EssentialsCommand
user.sendMessage(_("teleporting"));
final User target = getPlayer(server, args, 0);
final User toPlayer = getPlayer(server, args, 1);
target.getTeleport().now(toPlayer, false);
target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND);
target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName()));
break;
}
@ -61,7 +62,7 @@ public class Commandtp extends EssentialsCommand
sender.sendMessage(_("teleporting"));
final User target = getPlayer(server, args, 0);
final User toPlayer = getPlayer(server, args, 1);
target.getTeleport().now(toPlayer, false);
target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND);
target.sendMessage(_("teleportAtoB", Console.NAME, toPlayer.getDisplayName()));
}
}

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.OfflinePlayer;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandtpaccept extends EssentialsCommand
@ -40,11 +41,11 @@ public class Commandtpaccept extends EssentialsCommand
if (user.isTeleportRequestHere())
{
user.getTeleport().teleport(target, charge);
user.getTeleport().teleport(target, charge, TeleportCause.COMMAND);
}
else
{
target.getTeleport().teleport(user, charge);
target.getTeleport().teleport(user, charge, TeleportCause.COMMAND);
}
user.requestTeleport(null, false);
}

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandtpall extends EssentialsCommand
@ -43,7 +44,7 @@ public class Commandtpall extends EssentialsCommand
}
try
{
player.getTeleport().now(user, false);
player.getTeleport().now(user, false, TeleportCause.COMMAND);
}
catch (Exception ex)
{

View File

@ -4,6 +4,7 @@ import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandtphere extends EssentialsCommand
@ -21,7 +22,7 @@ public class Commandtphere extends EssentialsCommand
{
throw new Exception(_("teleportDisabled", player.getDisplayName()));
}
player.getTeleport().teleport(user, new Trade(this.getName(), ess));
player.getTeleport().teleport(user, new Trade(this.getName(), ess), TeleportCause.COMMAND);
user.sendMessage(_("teleporting"));
player.sendMessage(_("teleporting"));
throw new NoChargeException();

View File

@ -4,6 +4,7 @@ import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.OfflinePlayer;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandtpo extends EssentialsCommand
@ -32,7 +33,7 @@ public class Commandtpo extends EssentialsCommand
// Verify permission
if (!player.isHidden() || user.isAuthorized("essentials.teleport.hidden"))
{
user.getTeleport().now(player, false);
user.getTeleport().now(player, false, TeleportCause.COMMAND);
user.sendMessage(_("teleporting"));
}
else

View File

@ -4,6 +4,7 @@ import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.OfflinePlayer;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandtpohere extends EssentialsCommand
@ -33,7 +34,7 @@ public class Commandtpohere extends EssentialsCommand
// Verify permission
if (!player.isHidden() || user.isAuthorized("essentials.teleport.hidden"))
{
player.getTeleport().now(user, false);
player.getTeleport().now(user, false, TeleportCause.COMMAND);
user.sendMessage(_("teleporting"));
}
else

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandtppos extends EssentialsCommand
@ -37,7 +38,7 @@ public class Commandtppos extends EssentialsCommand
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
user.sendMessage(_("teleporting"));
user.getTeleport().teleport(location, charge);
user.getTeleport().teleport(location, charge, TeleportCause.COMMAND);
throw new NoChargeException();
}
}

View File

@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.InventoryWorkaround;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.User;
import java.util.List;
import java.util.Locale;
@ -103,7 +103,7 @@ public class Commandunlimited extends EssentialsCommand
{
message = "enableUnlimited";
enableUnlimited = true;
if (!InventoryWorkaround.containsItem(target.getInventory(), true, stack))
if (!InventoryWorkaround.containsItem(target.getInventory(), true, true, stack))
{
target.getInventory().addItem(stack);
}

View File

@ -10,6 +10,7 @@ import java.util.Iterator;
import java.util.List;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandwarp extends EssentialsCommand
@ -118,11 +119,11 @@ public class Commandwarp extends EssentialsCommand
{
if (user.isAuthorized("essentials.warp." + name))
{
user.getTeleport().warp(name, charge);
user.getTeleport().warp(name, charge, TeleportCause.COMMAND);
return;
}
throw new Exception(_("warpUsePermission"));
}
user.getTeleport().warp(name, charge);
user.getTeleport().warp(name, charge, TeleportCause.COMMAND);
}
}

View File

@ -7,6 +7,7 @@ import java.util.List;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Commandworld extends EssentialsCommand
@ -53,6 +54,15 @@ public class Commandworld extends EssentialsCommand
}
}
if (ess.getSettings().getIsWorldTeleportPermissions())
{
if (!user.isAuthorized("essentials.world." + world.getName()))
{
user.sendMessage(_("invalidWorld")); //TODO: Make a "world teleport denied" translation
throw new NoChargeException();
}
}
double factor;
if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL)
{
@ -72,7 +82,7 @@ public class Commandworld extends EssentialsCommand
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
user.getTeleport().teleport(target, charge);
user.getTeleport().teleport(target, charge, TeleportCause.COMMAND);
throw new NoChargeException();
}
}

View File

@ -2,6 +2,7 @@ package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.IEssentialsModule;
import com.earth2me.essentials.OfflinePlayer;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
@ -17,6 +18,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand
{
private final transient String name;
protected transient IEssentials ess;
protected transient IEssentialsModule module;
protected final static Logger logger = Logger.getLogger("Minecraft");
protected EssentialsCommand(final String name)
@ -29,6 +31,12 @@ public abstract class EssentialsCommand implements IEssentialsCommand
{
this.ess = ess;
}
@Override
public void setEssentialsModule(final IEssentialsModule module)
{
this.module = module;
}
@Override
public String getName()

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.IEssentialsModule;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.command.Command;
@ -18,4 +19,6 @@ public interface IEssentialsCommand
throws Exception;
void setEssentials(IEssentials ess);
void setEssentialsModule(IEssentialsModule module);
}

View File

@ -1,66 +0,0 @@
package com.earth2me.essentials.craftbukkit;
import org.bukkit.craftbukkit.inventory.CraftInventory;
import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class EnchantmentFix
{
public static void setContents(Inventory inventory, ItemStack[] items)
{
CraftInventory cInventory = (CraftInventory)inventory;
if (cInventory.getContents().length != items.length)
{
throw new IllegalArgumentException("Invalid inventory size; expected " + cInventory.getContents().length);
}
net.minecraft.server.ItemStack[] mcItems = cInventory.getInventory().getContents();
for (int i = 0; i < items.length; i++)
{
ItemStack item = items[i];
if (item == null || item.getTypeId() <= 0)
{
mcItems[i] = null;
}
else
{
mcItems[i] = new net.minecraft.server.ItemStack(item.getTypeId(), item.getAmount(), item.getDurability());
new CraftItemStack(mcItems[i]).addUnsafeEnchantments(item.getEnchantments());
}
}
}
public static void setItem(Inventory inventory, int index, ItemStack item)
{
CraftInventory cInventory = (CraftInventory)inventory;
if (item == null)
{
cInventory.getInventory().setItem(index, null);
}
else
{
net.minecraft.server.ItemStack stack = new net.minecraft.server.ItemStack(item.getTypeId(), item.getAmount(), item.getDurability());
new CraftItemStack(stack).addUnsafeEnchantments(item.getEnchantments());
cInventory.getInventory().setItem(index, stack);
}
}
public static void setItemInHand(Inventory inventory, ItemStack item)
{
CraftInventoryPlayer cInventory = (CraftInventoryPlayer)inventory;
if (item == null)
{
cInventory.getInventory().setItem(cInventory.getInventory().itemInHandIndex, null);
}
else
{
net.minecraft.server.ItemStack stack = new net.minecraft.server.ItemStack(item.getTypeId(), item.getAmount(), item.getDurability());
new CraftItemStack(stack).addUnsafeEnchantments(item.getEnchantments());
cInventory.getInventory().setItem(cInventory.getInventory().itemInHandIndex, stack);
}
}
}

View File

@ -1,4 +1,4 @@
package com.earth2me.essentials;
package com.earth2me.essentials.craftbukkit;
import java.util.HashMap;
import org.bukkit.Material;

View File

@ -1,4 +1,4 @@
package com.earth2me.essentials;
package com.earth2me.essentials.craftbukkit;
import java.io.File;
import java.util.List;
@ -15,10 +15,10 @@ import org.bukkit.util.Vector;
public class FakeWorld implements World
{
private final String name;
private final Environment env;
FakeWorld(String string, Environment environment)
public FakeWorld(String string, Environment environment)
{
this.name = string;
this.env = environment;
@ -444,7 +444,6 @@ public class FakeWorld implements World
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Biome getBiome(int i, int i1)
{
@ -498,19 +497,19 @@ public class FakeWorld implements World
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Difficulty getDifficulty()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setDifficulty(Difficulty difficulty)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getSeaLevel()
{

View File

@ -1,6 +1,6 @@
package com.earth2me.essentials;
package com.earth2me.essentials.craftbukkit;
import com.earth2me.essentials.craftbukkit.EnchantmentFix;
import com.earth2me.essentials.craftbukkit.FakeInventory;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Location;
@ -20,12 +20,12 @@ public final class InventoryWorkaround
{
}
public static int first(final Inventory inventory, final ItemStack item, final boolean forceDurability, final boolean forceAmount)
public static int first(final Inventory inventory, final ItemStack item, final boolean forceDurability, final boolean forceAmount, final boolean forceEnchantments)
{
return next(inventory, item, 0, forceDurability, forceAmount);
return next(inventory, item, 0, forceDurability, forceAmount, forceEnchantments);
}
public static int next(final Inventory cinventory, final ItemStack item, final int start, final boolean forceDurability, final boolean forceAmount)
public static int next(final Inventory cinventory, final ItemStack item, final int start, final boolean forceDurability, final boolean forceAmount, final boolean forceEnchantments)
{
final ItemStack[] inventory = cinventory.getContents();
for (int i = start; i < inventory.length; i++)
@ -35,7 +35,7 @@ public final class InventoryWorkaround
{
continue;
}
if (item.getTypeId() == cItem.getTypeId() && (!forceAmount || item.getAmount() == cItem.getAmount()) && (!forceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments()))
if (item.getTypeId() == cItem.getTypeId() && (!forceAmount || item.getAmount() == cItem.getAmount()) && (!forceDurability || cItem.getDurability() == item.getDurability()) && (!forceEnchantments || cItem.getEnchantments().equals(item.getEnchantments())))
{
return i;
}
@ -44,6 +44,11 @@ public final class InventoryWorkaround
}
public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean forceDurability)
{
return firstPartial(cinventory, item, forceDurability, item.getType().getMaxStackSize());
}
public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean forceDurability, final int maxAmount)
{
if (item == null)
{
@ -57,7 +62,7 @@ public final class InventoryWorkaround
{
continue;
}
if (item.getTypeId() == cItem.getTypeId() && cItem.getAmount() < cItem.getType().getMaxStackSize() && (!forceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments()))
if (item.getTypeId() == cItem.getTypeId() && cItem.getAmount() < maxAmount && (!forceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments()))
{
return i;
}
@ -130,7 +135,8 @@ public final class InventoryWorkaround
while (true)
{
// Do we already have a stack of it?
final int firstPartial = firstPartial(cinventory, item, forceDurability);
final int maxAmount = oversizedStacks > item.getType().getMaxStackSize() ? oversizedStacks : item.getType().getMaxStackSize();
final int firstPartial = firstPartial(cinventory, item, forceDurability, maxAmount);
// Drat! no partial stack
if (firstPartial == -1)
@ -146,33 +152,18 @@ public final class InventoryWorkaround
}
else
{
final int maxAmount = oversizedStacks > 0 ? oversizedStacks : item.getType().getMaxStackSize();
// More than a single stack!
if (item.getAmount() > maxAmount)
{
final ItemStack stack = item.clone();
stack.setAmount(maxAmount);
if (cinventory instanceof FakeInventory)
{
cinventory.setItem(firstFree, stack);
}
else
{
EnchantmentFix.setItem(cinventory, firstFree, stack);
}
cinventory.setItem(firstFree, stack);
item.setAmount(item.getAmount() - maxAmount);
}
else
{
// Just store it
if (cinventory instanceof FakeInventory)
{
cinventory.setItem(firstFree, item);
}
else
{
EnchantmentFix.setItem(cinventory, firstFree, item);
}
cinventory.setItem(firstFree, item);
break;
}
}
@ -184,8 +175,7 @@ public final class InventoryWorkaround
final int amount = item.getAmount();
final int partialAmount = partialItem.getAmount();
final int maxAmount = oversizedStacks > 0 ? oversizedStacks : partialItem.getType().getMaxStackSize();
// Check if it fully fits
if (amount + partialAmount <= maxAmount)
{
@ -202,7 +192,7 @@ public final class InventoryWorkaround
return leftover;
}
public static Map<Integer, ItemStack> removeItem(final Inventory cinventory, final boolean forceDurability, final ItemStack... items)
public static Map<Integer, ItemStack> removeItem(final Inventory cinventory, final boolean forceDurability, final boolean forceEnchantments, final ItemStack... items)
{
final Map<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
@ -227,7 +217,7 @@ public final class InventoryWorkaround
}
// get first Item, ignore the amount
final int first = first(cinventory, item, forceDurability, false);
final int first = first(cinventory, item, forceDurability, false, forceEnchantments);
// Drat! we don't have this type in the inventory
if (first == -1)
@ -251,7 +241,7 @@ public final class InventoryWorkaround
{
// split the stack and store
itemStack.setAmount(amount - toDelete);
EnchantmentFix.setItem(cinventory, first, itemStack);
cinventory.setItem(first, itemStack);
toDelete = 0;
}
}
@ -260,7 +250,7 @@ public final class InventoryWorkaround
return leftover;
}
public static boolean containsItem(final Inventory cinventory, final boolean forceDurability, final ItemStack... items)
public static boolean containsItem(final Inventory cinventory, final boolean forceDurability, final boolean forceEnchantments, final ItemStack... items)
{
final Map<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
@ -282,7 +272,7 @@ public final class InventoryWorkaround
combined[j] = items[i].clone();
break;
}
if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && combined[j].getEnchantments().equals(items[i].getEnchantments()))
if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && (!forceEnchantments || combined[j].getEnchantments().equals(items[i].getEnchantments())))
{
combined[j].setAmount(combined[j].getAmount() + items[i].getAmount());
break;
@ -308,7 +298,7 @@ public final class InventoryWorkaround
break;
}
final int slot = next(cinventory, item, position, forceDurability, false);
final int slot = next(cinventory, item, position, forceDurability, false, forceEnchantments);
// Drat! we don't have this type in the inventory
if (slot == -1)

View File

@ -0,0 +1,52 @@
package com.earth2me.essentials.craftbukkit;
import com.earth2me.essentials.IEssentials;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.NBTTagCompound;
import net.minecraft.server.WorldNBTStorage;
import org.bukkit.Location;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.CraftWorld;
public class OfflineBedLocation
{
public static Location getBedLocation(final String playername, final IEssentials ess)
{
try
{
final CraftServer cserver = (CraftServer)ess.getServer();
if (cserver == null)
{
return null;
}
final WorldNBTStorage wnbtStorage = (WorldNBTStorage)cserver.getHandle().playerFileData;
if (wnbtStorage == null)
{
return null;
}
final NBTTagCompound playerStorage = wnbtStorage.getPlayerData(playername);
if (playerStorage == null)
{
return null;
}
if (playerStorage.hasKey("SpawnX") && playerStorage.hasKey("SpawnY") && playerStorage.hasKey("SpawnZ"))
{
String spawnWorld = playerStorage.getString("SpawnWorld");
if ("".equals(spawnWorld))
{
spawnWorld = cserver.getWorlds().get(0).getName();
}
return new Location(cserver.getWorld(spawnWorld), playerStorage.getInt("SpawnX"), playerStorage.getInt("SpawnY"), playerStorage.getInt("SpawnZ"));
}
return null;
}
catch (Throwable ex)
{
Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
return null;
}
}
}

View File

@ -0,0 +1,25 @@
package com.earth2me.essentials.craftbukkit;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.ChunkCoordinates;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.entity.Player;
public class SetBed
{
public static void setBed(final Player player, final Block block)
{
try
{
final CraftPlayer cplayer = (CraftPlayer)player;
cplayer.getHandle().a(new ChunkCoordinates(block.getX(), block.getY(), block.getZ()));
}
catch (Throwable ex)
{
Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
}
}
}

View File

@ -1,11 +1,10 @@
package com.earth2me.essentials.craftbukkit;
import com.earth2me.essentials.InventoryWorkaround;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.EntityPlayer;
import net.minecraft.server.IInventory;
import net.minecraft.server.InventoryPlayer;
import net.minecraft.server.PlayerInventory;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer;
import org.bukkit.entity.Player;
@ -19,7 +18,7 @@ public class ShowInventory
try
{
final EntityPlayer entityPlayer = ((CraftPlayer)player).getHandle();
final CraftInventoryPlayer inv = new CraftInventoryPlayer(new InventoryPlayer(((CraftPlayer)player).getHandle()));
final CraftInventoryPlayer inv = new CraftInventoryPlayer(new PlayerInventory(((CraftPlayer)player).getHandle()));
inv.clear();
entityPlayer.a((IInventory)inv.getInventory());
}
@ -34,7 +33,7 @@ public class ShowInventory
try
{
final EntityPlayer entityPlayer = ((CraftPlayer)player).getHandle();
final CraftInventoryPlayer inv = new CraftInventoryPlayer(new InventoryPlayer(((CraftPlayer)player).getHandle()));
final CraftInventoryPlayer inv = new CraftInventoryPlayer(new PlayerInventory(((CraftPlayer)player).getHandle()));
inv.clear();
InventoryWorkaround.addItem(inv, true, stack);
entityPlayer.a((IInventory)inv.getInventory());

Some files were not shown because too many files have changed in this diff Show More