diff options
author | ementalo <ementalodev@gmx.co.uk> | 2012-05-28 00:37:28 +0100 |
---|---|---|
committer | ementalo <ementalodev@gmx.co.uk> | 2012-05-28 00:37:28 +0100 |
commit | 373a48da5412c6005f7ad2fe4bec41c68d4eb2a2 (patch) | |
tree | 3ebc11bffcb1dde3f3bd338fca97656d03511e70 /Essentials/src | |
parent | 45c1e347b0698318ebd3772c540a9a52b6509daf (diff) | |
parent | b69a16bcf0abac1ebd2ca3d35520cfcb5b433e88 (diff) | |
download | Essentials-373a48da5412c6005f7ad2fe4bec41c68d4eb2a2.tar Essentials-373a48da5412c6005f7ad2fe4bec41c68d4eb2a2.tar.gz Essentials-373a48da5412c6005f7ad2fe4bec41c68d4eb2a2.tar.lz Essentials-373a48da5412c6005f7ad2fe4bec41c68d4eb2a2.tar.xz Essentials-373a48da5412c6005f7ad2fe4bec41c68d4eb2a2.zip |
Master -> 3.0
Diffstat (limited to 'Essentials/src')
314 files changed, 7982 insertions, 13538 deletions
diff --git a/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java b/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java deleted file mode 100644 index e75644ad5..000000000 --- a/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java +++ /dev/null @@ -1,137 +0,0 @@ -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; -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> disabledList = new HashMap<String, String>(); - private final transient IEssentials ess; - - public AlternativeCommandsHandler(final IEssentials ess) - { - this.ess = ess; - for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) - { - if (plugin.isEnabled()) - { - addPlugin(plugin); - } - } - } - - public final void addPlugin(final Plugin plugin) - { - if (plugin.getDescription().getMain().contains("com.earth2me.essentials")) - { - return; - } - final List<Command> commands = PluginCommandYamlParser.parse(plugin); - final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH); - - for (Command command : commands) - { - final PluginCommand pc = (PluginCommand)command; - final List<String> labels = new ArrayList<String>(pc.getAliases()); - labels.add(pc.getName()); - - PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH)); - if (reg == null) - { - reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH)); - } - if (reg == null || !reg.getPlugin().equals(plugin)) - { - continue; - } - for (String label : labels) - { - List<PluginCommand> plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH)); - if (plugincommands == null) - { - plugincommands = new ArrayList<PluginCommand>(); - altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands); - } - boolean found = false; - for (PluginCommand pc2 : plugincommands) - { - if (pc2.getPlugin().equals(plugin)) - { - found = true; - } - } - if (!found) - { - plugincommands.add(reg); - } - } - } - } - - public void removePlugin(final Plugin plugin) - { - final Iterator<Map.Entry<String, List<PluginCommand>>> iterator = altcommands.entrySet().iterator(); - while (iterator.hasNext()) - { - final Map.Entry<String, List<PluginCommand>> entry = iterator.next(); - final Iterator<PluginCommand> pcIterator = entry.getValue().iterator(); - while (pcIterator.hasNext()) - { - final PluginCommand pc = pcIterator.next(); - if (pc.getPlugin() == null || pc.getPlugin().equals(plugin)) - { - pcIterator.remove(); - } - } - if (entry.getValue().isEmpty()) - { - iterator.remove(); - } - } - } - - public PluginCommand getAlternative(final String label) - { - final List<PluginCommand> commands = altcommands.get(label); - if (commands == null || commands.isEmpty()) - { - return null; - } - if (commands.size() == 1) - { - return commands.get(0); - } - // return the first command that is not an alias - for (PluginCommand command : commands) - { - if (command.getName().equalsIgnoreCase(label)) - { - return command; - } - } - // return the first alias - return commands.get(0); - } - - public void executed(final String label, final String 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 disabledList; - } -} diff --git a/Essentials/src/com/earth2me/essentials/Backup.java b/Essentials/src/com/earth2me/essentials/Backup.java deleted file mode 100644 index baa90e561..000000000 --- a/Essentials/src/com/earth2me/essentials/Backup.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; - - -public class Backup implements Runnable -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private transient final Server server; - private transient final IEssentials ess; - private transient boolean running = false; - private transient int taskId = -1; - private transient boolean active = false; - - public Backup(final IEssentials ess) - { - this.ess = ess; - server = ess.getServer(); - if (server.getOnlinePlayers().length > 0) - { - startTask(); - } - } - - void onPlayerJoin() - { - startTask(); - } - - private void startTask() - { - if (!running) - { - final long interval = ess.getSettings().getBackupInterval() * 1200; // minutes -> ticks - if (interval < 1200) - { - return; - } - taskId = ess.scheduleSyncRepeatingTask(this, interval, interval); - running = true; - } - } - - @Override - public void run() - { - if (active) - { - return; - } - active = true; - final String command = ess.getSettings().getBackupCommand(); - if (command == null || "".equals(command)) - { - return; - } - if ("save-all".equalsIgnoreCase(command)) { - final CommandSender cs = server.getConsoleSender(); - server.dispatchCommand(cs, "save-all"); - active = false; - return; - } - LOGGER.log(Level.INFO, _("backupStarted")); - final CommandSender cs = server.getConsoleSender(); - server.dispatchCommand(cs, "save-all"); - server.dispatchCommand(cs, "save-off"); - - ess.scheduleAsyncDelayedTask( - new Runnable() - { - @Override - public void run() - { - try - { - final ProcessBuilder childBuilder = new ProcessBuilder(command); - childBuilder.redirectErrorStream(true); - childBuilder.directory(ess.getDataFolder().getParentFile().getParentFile()); - final Process child = childBuilder.start(); - final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream())); - try - { - child.waitFor(); - String line; - do - { - line = reader.readLine(); - if (line != null) - { - LOGGER.log(Level.INFO, line); - } - } - while (line != null); - } - finally - { - reader.close(); - } - } - catch (InterruptedException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - finally - { - ess.scheduleSyncDelayedTask( - new Runnable() - { - @Override - public void run() - { - server.dispatchCommand(cs, "save-on"); - if (server.getOnlinePlayers().length == 0) - { - running = false; - if (taskId != -1) - { - server.getScheduler().cancelTask(taskId); - } - } - active = false; - LOGGER.log(Level.INFO, _("backupFinished")); - } - }); - } - } - }); - } -} diff --git a/Essentials/src/com/earth2me/essentials/Console.java b/Essentials/src/com/earth2me/essentials/Console.java index d07171c63..2e43883cf 100644 --- a/Essentials/src/com/earth2me/essentials/Console.java +++ b/Essentials/src/com/earth2me/essentials/Console.java @@ -1,6 +1,6 @@ package com.earth2me.essentials; -import org.bukkit.Server; +import com.earth2me.essentials.api.IReplyTo; import org.bukkit.command.CommandSender; @@ -14,13 +14,8 @@ public final class Console implements IReplyTo { } - public static CommandSender getCommandSender(Server server) throws Exception - { - return server.getConsoleSender(); - } - @Override - public void setReplyTo(CommandSender user) + public void setReplyTo(final CommandSender user) { replyTo = user; } diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java index 5b6236c30..dc63d3020 100644 --- a/Essentials/src/com/earth2me/essentials/Essentials.java +++ b/Essentials/src/com/earth2me/essentials/Essentials.java @@ -17,7 +17,20 @@ */ package com.earth2me.essentials; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.commands.EssentialsCommandHandler; +import com.earth2me.essentials.utils.ExecuteTimer; +import com.earth2me.essentials.economy.WorthHolder; +import com.earth2me.essentials.economy.Economy; +import com.earth2me.essentials.backup.Backup; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.*; +import com.earth2me.essentials.listener.*; +import com.earth2me.essentials.economy.register.Methods; +import com.earth2me.essentials.ranks.RanksStorage; +import com.earth2me.essentials.settings.SettingsHolder; +import com.earth2me.essentials.settings.SpawnsHolder; +import com.earth2me.essentials.user.UserMap; import com.earth2me.essentials.api.Economy; import com.earth2me.essentials.api.IJails; import com.earth2me.essentials.commands.EssentialsCommand; @@ -36,32 +49,25 @@ import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.world.WorldLoadEvent; -import org.bukkit.event.world.WorldUnloadEvent; 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; @@ -70,19 +76,24 @@ public class Essentials extends JavaPlugin implements IEssentials public static final int BUKKIT_VERSION = 2149; private static final Logger LOGGER = Logger.getLogger("Minecraft"); private transient ISettings settings; - private final transient TNTExplodeListener tntListener = new TNTExplodeListener(this); - private transient Jails jails; - private transient Warps warps; - private transient Worth worth; - private transient List<IConf> confList; - private transient Backup backup; - private transient ItemDb itemDb; + private final transient TntExplodeListener tntListener = new TntExplodeListener(this); + private transient IJails jails; + private transient IKits kits; + private transient IWarps warps; + private transient IWorth worth; + private transient List<IReload> reloadList; + private transient IBackup backup; + private transient IItemDb itemDb; + private transient IRanks groups; + private transient SpawnsHolder spawns; private transient final Methods paymentMethod = new Methods(); - private transient PermissionsHandler permissionsHandler; - private transient AlternativeCommandsHandler alternativeCommandsHandler; - private transient UserMap userMap; + //private transient PermissionsHandler permissionsHandler; + private transient IUserMap userMap; private transient ExecuteTimer execTimer; private transient I18n i18n; + private transient ICommandHandler commandHandler; + private transient Economy economy; + public transient boolean testing; private transient Metrics metrics; private transient EssentialsTimer timer; private transient List<String> vanishedPlayers = new ArrayList<String>(); @@ -95,6 +106,7 @@ public class Essentials extends JavaPlugin implements IEssentials public void setupForTesting(final Server server) throws IOException, InvalidDescriptionException { + testing = true; final File dataFolder = File.createTempFile("essentialstest", ""); if (!dataFolder.delete()) { @@ -109,11 +121,11 @@ public class Essentials extends JavaPlugin implements IEssentials LOGGER.log(Level.INFO, _("usingTempFolderForTesting")); LOGGER.log(Level.INFO, dataFolder.toString()); this.initialize(null, server, new PluginDescriptionFile(new FileReader(new File("src" + File.separator + "plugin.yml"))), dataFolder, null, null); - settings = new Settings(this); + settings = new SettingsHolder(this); i18n.updateLocale("en"); userMap = new UserMap(this); - permissionsHandler = new PermissionsHandler(this, false); - Economy.setEss(this); + //permissionsHandler = new PermissionsHandler(this); + economy = new Economy(this); } @Override @@ -157,27 +169,37 @@ public class Essentials extends JavaPlugin implements IEssentials 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); + //final EssentialsUpgrade upgrade = new EssentialsUpgrade(this); + //upgrade.beforeSettings(); + //execTimer.mark("Upgrade"); + reloadList = new ArrayList<IReload>(); + settings = new SettingsHolder(this); + reloadList.add(settings); execTimer.mark("Settings"); - upgrade.afterSettings(); - execTimer.mark("Upgrade2"); + //upgrade.afterSettings(); + //execTimer.mark("Upgrade2"); i18n.updateLocale(settings.getLocale()); userMap = new UserMap(this); - confList.add(userMap); + reloadList.add(userMap); execTimer.mark("Init(Usermap)"); - warps = new Warps(getServer(), this.getDataFolder()); - confList.add(warps); + groups = new RanksStorage(this); + reloadList.add((RanksStorage)groups); + warps = new Warps(this); + reloadList.add(warps); execTimer.mark("Init(Spawn/Warp)"); - worth = new Worth(this.getDataFolder()); - confList.add(worth); + worth = new WorthHolder(this); + reloadList.add(worth); itemDb = new ItemDb(this); - confList.add(itemDb); + reloadList.add(itemDb); execTimer.mark("Init(Worth/ItemDB)"); + kits = new Kits(this); + reloadList.add(kits); + commandHandler = new EssentialsCommandHandler(Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.", this); + reloadList.add(commandHandler); + economy = new Economy(this); + reloadList.add(economy); + spawns = new SpawnsHolder(this); + reloadList.add(spawns); reload(); } catch (YAMLException exception) @@ -207,11 +229,10 @@ public class Essentials extends JavaPlugin implements IEssentials return; } backup = new Backup(this); - permissionsHandler = new PermissionsHandler(this, settings.useBukkitPermissions()); - alternativeCommandsHandler = new AlternativeCommandsHandler(this); + //permissionsHandler = new PermissionsHandler(this); final EssentialsPluginListener serverListener = new EssentialsPluginListener(this); pm.registerEvents(serverListener, this); - confList.add(serverListener); + reloadList.add(serverListener); final EssentialsPlayerListener playerListener = new EssentialsPlayerListener(this); pm.registerEvents(playerListener, this); @@ -219,31 +240,17 @@ public class Essentials extends JavaPlugin implements IEssentials final EssentialsBlockListener blockListener = new EssentialsBlockListener(this); pm.registerEvents(blockListener, this); - final SignBlockListener signBlockListener = new SignBlockListener(this); - pm.registerEvents(signBlockListener, this); - - final SignPlayerListener signPlayerListener = new SignPlayerListener(this); - pm.registerEvents(signPlayerListener, this); - - final SignEntityListener signEntityListener = new SignEntityListener(this); - pm.registerEvents(signEntityListener, this); - final EssentialsEntityListener entityListener = new EssentialsEntityListener(this); pm.registerEvents(entityListener, this); - final EssentialsWorldListener worldListener = new EssentialsWorldListener(this); - pm.registerEvents(worldListener, this); - - //TODO: Check if this should be here, and not above before reload() jails = new Jails(this); - confList.add(jails); + reloadList.add(jails); pm.registerEvents(tntListener, this); - timer = new EssentialsTimer(this); - getScheduler().scheduleSyncRepeatingTask(this, timer, 100, 100); - Economy.setEss(this); + final EssentialsTimer timer = new EssentialsTimer(this); + getServer().getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 100); execTimer.mark("RegListeners"); final MetricsStarter metricsStarter = new MetricsStarter(this); @@ -260,7 +267,7 @@ public class Essentials extends JavaPlugin implements IEssentials final String timeroutput = execTimer.end(); if (getSettings().isDebug()) { - LOGGER.log(Level.INFO, "Essentials load " + timeroutput); + LOGGER.log(Level.INFO, "Essentials load {0}", timeroutput); } } @@ -275,7 +282,6 @@ public class Essentials extends JavaPlugin implements IEssentials } } i18n.onDisable(); - Economy.setEss(null); Trade.closeLog(); } @@ -284,10 +290,10 @@ public class Essentials extends JavaPlugin implements IEssentials { Trade.closeLog(); - for (IConf iConf : confList) + for (IReload iReload : reloadList) { - iConf.reloadConfig(); - execTimer.mark("Reload(" + iConf.getClass().getSimpleName() + ")"); + iReload.onReload(); + execTimer.mark("Reload(" + iReload.getClass().getSimpleName() + ")"); } i18n.updateLocale(settings.getLocale()); @@ -296,155 +302,36 @@ 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.", null); + return commandHandler.handleCommand(sender, command, commandLabel, args); + //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, final IEssentialsModule module) - { - // Allow plugins to override the command via onCommand - if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) - { - final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel); - if (pc != null) - { - alternativeCommandsHandler.executed(commandLabel, pc.getLabel()); - try - { - return pc.execute(sender, commandLabel, args); - } - catch (final Exception ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command"); - return true; - } - } - } - - try - { - User user = null; - if (sender instanceof Player) - { - user = getUser(sender); - LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0))); - } - - // New mail notification - if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail")) - { - final List<String> mail = user.getMails(); - if (mail != null && !mail.isEmpty()) - { - user.sendMessage(_("youHaveNewMail", mail.size())); - } - } - - // Check for disabled commands - if (getSettings().isCommandDisabled(commandLabel)) - { - return true; - } - - IEssentialsCommand cmd; - try - { - cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance(); - cmd.setEssentials(this); - cmd.setEssentialsModule(module); - } - catch (Exception ex) - { - sender.sendMessage(_("commandNotLoaded", commandLabel)); - LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandLabel), ex); - return true; - } - - // Check authorization - if (user != null && !user.isAuthorized(cmd, permissionPrefix)) - { - LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName())); - user.sendMessage(_("noAccessCommand")); - return true; - } - - // Run the command - try - { - if (user == null) - { - cmd.run(getServer(), sender, commandLabel, command, args); - } - else - { - cmd.run(getServer(), user, commandLabel, command, args); - } - return true; - } - catch (NoChargeException ex) - { - return true; - } - catch (NotEnoughArgumentsException ex) - { - sender.sendMessage(command.getDescription()); - sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); - if (!ex.getMessage().isEmpty()) - { - sender.sendMessage(ex.getMessage()); - } - return true; - } - catch (Throwable ex) - { - showError(sender, ex, commandLabel); - return true; - } - } - catch (Throwable ex) - { - LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex); - return true; - } - } - - @Override - public void showError(final CommandSender sender, final Throwable exception, final String commandLabel) - { - sender.sendMessage(_("errorWithMessage", exception.getMessage())); - if (getSettings().isDebug()) - { - LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception); - } - } - - @Override - public BukkitScheduler getScheduler() + public IJails getJails() { - return this.getServer().getScheduler(); + return jails; } @Override - public IJails getJails() + public IKits getKits() { - return jails; + return kits; } @Override - public Warps getWarps() + public IWarps getWarps() { return warps; } @Override - public Worth getWorth() + public IWorth getWorth() { return worth; } @Override - public Backup getBackup() + public IBackup getBackup() { return backup; } @@ -460,57 +347,15 @@ public class Essentials extends JavaPlugin implements IEssentials } @Override - public User getUser(final Object base) + public IUser getUser(final Player player) { - if (base instanceof Player) - { - return getUser((Player)base); - } - if (base instanceof String) - { - final User user = userMap.getUser((String)base); - if (user != null && user.getBase() instanceof OfflinePlayer) - { - ((OfflinePlayer)user.getBase()).setName((String)base); - } - return user; - } - return null; - } - - private <T extends Player> User getUser(final T base) - { - if (base == null) - { - return null; - } - - if (base instanceof User) - { - return (User)base; - } - User user = userMap.getUser(base.getName()); - - if (user == null) - { - user = new User(base, this); - } - else - { - user.update(base); - } - return user; + return userMap.getUser(player); } @Override - public User getOfflineUser(final String name) + public IUser getUser(final String playerName) { - final User user = userMap.getUser(name); - if (user != null && user.getBase() instanceof OfflinePlayer) - { - ((OfflinePlayer)user.getBase()).setName(name); - } - return user; + return userMap.getUser(playerName); } @Override @@ -528,9 +373,9 @@ public class Essentials extends JavaPlugin implements IEssentials } @Override - public void addReloadListener(final IConf listener) + public void addReloadListener(final IReload listener) { - confList.add(listener); + reloadList.add(listener); } @Override @@ -554,8 +399,8 @@ public class Essentials extends JavaPlugin implements IEssentials for (Player player : players) { - final User user = getUser(player); - if (!user.isIgnoredPlayer(sender.getName())) + final IUser user = getUser(player); + if (!user.isIgnoringPlayer(sender.getName())) { player.sendMessage(message); } @@ -567,116 +412,81 @@ public class Essentials extends JavaPlugin implements IEssentials @Override public int scheduleAsyncDelayedTask(final Runnable run) { - return this.getScheduler().scheduleAsyncDelayedTask(this, run); + return this.getServer().getScheduler().scheduleAsyncDelayedTask(this, run); } @Override public int scheduleSyncDelayedTask(final Runnable run) { - return this.getScheduler().scheduleSyncDelayedTask(this, run); + return this.getServer().getScheduler().scheduleSyncDelayedTask(this, run); } @Override public int scheduleSyncDelayedTask(final Runnable run, final long delay) { - return this.getScheduler().scheduleSyncDelayedTask(this, run, delay); + return this.getServer().getScheduler().scheduleSyncDelayedTask(this, run, delay); } @Override public int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period) { - return this.getScheduler().scheduleSyncRepeatingTask(this, run, delay, period); + return this.getServer().getScheduler().scheduleSyncRepeatingTask(this, run, delay, period); } @Override - public TNTExplodeListener getTNTListener() + public TntExplodeListener getTNTListener() { return tntListener; } + /* + * @Override public PermissionsHandler getPermissionsHandler() { return permissionsHandler; } + */ @Override - public PermissionsHandler getPermissionsHandler() + public IItemDb getItemDb() { - return permissionsHandler; + return itemDb; } @Override - public AlternativeCommandsHandler getAlternativeCommandsHandler() + public IUserMap getUserMap() { - return alternativeCommandsHandler; + return userMap; } @Override - public ItemDb getItemDb() + public I18n getI18n() { - return itemDb; + return i18n; } @Override - public UserMap getUserMap() + public IRanks getRanks() { - return userMap; + return groups; } @Override - public I18n getI18n() + public ICommandHandler getCommandHandler() { - return i18n; + return commandHandler; } @Override - public EssentialsTimer getTimer() + public void setRanks(final IRanks groups) { - return timer; + this.groups = groups; } @Override - public List<String> getVanishedPlayers() + public void removeReloadListener(IReload groups) { - return vanishedPlayers; + this.reloadList.remove(groups); } - private static class EssentialsWorldListener implements Listener, Runnable + @Override + public IEconomy getEconomy() { - private transient final IEssentials ess; - - public EssentialsWorldListener(final IEssentials ess) - { - this.ess = ess; - } - - @EventHandler(priority = EventPriority.LOW) - public void onWorldLoad(final WorldLoadEvent event) - { - ess.getJails().onReload(); - ess.getWarps().reloadConfig(); - for (IConf iConf : ((Essentials)ess).confList) - { - if (iConf instanceof IEssentialsModule) - { - iConf.reloadConfig(); - } - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onWorldUnload(final WorldUnloadEvent event) - { - ess.getJails().onReload(); - ess.getWarps().reloadConfig(); - for (IConf iConf : ((Essentials)ess).confList) - { - if (iConf instanceof IEssentialsModule) - { - iConf.reloadConfig(); - } - } - } - - @Override - public void run() - { - ess.reload(); - } + return economy; } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsConf.java b/Essentials/src/com/earth2me/essentials/EssentialsConf.java deleted file mode 100644 index b2cb1fd12..000000000 --- a/Essentials/src/com/earth2me/essentials/EssentialsConf.java +++ /dev/null @@ -1,396 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.google.common.io.Files; -import java.io.*; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.World; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsConf extends YamlConfiguration -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private transient File configFile; - private transient String templateName = null; - private transient Class<?> resourceClass = EssentialsConf.class; - private static final Charset UTF8 = Charset.forName("UTF-8"); - - public EssentialsConf(final File configFile) - { - super(); - this.configFile = configFile; - } - - public synchronized void load() - { - configFile = configFile.getAbsoluteFile(); - if (!configFile.getParentFile().exists()) - { - if (!configFile.getParentFile().mkdirs()) - { - LOGGER.log(Level.SEVERE, _("failedToCreateConfig", configFile.toString())); - } - } - // This will delete files where the first character is 0. In most cases they are broken. - if (configFile.exists() && configFile.length() != 0) - { - try - { - final InputStream input = new FileInputStream(configFile); - try - { - if (input.read() == 0) - { - input.close(); - configFile.delete(); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - finally - { - try - { - input.close(); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - catch (FileNotFoundException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - - if (!configFile.exists()) - { - if (templateName != null) - { - LOGGER.log(Level.INFO, _("creatingConfigFromTemplate", configFile.toString())); - createFromTemplate(); - } - else - { - try - { - LOGGER.log(Level.INFO, _("creatingEmptyConfig", configFile.toString())); - if (!configFile.createNewFile()) - { - LOGGER.log(Level.SEVERE, _("failedToCreateConfig", configFile.toString())); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, _("failedToCreateConfig", configFile.toString()), ex); - } - } - } - - - try - { - final FileInputStream inputStream = new FileInputStream(configFile); - try - { - final FileChannel channel = inputStream.getChannel(); - final ByteBuffer buffer = ByteBuffer.allocate((int)configFile.length()); - channel.read(buffer); - buffer.rewind(); - final CharBuffer data = CharBuffer.allocate((int)configFile.length()); - CharsetDecoder decoder = UTF8.newDecoder(); - CoderResult result = decoder.decode(buffer, data, true); - if (result.isError()) - { - buffer.rewind(); - data.clear(); - LOGGER.log(Level.INFO, "File " + configFile.getAbsolutePath().toString() + " is not utf-8 encoded, trying " + Charset.defaultCharset().displayName()); - decoder = Charset.defaultCharset().newDecoder(); - result = decoder.decode(buffer, data, true); - if (result.isError()) - { - throw new InvalidConfigurationException("Invalid Characters in file " + configFile.getAbsolutePath().toString()); - } - else - { - decoder.flush(data); - } - } - else - { - decoder.flush(data); - } - final int end = data.position(); - data.rewind(); - super.loadFromString(data.subSequence(0, end).toString()); - } - finally - { - inputStream.close(); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - catch (InvalidConfigurationException ex) - { - File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis()); - configFile.renameTo(broken); - LOGGER.log(Level.SEVERE, "The file " + configFile.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause()); - } - } - - private void createFromTemplate() - { - InputStream istr = null; - OutputStream ostr = null; - try - { - istr = resourceClass.getResourceAsStream(templateName); - if (istr == null) - { - LOGGER.log(Level.SEVERE, _("couldNotFindTemplate", templateName)); - return; - } - ostr = new FileOutputStream(configFile); - byte[] buffer = new byte[1024]; - int length = 0; - length = istr.read(buffer); - while (length > 0) - { - ostr.write(buffer, 0, length); - length = istr.read(buffer); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, _("failedToWriteConfig", configFile.toString()), ex); - } - finally - { - try - { - if (istr != null) - { - istr.close(); - } - } - catch (IOException ex) - { - Logger.getLogger(EssentialsConf.class.getName()).log(Level.SEVERE, null, ex); - } - try - { - if (ostr != null) - { - ostr.close(); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, _("failedToCloseConfig", configFile.toString()), ex); - } - } - } - - public void setTemplateName(final String templateName) - { - this.templateName = templateName; - } - - public File getFile() - { - return configFile; - } - - public void setTemplateName(final String templateName, final Class<?> resClass) - { - this.templateName = templateName; - this.resourceClass = resClass; - } - - public boolean hasProperty(final String path) - { - return isSet(path); - } - - public Location getLocation(final String path, final Server server) throws Exception - { - final String worldName = getString((path == null ? "" : path + ".") + "world"); - if (worldName == null || worldName.isEmpty()) - { - return null; - } - final World world = server.getWorld(worldName); - if (world == null) - { - throw new Exception(_("invalidWorld")); - } - return new Location(world, - getDouble((path == null ? "" : path + ".") + "x", 0), - getDouble((path == null ? "" : path + ".") + "y", 0), - getDouble((path == null ? "" : path + ".") + "z", 0), - (float)getDouble((path == null ? "" : path + ".") + "yaw", 0), - (float)getDouble((path == null ? "" : path + ".") + "pitch", 0)); - } - - public void setProperty(final String path, final Location loc) - { - set((path == null ? "" : path + ".") + "world", loc.getWorld().getName()); - set((path == null ? "" : path + ".") + "x", loc.getX()); - set((path == null ? "" : path + ".") + "y", loc.getY()); - set((path == null ? "" : path + ".") + "z", loc.getZ()); - set((path == null ? "" : path + ".") + "yaw", loc.getYaw()); - set((path == null ? "" : path + ".") + "pitch", loc.getPitch()); - } - - @Override - public ItemStack getItemStack(final String path) - { - final ItemStack stack = new ItemStack( - Material.valueOf(getString(path + ".type", "AIR")), - getInt(path + ".amount", 1), - (short)getInt(path + ".damage", 0)); - final ConfigurationSection enchants = getConfigurationSection(path + ".enchant"); - if (enchants != null) - { - for (String enchant : enchants.getKeys(false)) - { - final Enchantment enchantment = Enchantment.getByName(enchant.toUpperCase(Locale.ENGLISH)); - if (enchantment == null) - { - continue; - } - final int level = getInt(path + ".enchant." + enchant, enchantment.getStartLevel()); - stack.addUnsafeEnchantment(enchantment, level); - } - } - return stack; - /* - * , - * (byte)getInt(path + ".data", 0) - */ - } - - public void setProperty(final String path, final ItemStack stack) - { - final Map<String, Object> map = new HashMap<String, Object>(); - map.put("type", stack.getType().toString()); - map.put("amount", stack.getAmount()); - map.put("damage", stack.getDurability()); - Map<Enchantment, Integer> enchantments = stack.getEnchantments(); - if (!enchantments.isEmpty()) - { - Map<String, Integer> enchant = new HashMap<String, Integer>(); - for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) - { - enchant.put(entry.getKey().getName().toLowerCase(Locale.ENGLISH), entry.getValue()); - } - map.put("enchant", enchant); - } - // getData().getData() is broken - //map.put("data", stack.getDurability()); - set(path, map); - } - - public long getLong(final String path, final long def) - { - try - { - final Number num = (Number)get(path); - return num == null ? def : num.longValue(); - } - catch (ClassCastException ex) - { - return def; - } - } - - @Override - public double getDouble(final String path, final double def) - { - try - { - Number num = (Number)get(path); - return num == null ? def : num.doubleValue(); - } - catch (ClassCastException ex) - { - return def; - } - } - - public void save() - { - try - { - save(configFile); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - } - - @Override - public synchronized void save(final File file) throws IOException - { - if (file == null) - { - throw new IllegalArgumentException("File cannot be null"); - } - - Files.createParentDirs(file); - - final String data = saveToString(); - - final OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), UTF8); - - try - { - writer.write(data); - } - finally - { - writer.close(); - } - } - - public Object getProperty(String path) - { - return get(path); - } - - public void setProperty(String path, Object object) - { - set(path, object); - } - - public void removeProperty(String path) - { - set(path, null); - } -} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java deleted file mode 100644 index 551833fc0..000000000 --- a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java +++ /dev/null @@ -1,448 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.textreader.IText; -import com.earth2me.essentials.textreader.KeywordReplacer; -import com.earth2me.essentials.textreader.TextInput; -import com.earth2me.essentials.textreader.TextPager; -import java.io.IOException; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.event.player.PlayerLoginEvent.Result; -import org.bukkit.event.player.*; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsPlayerListener implements Listener -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private final transient IEssentials ess; - private static final int AIR = Material.AIR.getId(); - private static final int BED = Material.BED_BLOCK.getId(); - - public EssentialsPlayerListener(final IEssentials parent) - { - this.ess = parent; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerRespawn(final PlayerRespawnEvent event) - { - final User user = ess.getUser(event.getPlayer()); - updateCompass(user); - user.setDisplayNick(); - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerChat(final PlayerChatEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.isMuted()) - { - event.setCancelled(true); - user.sendMessage(_("playerMuted")); - LOGGER.info(_("mutedUserSpeaks", user.getName())); - } - final Iterator<Player> it = event.getRecipients().iterator(); - while (it.hasNext()) - { - final User u = ess.getUser(it.next()); - if (u.isIgnoredPlayer(user.getName())) - { - it.remove(); - } - } - user.updateActivity(true); - user.setDisplayNick(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(final PlayerMoveEvent event) - { - if ((!ess.getSettings().cancelAfkOnMove() && !ess.getSettings().getFreezeAfkPlayers()) - || event.getFrom().getBlockX() == event.getTo().getBlockX() - && event.getFrom().getBlockZ() == event.getTo().getBlockZ() - && event.getFrom().getBlockY() == event.getTo().getBlockY()) - { - return; - } - - final User user = ess.getUser(event.getPlayer()); - if (user.isAfk() && ess.getSettings().getFreezeAfkPlayers()) - { - final Location from = event.getFrom(); - final Location to = event.getTo().clone(); - to.setX(from.getX()); - to.setY(from.getY()); - to.setZ(from.getZ()); - try - { - event.setTo(Util.getSafeDestination(to)); - } - catch (Exception ex) - { - event.setTo(to); - } - return; - } - final Location afk = user.getAfkPosition(); - if (afk == null || !event.getTo().getWorld().equals(afk.getWorld()) || afk.distanceSquared(event.getTo()) > 9) - { - user.updateActivity(true); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerQuit(final PlayerQuitEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (ess.getSettings().removeGodOnDisconnect() && user.isGodModeEnabled()) - { - user.toggleGodModeEnabled(); - } - ess.getVanishedPlayers().remove(user.getName()); - user.setLastLocation(); - user.updateActivity(false); - user.dispose(); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(final PlayerJoinEvent event) - { - ess.scheduleAsyncDelayedTask(new Runnable() - { - @Override - public void run() - { - delayedJoin(event.getPlayer()); - } - }); - } - - public void delayedJoin(final Player player) - { - ess.getBackup().onPlayerJoin(); - final User user = ess.getUser(player); - user.setDisplayNick(); - updateCompass(user); - user.setLastLogin(System.currentTimeMillis()); - user.updateActivity(false); - - for (String p : ess.getVanishedPlayers()) - { - if (!user.isAuthorized("essentials.vanish.see")) - { - user.hidePlayer(ess.getUser(p)); - } - } - - if (user.isAuthorized("essentials.sleepingignored")) - { - user.setSleepingIgnored(true); - } - - if (!ess.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd")) - { - try - { - final IText input = new TextInput(user, "motd", true, ess); - final IText output = new KeywordReplacer(input, user, ess); - final TextPager pager = new TextPager(output, true); - pager.showPage("1", null, "motd", user); - } - catch (IOException ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.WARNING, ex.getMessage(), ex); - } - else - { - LOGGER.log(Level.WARNING, ex.getMessage()); - } - } - } - - if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) - { - final List<String> mail = user.getMails(); - if (mail.isEmpty()) - { - user.sendMessage(_("noNewMail")); - } - else - { - user.sendMessage(_("youHaveNewMail", mail.size())); - } - } - } - - private void updateCompass(final User user) - { - Location loc = user.getHome(user.getLocation()); - if (loc == null) - { - loc = user.getBedSpawnLocation(); - } - if (loc != null) - { - final Location updateLoc = loc; - ess.scheduleSyncDelayedTask(new Runnable() - { - @Override - public void run() - { - user.setCompassTarget(updateLoc); - } - }); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerLogin(final PlayerLoginEvent event) - { - switch (event.getResult()) - { - case ALLOWED: - case KICK_FULL: - case KICK_BANNED: - break; - default: - return; - } - - final User user = ess.getUser(event.getPlayer()); - if (user.isNPC()) - { - user.setNPC(false); - } - - final long currentTime = System.currentTimeMillis(); - final boolean banExpired = user.checkBanTimeout(currentTime); - user.checkMuteTimeout(currentTime); - user.checkJailTimeout(currentTime); - - if (!banExpired && (user.isBanned() || event.getResult() == Result.KICK_BANNED)) - { - final String banReason = user.getBanReason(); - event.disallow(Result.KICK_BANNED, banReason != null && !banReason.isEmpty() && !banReason.equalsIgnoreCase("ban") ? banReason : _("defaultBanReason")); - return; - } - - if (event.getResult() == Result.KICK_FULL && !user.isAuthorized("essentials.joinfullserver")) - { - event.disallow(Result.KICK_FULL, _("serverFull")); - return; - } - event.allow(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerTeleport(final PlayerTeleportEvent event) - { - final boolean backListener = ess.getSettings().registerBackInListener(); - final boolean teleportInvulnerability = ess.getSettings().isTeleportInvulnerability(); - if (backListener || teleportInvulnerability) - { - final User user = ess.getUser(event.getPlayer()); - //There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports. - if (backListener && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) - { - user.setLastLocation(); - } - if (teleportInvulnerability) - { - user.enableInvulnerabilityAfterTeleport(); - } - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerEggThrow(final PlayerEggThrowEvent event) - { - final User user = ess.getUser(event.getPlayer()); - final ItemStack stack = new ItemStack(Material.EGG, 1); - if (user.hasUnlimited(stack)) - { - user.getInventory().addItem(stack); - user.updateInventory(); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.hasUnlimited(new ItemStack(event.getBucket()))) - { - event.getItemStack().setType(event.getBucket()); - ess.scheduleSyncDelayedTask(new Runnable() - { - @Override - public void run() - { - user.updateInventory(); - } - }); - } - } - private final static List<String> COMMANDS = Arrays.asList("msg", "r", "mail", "m", "t", "whisper", "emsg", "tell", "er", "reply", "ereply", "email"); - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) - { - final Player player = event.getPlayer(); - final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); - if (COMMANDS.contains(cmd)) - { - for (Player onlinePlayer : ess.getServer().getOnlinePlayers()) - { - final User spyer = ess.getUser(onlinePlayer); - if (spyer.isSocialSpyEnabled() && !player.equals(onlinePlayer)) - { - onlinePlayer.sendMessage(player.getDisplayName() + " : " + event.getMessage()); - } - } - } - else if (!cmd.equalsIgnoreCase("afk")) - { - final User user = ess.getUser(player); - user.updateActivity(true); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) - { - final User user = ess.getUser(event.getPlayer()); - final String newWorld = event.getPlayer().getLocation().getWorld().getName(); - user.setDisplayNick(); - updateCompass(user); - if (ess.getSettings().getNoGodWorlds().contains(newWorld) && user.isGodModeEnabledRaw()) - { - user.sendMessage(_("noGodWorldWarning")); - } - - if (!event.getPlayer().getWorld().getName().equals(newWorld)) - { - user.sendMessage(_("currentWorld", newWorld)); - } - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerInteract(final PlayerInteractEvent event) - { - switch (event.getAction()) - { - case RIGHT_CLICK_BLOCK: - if (!event.isCancelled() && event.getClickedBlock().getTypeId() == BED && ess.getSettings().getUpdateBedAtDaytime()) - { - Player player = event.getPlayer(); - player.setBedSpawnLocation(event.getClickedBlock().getLocation()); - player.sendMessage(_("homeSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ())); - } - break; - case LEFT_CLICK_AIR: - case LEFT_CLICK_BLOCK: - if (event.getItem() != null && event.getItem().getTypeId() != AIR) - { - final User user = ess.getUser(event.getPlayer()); - if (user.hasPowerTools() && user.arePowerToolsEnabled() && usePowertools(user, event.getItem().getTypeId())) - { - event.setCancelled(true); - } - } - break; - default: - break; - } - } - - private boolean usePowertools(final User user, final int id) - { - final List<String> commandList = user.getPowertool(id); - if (commandList == null || commandList.isEmpty()) - { - return false; - } - boolean used = false; - // We need to loop through each command and execute - for (final String command : commandList) - { - if (command.contains("{player}")) - { - continue; - } - else if (command.startsWith("c:")) - { - used = true; - user.chat(command.substring(2)); - } - else - { - used = true; - ess.scheduleSyncDelayedTask( - new Runnable() - { - @Override - public void run() - { - user.getServer().dispatchCommand(user.getBase(), command); - } - }); - } - } - return used; - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerPickupItem(final PlayerPickupItemEvent event) - { - if (ess.getSettings().getDisableItemPickupWhileAfk()) - { - if (ess.getUser(event.getPlayer()).isAfk()) - { - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onInventoryClickEvent(final InventoryClickEvent event) - { - if (event.getView().getTopInventory().getType() == InventoryType.PLAYER) - { - final User user = ess.getUser(event.getWhoClicked()); - final User invOwner = ess.getUser(event.getView().getPlayer()); - if (user.isInvSee() && (!user.isAuthorized("essentials.invsee.modify") - || invOwner.isAuthorized("essentials.invsee.preventmodify"))) - { - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onInventoryCloseEvent(final InventoryCloseEvent event) - { - if (event.getView().getTopInventory().getType() == InventoryType.PLAYER) - { - final User user = ess.getUser(event.getPlayer()); - user.setInvSee(false); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java b/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java deleted file mode 100644 index 2ec8538ca..000000000 --- a/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.earth2me.essentials; - -import java.util.logging.Level; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.event.server.PluginEnableEvent; - - -public class EssentialsPluginListener implements Listener, IConf -{ - private final transient IEssentials ess; - - public EssentialsPluginListener(final IEssentials ess) - { - this.ess = ess; - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginEnable(final PluginEnableEvent event) - { - ess.getPermissionsHandler().checkPermissions(); - ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin()); - if (!ess.getPaymentMethod().hasMethod() && ess.getPaymentMethod().setMethod(ess.getServer().getPluginManager())) - { - ess.getLogger().log(Level.INFO, "Payment method found (" + ess.getPaymentMethod().getMethod().getLongName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")"); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginDisable(final PluginDisableEvent event) - { - ess.getPermissionsHandler().checkPermissions(); - ess.getAlternativeCommandsHandler().removePlugin(event.getPlugin()); - // Check to see if the plugin thats being disabled is the one we are using - if (ess.getPaymentMethod() != null && ess.getPaymentMethod().hasMethod() && ess.getPaymentMethod().checkDisabled(event.getPlugin())) - { - ess.getPaymentMethod().reset(); - ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments."); - } - } - - @Override - public void reloadConfig() - { - ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); - ess.getPermissionsHandler().checkPermissions(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java index 95cf77521..34aecddc0 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java @@ -1,5 +1,11 @@ package com.earth2me.essentials; +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.UserData.TimestampType; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; @@ -11,7 +17,7 @@ import org.bukkit.entity.Player; public class EssentialsTimer implements Runnable { private final transient IEssentials ess; - private final transient Set<User> onlineUsers = new HashSet<User>(); + private final transient Set<IUser> onlineUsers = new HashSet<IUser>(); private transient long lastPoll = System.currentTimeMillis(); private final transient LinkedList<Float> history = new LinkedList<Float>(); @@ -41,12 +47,34 @@ public class EssentialsTimer implements Runnable lastPoll = currentTime; for (Player player : ess.getServer().getOnlinePlayers()) { + try { - final User user = ess.getUser(player); + final IUser user = ess.getUser(player); onlineUsers.add(user); user.setLastOnlineActivity(currentTime); user.checkActivity(); + + boolean mailDisabled = false; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + mailDisabled = settings.getData().getCommands().isDisabled("mail"); + } + finally + { + settings.unlock(); + } + // New mail notification + if (user != null && !mailDisabled && Permissions.MAIL.isAuthorized(user) && !user.gotMailInfo()) + { + final List<String> mail = user.getMails(); + if (mail != null && !mail.isEmpty()) + { + user.sendMessage(_("youHaveNewMail", mail.size())); + } + } } catch (Exception e) { @@ -54,13 +82,13 @@ public class EssentialsTimer implements Runnable } } - final Iterator<User> iterator = onlineUsers.iterator(); + final Iterator<IUser> iterator = onlineUsers.iterator(); while (iterator.hasNext()) { - final User user = iterator.next(); - if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getLastLogout()) + final IUser user = iterator.next(); + if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getTimestamp(TimestampType.LOGOUT)) { - user.setLastLogout(user.getLastOnlineActivity()); + user.setTimestamp(TimestampType.LOGOUT, user.getLastOnlineActivity()); iterator.remove(); continue; } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java b/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java deleted file mode 100644 index bc0de9fa4..000000000 --- a/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java +++ /dev/null @@ -1,816 +0,0 @@ -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; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsUpgrade -{ - private final static Logger LOGGER = Logger.getLogger("Minecraft"); - private final transient IEssentials ess; - private final transient EssentialsConf doneFile; - - EssentialsUpgrade(final IEssentials essentials) - { - ess = essentials; - if (!ess.getDataFolder().exists()) - { - ess.getDataFolder().mkdirs(); - } - doneFile = new EssentialsConf(new File(ess.getDataFolder(), "upgrades-done.yml")); - doneFile.load(); - } - - private void moveWorthValuesToWorthYml() - { - if (doneFile.getBoolean("moveWorthValuesToWorthYml", false)) - { - return; - } - try - { - final File configFile = new File(ess.getDataFolder(), "config.yml"); - if (!configFile.exists()) - { - return; - } - final EssentialsConf conf = new EssentialsConf(configFile); - conf.load(); - final Worth worth = new Worth(ess.getDataFolder()); - boolean found = false; - for (Material mat : Material.values()) - { - final int id = mat.getId(); - final double value = conf.getDouble("worth-" + id, Double.NaN); - if (!Double.isNaN(value)) - { - found = true; - worth.setPrice(new ItemStack(mat, 1, (short)0, (byte)0), value); - } - } - if (found) - { - removeLinesFromConfig(configFile, "\\s*#?\\s*worth-[0-9]+.*", "# Worth values have been moved to worth.yml"); - } - doneFile.setProperty("moveWorthValuesToWorthYml", true); - doneFile.save(); - } - catch (Throwable e) - { - LOGGER.log(Level.SEVERE, _("upgradingFilesError"), e); - } - } - - private void moveMotdRulesToFile(String name) - { - if (doneFile.getBoolean("move" + name + "ToFile", false)) - { - return; - } - try - { - final File file = new File(ess.getDataFolder(), name + ".txt"); - if (file.exists()) - { - return; - } - final File configFile = new File(ess.getDataFolder(), "config.yml"); - if (!configFile.exists()) - { - return; - } - final EssentialsConf conf = new EssentialsConf(configFile); - conf.load(); - List<String> lines = conf.getStringList(name); - if (lines != null && !lines.isEmpty()) - { - if (!file.createNewFile()) - { - throw new IOException("Failed to create file " + file); - } - PrintWriter writer = new PrintWriter(file); - - for (String line : lines) - { - writer.println(line); - } - writer.close(); - } - doneFile.setProperty("move" + name + "ToFile", true); - doneFile.save(); - } - catch (Throwable e) - { - LOGGER.log(Level.SEVERE, _("upgradingFilesError"), e); - } - } - - private void removeLinesFromConfig(File file, String regex, String info) throws Exception - { - boolean needUpdate = false; - final BufferedReader bReader = new BufferedReader(new FileReader(file)); - final File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder()); - final BufferedWriter bWriter = new BufferedWriter(new FileWriter(tempFile)); - do - { - final String line = bReader.readLine(); - if (line == null) - { - break; - } - if (line.matches(regex)) - { - if (!needUpdate && info != null) - { - bWriter.write(info, 0, info.length()); - bWriter.newLine(); - } - needUpdate = true; - } - else - { - if (line.endsWith("\r\n")) - { - bWriter.write(line, 0, line.length() - 2); - } - else if (line.endsWith("\r") || line.endsWith("\n")) - { - bWriter.write(line, 0, line.length() - 1); - } - else - { - bWriter.write(line, 0, line.length()); - } - bWriter.newLine(); - } - } - while (true); - bReader.close(); - bWriter.close(); - if (needUpdate) - { - if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup")))) - { - throw new Exception(_("configFileMoveError")); - } - if (!tempFile.renameTo(file)) - { - throw new Exception(_("configFileRenameError")); - } - } - else - { - tempFile.delete(); - } - } - - private void updateUsersToNewDefaultHome() - { - if (doneFile.getBoolean("updateUsersToNewDefaultHome", false)) - { - return; - } - final File userdataFolder = new File(ess.getDataFolder(), "userdata"); - if (!userdataFolder.exists() || !userdataFolder.isDirectory()) - { - return; - } - final File[] userFiles = userdataFolder.listFiles(); - - for (File file : userFiles) - { - if (!file.isFile() || !file.getName().endsWith(".yml")) - { - continue; - } - final EssentialsConf config = new EssentialsConf(file); - try - { - config.load(); - if (config.hasProperty("home") && !config.hasProperty("home.default")) - { - @SuppressWarnings("unchecked") - final List<Object> vals = (List<Object>)config.getProperty("home"); - if (vals == null) - { - continue; - } - World world = ess.getServer().getWorlds().get(0); - if (vals.size() > 5) - { - world = ess.getServer().getWorld((String)vals.get(5)); - } - if (world != null) - { - final Location loc = new Location( - world, - ((Number)vals.get(0)).doubleValue(), - ((Number)vals.get(1)).doubleValue(), - ((Number)vals.get(2)).doubleValue(), - ((Number)vals.get(3)).floatValue(), - ((Number)vals.get(4)).floatValue()); - - final String worldName = world.getName().toLowerCase(Locale.ENGLISH); - if (worldName != null && !worldName.isEmpty()) - { - config.removeProperty("home"); - config.setProperty("home.default", worldName); - config.setProperty("home.worlds." + worldName, loc); - config.save(); - } - } - } - } - catch (RuntimeException ex) - { - LOGGER.log(Level.INFO, "File: " + file.toString()); - throw ex; - } - } - doneFile.setProperty("updateUsersToNewDefaultHome", true); - doneFile.save(); - } - - private void updateUsersPowerToolsFormat() - { - if (doneFile.getBoolean("updateUsersPowerToolsFormat", false)) - { - return; - } - final File userdataFolder = new File(ess.getDataFolder(), "userdata"); - if (!userdataFolder.exists() || !userdataFolder.isDirectory()) - { - return; - } - final File[] userFiles = userdataFolder.listFiles(); - - for (File file : userFiles) - { - if (!file.isFile() || !file.getName().endsWith(".yml")) - { - continue; - } - final EssentialsConf config = new EssentialsConf(file); - try - { - config.load(); - if (config.hasProperty("powertools")) - { - @SuppressWarnings("unchecked") - final Map<String, Object> powertools = config.getConfigurationSection("powertools").getValues(false); - if (powertools == null) - { - continue; - } - for (Map.Entry<String, Object> entry : powertools.entrySet()) - { - if (entry.getValue() instanceof String) - { - List<String> temp = new ArrayList<String>(); - temp.add((String)entry.getValue()); - ((Map<String, Object>)powertools).put(entry.getKey(), temp); - } - } - config.save(); - } - } - catch (RuntimeException ex) - { - LOGGER.log(Level.INFO, "File: " + file.toString()); - throw ex; - } - } - doneFile.setProperty("updateUsersPowerToolsFormat", true); - doneFile.save(); - } - - private void updateUsersHomesFormat() - { - if (doneFile.getBoolean("updateUsersHomesFormat", false)) - { - return; - } - final File userdataFolder = new File(ess.getDataFolder(), "userdata"); - if (!userdataFolder.exists() || !userdataFolder.isDirectory()) - { - return; - } - final File[] userFiles = userdataFolder.listFiles(); - - for (File file : userFiles) - { - if (!file.isFile() || !file.getName().endsWith(".yml")) - { - continue; - } - final EssentialsConf config = new EssentialsConf(file); - try - { - - config.load(); - if (config.hasProperty("home") && config.hasProperty("home.default")) - { - @SuppressWarnings("unchecked") - final String defworld = (String)config.getProperty("home.default"); - final Location defloc = getFakeLocation(config, "home.worlds." + defworld); - if (defloc != null) - { - config.setProperty("homes.home", defloc); - } - - Set<String> worlds = config.getConfigurationSection("home.worlds").getKeys(false); - Location loc; - String worldName; - - if (worlds == null) - { - continue; - } - for (String world : worlds) - { - if (defworld.equalsIgnoreCase(world)) - { - continue; - } - loc = getFakeLocation(config, "home.worlds." + world); - if (loc == null) - { - continue; - } - worldName = loc.getWorld().getName().toLowerCase(Locale.ENGLISH); - if (worldName != null && !worldName.isEmpty()) - { - config.setProperty("homes." + worldName, loc); - } - } - config.removeProperty("home"); - config.save(); - } - - } - catch (RuntimeException ex) - { - LOGGER.log(Level.INFO, "File: " + file.toString()); - throw ex; - } - } - doneFile.setProperty("updateUsersHomesFormat", true); - doneFile.save(); - } - - private void moveUsersDataToUserdataFolder() - { - final File usersFile = new File(ess.getDataFolder(), "users.yml"); - if (!usersFile.exists()) - { - return; - } - final EssentialsConf usersConfig = new EssentialsConf(usersFile); - usersConfig.load(); - for (String username : usersConfig.getKeys(false)) - { - final User user = new User(new OfflinePlayer(username, ess), ess); - final String nickname = usersConfig.getString(username + ".nickname"); - if (nickname != null && !nickname.isEmpty() && !nickname.equals(username)) - { - user.setNickname(nickname); - } - final List<String> mails = usersConfig.getStringList(username + ".mail"); - if (mails != null && !mails.isEmpty()) - { - user.setMails(mails); - } - if (!user.hasHome()) - { - @SuppressWarnings("unchecked") - final List<Object> vals = (List<Object>)usersConfig.getProperty(username + ".home"); - if (vals != null) - { - World world = ess.getServer().getWorlds().get(0); - if (vals.size() > 5) - { - world = getFakeWorld((String)vals.get(5)); - } - if (world != null) - { - user.setHome("home", new Location(world, - ((Number)vals.get(0)).doubleValue(), - ((Number)vals.get(1)).doubleValue(), - ((Number)vals.get(2)).doubleValue(), - ((Number)vals.get(3)).floatValue(), - ((Number)vals.get(4)).floatValue())); - } - } - } - } - usersFile.renameTo(new File(usersFile.getAbsolutePath() + ".old")); - } - - private void convertWarps() - { - final File warpsFolder = new File(ess.getDataFolder(), "warps"); - if (!warpsFolder.exists()) - { - warpsFolder.mkdirs(); - } - final File[] listOfFiles = warpsFolder.listFiles(); - if (listOfFiles.length >= 1) - { - for (int i = 0; i < listOfFiles.length; i++) - { - final String filename = listOfFiles[i].getName(); - if (listOfFiles[i].isFile() && filename.endsWith(".dat")) - { - try - { - final BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i])); - double x, y, z; - float yaw, pitch; - String worldName; - try - { - if (!rx.ready()) - { - continue; - } - x = Double.parseDouble(rx.readLine().trim()); - if (!rx.ready()) - { - continue; - } - y = Double.parseDouble(rx.readLine().trim()); - if (!rx.ready()) - { - continue; - } - z = Double.parseDouble(rx.readLine().trim()); - if (!rx.ready()) - { - continue; - } - yaw = Float.parseFloat(rx.readLine().trim()); - if (!rx.ready()) - { - continue; - } - pitch = Float.parseFloat(rx.readLine().trim()); - worldName = rx.readLine(); - } - finally - { - rx.close(); - } - World w = null; - for (World world : ess.getServer().getWorlds()) - { - if (world.getEnvironment() != World.Environment.NETHER) - { - w = world; - break; - } - } - if (worldName != null) - { - worldName = worldName.trim(); - World w1 = null; - w1 = getFakeWorld(worldName); - if (w1 != null) - { - w = w1; - } - } - final Location loc = new Location(w, x, y, z, yaw, pitch); - ess.getWarps().setWarp(filename.substring(0, filename.length() - 4), loc); - if (!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old"))) - { - throw new Exception(_("fileRenameError", filename)); - } - } - catch (Exception ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - - } - final File warpFile = new File(ess.getDataFolder(), "warps.txt"); - if (warpFile.exists()) - { - try - { - final BufferedReader rx = new BufferedReader(new FileReader(warpFile)); - try - { - for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":")) - { - if (parts.length < 6) - { - continue; - } - final String name = parts[0]; - final double x = Double.parseDouble(parts[1].trim()); - final double y = Double.parseDouble(parts[2].trim()); - final double z = Double.parseDouble(parts[3].trim()); - final float yaw = Float.parseFloat(parts[4].trim()); - final float pitch = Float.parseFloat(parts[5].trim()); - if (name.isEmpty()) - { - continue; - } - World w = null; - for (World world : ess.getServer().getWorlds()) - { - if (world.getEnvironment() != World.Environment.NETHER) - { - w = world; - break; - } - } - final Location loc = new Location(w, x, y, z, yaw, pitch); - ess.getWarps().setWarp(name, loc); - if (!warpFile.renameTo(new File(ess.getDataFolder(), "warps.txt.old"))) - { - throw new Exception(_("fileRenameError", "warps.txt")); - } - } - } - finally - { - rx.close(); - } - } - catch (Exception ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - - private void sanitizeAllUserFilenames() - { - if (doneFile.getBoolean("sanitizeAllUserFilenames", false)) - { - return; - } - final File usersFolder = new File(ess.getDataFolder(), "userdata"); - if (!usersFolder.exists()) - { - return; - } - final File[] listOfFiles = usersFolder.listFiles(); - for (int i = 0; i < listOfFiles.length; i++) - { - final String filename = listOfFiles[i].getName(); - if (!listOfFiles[i].isFile() || !filename.endsWith(".yml")) - { - continue; - } - final String sanitizedFilename = Util.sanitizeFileName(filename.substring(0, filename.length() - 4)) + ".yml"; - if (sanitizedFilename.equals(filename)) - { - continue; - } - final File tmpFile = new File(listOfFiles[i].getParentFile(), sanitizedFilename + ".tmp"); - final File newFile = new File(listOfFiles[i].getParentFile(), sanitizedFilename); - if (!listOfFiles[i].renameTo(tmpFile)) - { - LOGGER.log(Level.WARNING, _("userdataMoveError", filename, sanitizedFilename)); - continue; - } - if (newFile.exists()) - { - LOGGER.log(Level.WARNING, _("duplicatedUserdata", filename, sanitizedFilename)); - continue; - } - if (!tmpFile.renameTo(newFile)) - { - LOGGER.log(Level.WARNING, _("userdataMoveBackError", sanitizedFilename, sanitizedFilename)); - } - } - doneFile.setProperty("sanitizeAllUserFilenames", true); - doneFile.save(); - } - - private World getFakeWorld(final String name) - { - final File bukkitDirectory = ess.getDataFolder().getParentFile().getParentFile(); - final File worldDirectory = new File(bukkitDirectory, name); - if (worldDirectory.exists() && worldDirectory.isDirectory()) - { - return new FakeWorld(worldDirectory.getName(), World.Environment.NORMAL); - } - return null; - } - - public Location getFakeLocation(EssentialsConf config, String path) - { - String worldName = config.getString((path != null ? path + "." : "") + "world"); - if (worldName == null || worldName.isEmpty()) - { - return null; - } - World world = getFakeWorld(worldName); - if (world == null) - { - return null; - } - return new Location(world, - config.getDouble((path != null ? path + "." : "") + "x", 0), - config.getDouble((path != null ? path + "." : "") + "y", 0), - config.getDouble((path != null ? path + "." : "") + "z", 0), - (float)config.getDouble((path != null ? path + "." : "") + "yaw", 0), - (float)config.getDouble((path != null ? path + "." : "") + "pitch", 0)); - } - - private void deleteOldItemsCsv() - { - if (doneFile.getBoolean("deleteOldItemsCsv", false)) - { - return; - } - final File file = new File(ess.getDataFolder(), "items.csv"); - if (file.exists()) - { - try - { - final Set<BigInteger> oldconfigs = new HashSet<BigInteger>(); - oldconfigs.add(new BigInteger("66ec40b09ac167079f558d1099e39f10", 16)); // sep 1 - oldconfigs.add(new BigInteger("34284de1ead43b0bee2aae85e75c041d", 16)); // crlf - oldconfigs.add(new BigInteger("c33bc9b8ee003861611bbc2f48eb6f4f", 16)); // jul 24 - oldconfigs.add(new BigInteger("6ff17925430735129fc2a02f830c1daa", 16)); // crlf - - MessageDigest digest = ManagedFile.getDigest(); - final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); - final DigestInputStream dis = new DigestInputStream(bis, digest); - final byte[] buffer = new byte[1024]; - try - { - while (dis.read(buffer) != -1) - { - } - } - finally - { - dis.close(); - } - - BigInteger hash = new BigInteger(1, digest.digest()); - if (oldconfigs.contains(hash) && !file.delete()) - { - throw new IOException("Could not delete file " + file.toString()); - } - doneFile.setProperty("deleteOldItemsCsv", true); - doneFile.save(); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - } - - 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(); - Set<String> keys = config.getKeys(false); - 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(); - Set<String> keys = config.getKeys(false); - 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(); - } - - private void warnMetrics() - { - if (doneFile.getBoolean("warnMetrics", false)) - { - return; - } - ess.getSettings().setMetricsEnabled(false); - doneFile.setProperty("warnMetrics", true); - doneFile.save(); - } - - public void beforeSettings() - { - if (!ess.getDataFolder().exists()) - { - ess.getDataFolder().mkdirs(); - } - moveWorthValuesToWorthYml(); - moveMotdRulesToFile("motd"); - moveMotdRulesToFile("rules"); - } - - public void afterSettings() - { - sanitizeAllUserFilenames(); - updateUsersToNewDefaultHome(); - moveUsersDataToUserdataFolder(); - convertWarps(); - updateUsersPowerToolsFormat(); - updateUsersHomesFormat(); - deleteOldItemsCsv(); - updateSpawnsToNewSpawnsConfig(); - updateJailsToNewJailsConfig(); - warnMetrics(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/I18n.java b/Essentials/src/com/earth2me/essentials/I18n.java index 97d500a6a..de4afec94 100644 --- a/Essentials/src/com/earth2me/essentials/I18n.java +++ b/Essentials/src/com/earth2me/essentials/I18n.java @@ -1,5 +1,6 @@ package com.earth2me.essentials; +import com.earth2me.essentials.api.IEssentials; import com.earth2me.essentials.api.II18n; import java.io.File; import java.io.FileInputStream; @@ -43,6 +44,7 @@ public class I18n implements II18n instance = null; } + @Override public Locale getCurrentLocale() { return currentLocale; diff --git a/Essentials/src/com/earth2me/essentials/IConf.java b/Essentials/src/com/earth2me/essentials/IConf.java deleted file mode 100644 index 580e6232f..000000000 --- a/Essentials/src/com/earth2me/essentials/IConf.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.earth2me.essentials; - -/** - * @deprecated New interface will be IReload in api package - */ -@Deprecated -public interface IConf { - public void reloadConfig(); -} diff --git a/Essentials/src/com/earth2me/essentials/IEssentials.java b/Essentials/src/com/earth2me/essentials/IEssentials.java deleted file mode 100644 index f12798db3..000000000 --- a/Essentials/src/com/earth2me/essentials/IEssentials.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.api.IJails; -import com.earth2me.essentials.metrics.Metrics; -import com.earth2me.essentials.perm.PermissionsHandler; -import com.earth2me.essentials.register.payment.Methods; -import java.util.List; -import org.bukkit.World; -import org.bukkit.command.Command; -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, IEssentialsModule module); - - User getUser(Object base); - - I18n getI18n(); - - User getOfflineUser(String name); - - World getWorld(String name); - - int broadcastMessage(IUser sender, String message); - - ISettings getSettings(); - - BukkitScheduler getScheduler(); - - IJails getJails(); - - Warps getWarps(); - - Worth getWorth(); - - Backup getBackup(); - - Methods getPaymentMethod(); - - int scheduleAsyncDelayedTask(Runnable run); - - int scheduleSyncDelayedTask(Runnable run); - - int scheduleSyncDelayedTask(Runnable run, long delay); - - int scheduleSyncRepeatingTask(final Runnable run, long delay, long period); - - TNTExplodeListener getTNTListener(); - - PermissionsHandler getPermissionsHandler(); - - AlternativeCommandsHandler getAlternativeCommandsHandler(); - - void showError(final CommandSender sender, final Throwable exception, final String commandLabel); - - ItemDb getItemDb(); - - UserMap getUserMap(); - - Metrics getMetrics(); - - void setMetrics(Metrics metrics); - - EssentialsTimer getTimer(); - - List<String> getVanishedPlayers(); -} diff --git a/Essentials/src/com/earth2me/essentials/IReplyTo.java b/Essentials/src/com/earth2me/essentials/IReplyTo.java deleted file mode 100644 index 5bef5fced..000000000 --- a/Essentials/src/com/earth2me/essentials/IReplyTo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.earth2me.essentials; - -import org.bukkit.command.CommandSender; - -public interface IReplyTo { - public void setReplyTo(CommandSender user); - - public CommandSender getReplyTo(); -} diff --git a/Essentials/src/com/earth2me/essentials/ISettings.java b/Essentials/src/com/earth2me/essentials/ISettings.java deleted file mode 100644 index 3c6763cbe..000000000 --- a/Essentials/src/com/earth2me/essentials/ISettings.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.commands.IEssentialsCommand; -import com.earth2me.essentials.signs.EssentialsSign; -import com.earth2me.essentials.textreader.IText; -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.bukkit.ChatColor; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.event.EventPriority; - - -public interface ISettings extends IConf -{ - boolean areSignsDisabled(); - - IText getAnnounceNewPlayerFormat(); - - boolean getAnnounceNewPlayers(); - - String getNewPlayerKit(); - - String getBackupCommand(); - - long getBackupInterval(); - - MessageFormat getChatFormat(String group); - - int getChatRadius(); - - double getCommandCost(IEssentialsCommand cmd); - - double getCommandCost(String label); - - String getCurrencySymbol(); - - int getOversizedStackSize(); - - int getDefaultStackSize(); - - double getHealCooldown(); - - Map<String, Object> getKit(String name); - - ConfigurationSection getKits(); - - String getLocale(); - - String getNewbieSpawn(); - - String getNicknamePrefix(); - - ChatColor getOperatorColor() throws Exception; - - boolean getPerWarpPermission(); - - boolean getProtectBoolean(final String configName, boolean def); - - int getProtectCreeperMaxHeight(); - - List<Integer> getProtectList(final String configName); - - boolean getProtectPreventSpawn(final String creatureName); - - String getProtectString(final String configName); - - boolean getRespawnAtHome(); - - Set getMultipleHomes(); - - int getHomeLimit(String set); - - int getHomeLimit(User user); - - boolean getSortListByGroups(); - - int getSpawnMobLimit(); - - int getStartingBalance(); - - double getTeleportCooldown(); - - double getTeleportDelay(); - - boolean hidePermissionlessHelp(); - - boolean isCommandDisabled(final IEssentialsCommand cmd); - - boolean isCommandDisabled(String label); - - boolean isCommandOverridden(String name); - - boolean isCommandRestricted(IEssentialsCommand cmd); - - boolean isCommandRestricted(String label); - - boolean isDebug(); - - boolean isEcoDisabled(); - - boolean isTradeInStacks(int id); - - List<Integer> itemSpawnBlacklist(); - - List<EssentialsSign> enabledSigns(); - - boolean permissionBasedItemSpawn(); - - boolean showNonEssCommandsInHelp(); - - boolean spawnIfNoHome(); - - boolean warnOnBuildDisallow(); - - boolean warnOnSmite(); - - double getMaxMoney(); - - double getMinMoney(); - - boolean isEcoLogEnabled(); - - boolean isEcoLogUpdateEnabled(); - - boolean removeGodOnDisconnect(); - - boolean changeDisplayName(); - - boolean changePlayerListName(); - - boolean isPlayerCommand(String string); - - boolean useBukkitPermissions(); - - boolean addPrefixSuffix(); - - boolean disablePrefix(); - - boolean disableSuffix(); - - long getAutoAfk(); - - long getAutoAfkKick(); - - boolean getFreezeAfkPlayers(); - - boolean cancelAfkOnMove(); - - boolean areDeathMessagesEnabled(); - - public void setDebug(boolean debug); - - Set<String> getNoGodWorlds(); - - boolean getUpdateBedAtDaytime(); - - boolean getRepairEnchanted(); - - boolean isWorldTeleportPermissions(); - - boolean isWorldHomePermissions(); - - boolean registerBackInListener(); - - boolean getDisableItemPickupWhileAfk(); - - EventPriority getRespawnPriority(); - - long getTpaAcceptCancellation(); - - boolean isMetricsEnabled(); - - void setMetricsEnabled(boolean metricsEnabled); - - long getTeleportInvulnerability(); - - boolean isTeleportInvulnerability(); - - long getLoginAttackDelay(); -} diff --git a/Essentials/src/com/earth2me/essentials/IUser.java b/Essentials/src/com/earth2me/essentials/IUser.java deleted file mode 100644 index bfa9ed146..000000000 --- a/Essentials/src/com/earth2me/essentials/IUser.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.commands.IEssentialsCommand; -import org.bukkit.Location; -import org.bukkit.entity.Player; - - -/** - * @deprecated This will be moved to the api package soon - */ -@Deprecated -public interface IUser extends Player -{ - 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); - - boolean canAfford(double value); - - String getGroup(); - - void setLastLocation(); - - Location getHome(String name) throws Exception; - - Location getHome(Location loc) throws Exception; - - boolean isHidden(); - - Teleport getTeleport(); - - void setJail(String jail); -} diff --git a/Essentials/src/com/earth2me/essentials/ItemDb.java b/Essentials/src/com/earth2me/essentials/ItemDb.java index e3df50bab..cfcc00dd2 100644 --- a/Essentials/src/com/earth2me/essentials/ItemDb.java +++ b/Essentials/src/com/earth2me/essentials/ItemDb.java @@ -1,16 +1,22 @@ package com.earth2me.essentials; -import com.earth2me.essentials.api.IItemDb; +import com.earth2me.essentials.storage.ManagedFile; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IItemDb; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.regex.Pattern; +import lombok.Cleanup; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -public class ItemDb implements IConf, IItemDb +public class ItemDb implements IItemDb { private final transient IEssentials ess; @@ -19,12 +25,12 @@ public class ItemDb implements IConf, IItemDb this.ess = ess; file = new ManagedFile("items.csv", ess); } - private final transient Map<String, Integer> items = new HashMap<String, Integer>(); - private final transient Map<String, Short> durabilities = new HashMap<String, Short>(); + private final transient Map<String, Long> items = new HashMap<String, Long>(); private final transient ManagedFile file; + private static final Pattern SPLIT = Pattern.compile("[^a-zA-Z0-9]"); @Override - public void reloadConfig() + public void onReload() { final List<String> lines = file.getLines(); @@ -33,28 +39,52 @@ public class ItemDb implements IConf, IItemDb return; } - durabilities.clear(); items.clear(); for (String line : lines) { - line = line.trim().toLowerCase(Locale.ENGLISH); + line = line.trim(); if (line.length() > 0 && line.charAt(0) == '#') { continue; } - final String[] parts = line.split("[^a-z0-9]"); + final String[] parts = SPLIT.split(line); if (parts.length < 2) { continue; } - final int numeric = Integer.parseInt(parts[1]); + final long numeric = Integer.parseInt(parts[1]); + + final long durability = parts.length > 2 && !(parts[2].length() == 1 && parts[2].charAt(0) == '0') ? Short.parseShort(parts[2]) : 0; + items.put(parts[0].toLowerCase(Locale.ENGLISH), numeric | (durability << 32)); + } + } + + public ItemStack get(final String id, final IUser user) throws Exception + { + final ItemStack stack = get(id.toLowerCase(Locale.ENGLISH)); + + @Cleanup + com.earth2me.essentials.api.ISettings settings = ess.getSettings(); + settings.acquireReadLock(); - durabilities.put(parts[0].toLowerCase(Locale.ENGLISH), parts.length > 2 && !parts[2].equals("0") ? Short.parseShort(parts[2]) : 0); - items.put(parts[0].toLowerCase(Locale.ENGLISH), numeric); + final int defaultStackSize = settings.getData().getGeneral().getDefaultStacksize(); + + if (defaultStackSize > 0) + { + stack.setAmount(defaultStackSize); + } + else + { + final int oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); + if (oversizedStackSize > 0 && Permissions.OVERSIZEDSTACKS.isAuthorized(user)) + { + stack.setAmount(oversizedStackSize); + } } + return stack; } public ItemStack get(final String id, final int quantity) throws Exception @@ -92,10 +122,11 @@ public class ItemDb implements IConf, IItemDb { if (items.containsKey(itemname)) { - itemid = items.get(itemname); - if (durabilities.containsKey(itemname) && metaData == 0) + long item = items.get(itemname); + itemid = (int)(item & 0xffffffffL); + if (metaData == 0) { - metaData = durabilities.get(itemname); + metaData = (short)((item >> 32) & 0xffffL); } } else if (Material.getMaterial(itemname) != null) diff --git a/Essentials/src/com/earth2me/essentials/Jails.java b/Essentials/src/com/earth2me/essentials/Jails.java index 0aa90e08c..53bef54c4 100644 --- a/Essentials/src/com/earth2me/essentials/Jails.java +++ b/Essentials/src/com/earth2me/essentials/Jails.java @@ -1,12 +1,15 @@ package com.earth2me.essentials; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; import com.earth2me.essentials.api.IJails; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.storage.AsyncStorageObjectHolder; import java.io.File; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; +import lombok.Cleanup; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; @@ -35,7 +38,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett public Jails(final IEssentials ess) { super(ess, com.earth2me.essentials.settings.Jails.class); - reloadConfig(); + onReload(); } private void registerListeners() @@ -81,7 +84,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett { throw new Exception(_("jailNotExist")); } - Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH)); + Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH)).getBukkitLocation(); if (loc == null || loc.getWorld() == null) { throw new Exception(_("jailNotExist")); @@ -141,7 +144,15 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett Location loc = getJail(jail); user.getTeleport().now(loc, false, TeleportCause.COMMAND); } - user.setJail(jail); + user.acquireWriteLock(); + try + { + user.getData().setJail(jail); + } + finally + { + unlock(); + } } finally { @@ -157,9 +168,9 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett { if (getData().getJails() == null) { - getData().setJails(new HashMap<String, Location>()); + getData().setJails(new HashMap<String, com.earth2me.essentials.storage.Location>()); } - getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc); + getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), new com.earth2me.essentials.storage.Location(loc)); } finally { @@ -186,8 +197,10 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onBlockBreak(final BlockBreakEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (user.isJailed()) + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isJailed()) { event.setCancelled(true); } @@ -196,8 +209,10 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onBlockPlace(final BlockPlaceEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (user.isJailed()) + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isJailed()) { event.setCancelled(true); } @@ -206,8 +221,10 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onBlockDamage(final BlockDamageEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (user.isJailed()) + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isJailed()) { event.setCancelled(true); } @@ -231,11 +248,15 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett } } + private class JailPlayerListener implements Listener + { @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPlayerInteract(final PlayerInteractEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (user.isJailed()) + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isJailed()) { event.setCancelled(true); } @@ -244,15 +265,17 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerRespawn(final PlayerRespawnEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) { return; } try { - event.setRespawnLocation(getJail(user.getJail())); + event.setRespawnLocation(getJail(user.getData().getJail())); } catch (Exception ex) { @@ -270,15 +293,17 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @EventHandler(priority = EventPriority.HIGH) public void onPlayerTeleport(final PlayerTeleportEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) { return; } try { - event.setTo(getJail(user.getJail())); + event.setTo(getJail(user.getData().getJail())); } catch (Exception ex) { @@ -297,15 +322,17 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerJoin(final PlayerJoinEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) { return; } try { - sendToJail(user, user.getJail()); + sendToJail(user, user.getData().getJail()); } catch (Exception ex) { diff --git a/Essentials/src/com/earth2me/essentials/Kit.java b/Essentials/src/com/earth2me/essentials/Kit.java deleted file mode 100644 index 5edd40776..000000000 --- a/Essentials/src/com/earth2me/essentials/Kit.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import static com.earth2me.essentials.I18n.capitalCase; -import com.earth2me.essentials.commands.NoChargeException; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import java.util.*; -import java.util.logging.Level; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; - - -public class Kit -{ - //TODO: Convert this to use one of the new text classes? - public static String listKits(final IEssentials ess, final User user) throws Exception - { - try - { - final ConfigurationSection kits = ess.getSettings().getKits(); - final StringBuilder list = new StringBuilder(); - for (String kiteItem : kits.getKeys(false)) - { - if (user == null || user.isAuthorized("essentials.kit." + kiteItem.toLowerCase(Locale.ENGLISH))) - { - list.append(" ").append(capitalCase(kiteItem)); - } - } - return list.toString().trim(); - } - catch (Exception ex) - { - throw new Exception(_("kitError"), ex); - } - - } - - public static void checkTime(final User user, final String kitName, final Map<String, Object> els) throws NoChargeException - { - final double delay = els.containsKey("delay") ? ((Number)els.get("delay")).doubleValue() : 0L; - final Calendar c = new GregorianCalendar(); - c.add(Calendar.SECOND, -(int)delay); - c.add(Calendar.MILLISECOND, -(int)((delay * 1000.0) % 1000.0)); - - final long mintime = c.getTimeInMillis(); - - final Long lastTime = user.getKitTimestamp(kitName); - if (lastTime == null || lastTime < mintime) - { - final Calendar now = new GregorianCalendar(); - user.setKitTimestamp(kitName, now.getTimeInMillis()); - } - else - { - final Calendar future = new GregorianCalendar(); - future.setTimeInMillis(lastTime); - future.add(Calendar.SECOND, (int)delay); - future.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0)); - user.sendMessage(_("kitTimed", Util.formatDateDiff(future.getTimeInMillis()))); - throw new NoChargeException(); - } - } - - public static List<String> getItems(final User user, final Map<String, Object> kit) throws Exception - { - if (kit == null) - { - throw new Exception(_("kitError2")); - } - - try - { - return (List<String>)kit.get("items"); - } - catch (Exception e) - { - user.sendMessage(_("kitError2")); - throw new Exception(_("kitErrorHelp"),e); - } - } - - public static void expandItems(final IEssentials ess, final User user, final List<String> items) throws Exception - { - try - { - boolean spew = false; - for (String d : items) - { - final String[] parts = d.split(" "); - final String[] item = parts[0].split("[:+',;.]", 2); - final int id = Material.getMaterial(Integer.parseInt(item[0])).getId(); - final short data = item.length > 1 ? Short.parseShort(item[1]) : 0; - final int amount = parts.length > 1 ? Integer.parseInt(parts[1]) : 1; - - final ItemStack stack = new ItemStack(id, amount, data); - if (parts.length > 2) - { - for (int i = 2; i < parts.length; i++) - { - final String[] split = parts[i].split("[:+',;.]", 2); - if (split.length < 1) - { - continue; - } - final Enchantment enchantment = Enchantments.getByName(split[0]); - if (enchantment == null) - { - throw new Exception("Enchantment not found: " + split[0]); - } - int level; - if (split.length > 1) - { - level = Integer.parseInt(split[1]); - } - else - { - level = enchantment.getMaxLevel(); - } - try - { - stack.addEnchantment(enchantment, level); - } - catch (Exception ex) - { - throw new Exception("Enchantment " + enchantment.getName() + ": " + ex.getMessage(), ex); - } - } - } - - final Map<Integer, ItemStack> overfilled; - if (user.isAuthorized("essentials.oversizedstacks")) - { - overfilled = InventoryWorkaround.addItem(user.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack); - } - else - { - overfilled = InventoryWorkaround.addItem(user.getInventory(), true, 0, stack); - } - for (ItemStack itemStack : overfilled.values()) - { - user.getWorld().dropItemNaturally(user.getLocation(), itemStack); - spew = true; - } - } - user.updateInventory(); - if (spew) - { - user.sendMessage(_("kitInvFull")); - } - } - catch (Exception e) - { - user.updateInventory(); - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.WARNING, e.getMessage()); - } - else - { - ess.getLogger().log(Level.WARNING, e.getMessage()); - } - throw new Exception(_("kitError2"), e); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/Kits.java b/Essentials/src/com/earth2me/essentials/Kits.java new file mode 100644 index 000000000..3c3e61a5d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Kits.java @@ -0,0 +1,90 @@ +package com.earth2me.essentials; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IKits; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.settings.Kit; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; +import java.util.*; +import org.bukkit.inventory.ItemStack; + + +public class Kits extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Kits> implements IKits +{ + public Kits(final IEssentials ess) + { + super(ess, com.earth2me.essentials.settings.Kits.class); + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.getDataFolder(), "kits.yml"); + } + + @Override + public Kit getKit(String kitName) throws Exception + { + acquireReadLock(); + try + { + if (getData().getKits() == null || kitName == null + || !getData().getKits().containsKey(kitName.toLowerCase(Locale.ENGLISH))) + { + throw new Exception(_("kitError2")); + } + final Kit kit = getData().getKits().get(kitName.toLowerCase(Locale.ENGLISH)); + if (kit == null) + { + throw new Exception(_("kitError2")); + } + return kit; + } + finally + { + unlock(); + } + } + + @Override + public void sendKit(IUser user, String kitName) throws Exception + { + final Kit kit = getKit(kitName); + sendKit(user, kit); + } + + @Override + public void sendKit(IUser user, Kit kit) throws Exception + { + final List<ItemStack> itemList = kit.getItems(); + user.giveItems(itemList, true); + } + + @Override + public Collection<String> getList() throws Exception + { + acquireReadLock(); + try + { + if (getData().getKits() == null) + { + return Collections.emptyList(); + } + return new ArrayList<String>(getData().getKits().keySet()); + } + finally + { + unlock(); + } + } + + @Override + public boolean isEmpty() + { + return getData().getKits().isEmpty(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/OfflinePlayer.java b/Essentials/src/com/earth2me/essentials/OfflinePlayer.java deleted file mode 100644 index c6230f5e0..000000000 --- a/Essentials/src/com/earth2me/essentials/OfflinePlayer.java +++ /dev/null @@ -1,1054 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import java.net.InetSocketAddress; -import java.util.*; -import lombok.Delegate; -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.conversations.Conversation; -import org.bukkit.conversations.ConversationAbandonedEvent; -import org.bukkit.entity.*; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.InventoryView.Property; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.map.MapView; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionAttachment; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.Plugin; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.util.Vector; - -public class OfflinePlayer implements Player -{ - private final transient IEssentials ess; - private transient Location location = new Location(null, 0, 0, 0, 0, 0); - private transient World world; - private final transient UUID uniqueId = UUID.randomUUID(); - @Delegate(types = org.bukkit.OfflinePlayer.class) - private transient org.bukkit.OfflinePlayer base; - - public OfflinePlayer(final String name, final IEssentials ess) - { - this.ess = ess; - this.world = ess.getServer().getWorlds().get(0); - this.base = ess.getServer().getOfflinePlayer(name); - } - - @Override - public void sendMessage(final String string) - { - } - - @Override - public String getDisplayName() - { - return base.getName(); - } - - @Override - public void setDisplayName(String string) - { - } - - @Override - public void setCompassTarget(Location lctn) - { - } - - @Override - public InetSocketAddress getAddress() - { - return null; - } - - @Override - public void kickPlayer(String string) - { - } - - @Override - public PlayerInventory getInventory() - { - return null; - } - - @Override - public ItemStack getItemInHand() - { - return null; - } - - @Override - public void setItemInHand(ItemStack is) - { - } - - @Override - public int getHealth() - { - return 0; - } - - @Override - public void setHealth(int i) - { - } - - @Override - public Egg throwEgg() - { - return null; - } - - @Override - public Snowball throwSnowball() - { - return null; - } - - @Override - public Arrow shootArrow() - { - return null; - } - - @Override - public boolean isInsideVehicle() - { - return false; - } - - @Override - public boolean leaveVehicle() - { - return false; - } - - @Override - public Vehicle getVehicle() - { - return null; - } - - @Override - public Location getLocation() - { - return location; - } - - @Override - public World getWorld() - { - return world; - } - - public void setLocation(Location loc) - { - location = loc; - world = loc.getWorld(); - } - - public void teleportTo(Location lctn) - { - } - - public void teleportTo(Entity entity) - { - } - - @Override - public int getEntityId() - { - return -1; - } - - @Override - public boolean performCommand(String string) - { - return false; - } - - @Override - public int getRemainingAir() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setRemainingAir(int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public int getMaximumAir() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setMaximumAir(int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean isSneaking() - { - return false; - } - - @Override - public void setSneaking(boolean bln) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void updateInventory() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void chat(String string) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public double getEyeHeight() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public double getEyeHeight(boolean bln) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public List<Block> getLineOfSight(HashSet<Byte> hs, int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public Block getTargetBlock(HashSet<Byte> hs, int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public List<Block> getLastTwoTargetBlocks(HashSet<Byte> hs, int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public int getFireTicks() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public int getMaxFireTicks() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setFireTicks(int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public Server getServer() - { - return ess == null ? null : ess.getServer(); - } - - public Vector getMomentum() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - public void setMomentum(Vector vector) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setVelocity(Vector vector) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public Vector getVelocity() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void damage(int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void damage(int i, Entity entity) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public Location getEyeLocation() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void sendRawMessage(String string) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public Location getCompassTarget() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public int getMaximumNoDamageTicks() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setMaximumNoDamageTicks(int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public int getLastDamage() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setLastDamage(int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public int getNoDamageTicks() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setNoDamageTicks(int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean teleport(Location lctn) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean teleport(Entity entity) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public Entity getPassenger() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean setPassenger(Entity entity) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean isEmpty() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean eject() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void saveData() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void loadData() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean isSleeping() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public int getSleepTicks() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public List<Entity> getNearbyEntities(double d, double d1, double d2) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean isDead() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public float getFallDistance() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setFallDistance(float f) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setSleepingIgnored(boolean bln) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean isSleepingIgnored() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void awardAchievement(Achievement a) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic ststc) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic ststc, int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic ststc, Material mtrl) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic ststc, Material mtrl, int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void playNote(Location lctn, byte b, byte b1) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void sendBlockChange(Location lctn, Material mtrl, byte b) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void sendBlockChange(Location lctn, int i, byte b) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void setLastDamageCause(EntityDamageEvent ede) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public EntityDamageEvent getLastDamageCause() - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public void playEffect(Location lctn, Effect effect, int i) - { - throw new UnsupportedOperationException(_("notSupportedYet")); - } - - @Override - public boolean sendChunkChange(Location lctn, int i, int i1, int i2, byte[] bytes) - { - return true; - } - - @Override - public UUID getUniqueId() - { - return uniqueId; - } - - @Override - public void playNote(Location lctn, Instrument i, Note note) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setPlayerTime(long l, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getPlayerTime() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getPlayerTimeOffset() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPlayerTimeRelative() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void resetPlayerTime() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPermissionSet(String string) - { - return false; - } - - @Override - public boolean isPermissionSet(Permission prmsn) - { - return false; - } - - @Override - public boolean hasPermission(String string) - { - return false; - } - - @Override - public boolean hasPermission(Permission prmsn) - { - return false; - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String string, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String string, boolean bln, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removeAttachment(PermissionAttachment pa) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void recalculatePermissions() - { - } - - @Override - public Set<PermissionAttachmentInfo> getEffectivePermissions() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendMap(MapView mv) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public GameMode getGameMode() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setGameMode(GameMode gm) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getLevel() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setLevel(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getTotalExperience() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTotalExperience(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public float getExhaustion() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setExhaustion(float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public float getSaturation() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setSaturation(float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getFoodLevel() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setFoodLevel(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isSprinting() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setSprinting(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setPlayerListName(String name) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getPlayerListName() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getTicksLived() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTicksLived(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getMaxHealth() - { - 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."); - } - - @Override - public Player getKiller() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - void setName(final String name) - { - if (!this.base.getName().equalsIgnoreCase(name)) - { - this.base = ess.getServer().getOfflinePlayer(name); - } - } - - @Override - public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set<String> getListeningPluginChannels() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setAllowFlight(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getAllowFlight() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setBedSpawnLocation(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playEffect(EntityEffect ee) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void hidePlayer(Player player) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void showPlayer(Player player) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean canSee(Player player) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean addPotionEffect(PotionEffect pe) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean addPotionEffect(PotionEffect pe, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean addPotionEffects(Collection<PotionEffect> clctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasPotionEffect(PotionEffectType pet) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removePotionEffect(PotionEffectType pet) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Collection<PotionEffect> getActivePotionEffects() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public <T extends Projectile> T launchProjectile(Class<? extends T> arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public EntityType getType() - { - return EntityType.PLAYER; - } - - @Override - public <T> void playEffect(Location lctn, Effect effect, T t) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean setWindowProperty(Property prprt, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryView getOpenInventory() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryView openInventory(Inventory invntr) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryView openWorkbench(Location lctn, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryView openEnchanting(Location lctn, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void openInventory(InventoryView iv) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void closeInventory() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ItemStack getItemOnCursor() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setItemOnCursor(ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setMetadata(String string, MetadataValue mv) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List<MetadataValue> getMetadata(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasMetadata(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removeMetadata(String string, Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - - @Override - public boolean isConversing() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void acceptConversationInput(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean beginConversation(Conversation c) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void abandonConversation(Conversation c) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendMessage(String[] strings) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isBlocking() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void abandonConversation(Conversation arg0, ConversationAbandonedEvent arg1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isFlying() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setFlying(boolean arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } -} diff --git a/Essentials/src/com/earth2me/essentials/PlayerExtension.java b/Essentials/src/com/earth2me/essentials/PlayerExtension.java deleted file mode 100644 index 7c52e40d1..000000000 --- a/Essentials/src/com/earth2me/essentials/PlayerExtension.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.earth2me.essentials; - -import lombok.Delegate; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.entity.Entity; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.permissions.Permissible; -import org.bukkit.permissions.ServerOperator; - - -public class PlayerExtension implements Player -{ - @Delegate(types = - { - Player.class, Entity.class, CommandSender.class, ServerOperator.class, - HumanEntity.class, ConfigurationSerializable.class, LivingEntity.class, - Permissible.class - }) - protected Player base; - - public PlayerExtension(final Player base) - { - this.base = base; - } - - public final Player getBase() - { - return base; - } - - public final Player setBase(final Player base) - { - return this.base = base; - } -} diff --git a/Essentials/src/com/earth2me/essentials/Settings.java b/Essentials/src/com/earth2me/essentials/Settings.java deleted file mode 100644 index b1352b6c3..000000000 --- a/Essentials/src/com/earth2me/essentials/Settings.java +++ /dev/null @@ -1,822 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.commands.IEssentialsCommand; -import com.earth2me.essentials.signs.EssentialsSign; -import com.earth2me.essentials.signs.Signs; -import com.earth2me.essentials.textreader.IText; -import com.earth2me.essentials.textreader.SimpleTextInput; -import java.io.File; -import java.text.MessageFormat; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.ChatColor; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.MemoryConfiguration; -import org.bukkit.event.EventPriority; -import org.bukkit.inventory.ItemStack; - - -public class Settings implements ISettings -{ - private final transient EssentialsConf config; - private final static Logger logger = Logger.getLogger("Minecraft"); - private final transient IEssentials ess; - private boolean metricsEnabled = true; - - public Settings(IEssentials ess) - { - this.ess = ess; - config = new EssentialsConf(new File(ess.getDataFolder(), "config.yml")); - config.setTemplateName("/config.yml"); - reloadConfig(); - } - - @Override - public boolean getRespawnAtHome() - { - return config.getBoolean("respawn-at-home", false); - } - - @Override - public boolean getUpdateBedAtDaytime() - { - return config.getBoolean("update-bed-at-daytime", true); - } - - @Override - public Set<String> getMultipleHomes() - { - return config.getConfigurationSection("sethome-multiple").getKeys(false); - } - - @Override - public int getHomeLimit(final User user) - { - final Set<String> homeList = getMultipleHomes(); - if (homeList == null) - { - //TODO: Replace this code to remove backwards compat, after settings are automatically updated - // return getHomeLimit("default"); - return config.getInt("multiple-homes", 5); - } - int limit = getHomeLimit("default"); - for (String set : homeList) - { - if (user.isAuthorized("essentials.sethome.multiple." + set) && (limit < getHomeLimit(set))) - { - limit = getHomeLimit(set); - } - } - return limit; - } - - @Override - public int getHomeLimit(final String set) - { - return config.getInt("sethome-multiple." + set, config.getInt("sethome-multiple.default", 3)); - } - - @Override - public int getChatRadius() - { - return config.getInt("chat.radius", config.getInt("chat-radius", 0)); - } - - @Override - public double getTeleportDelay() - { - return config.getDouble("teleport-delay", 0); - } - - @Override - public int getOversizedStackSize() - { - return config.getInt("oversized-stacksize", 64); - } - - @Override - public int getDefaultStackSize() - { - return config.getInt("default-stack-size", -1); - } - - @Override - public int getStartingBalance() - { - return config.getInt("starting-balance", 0); - } - - @Override - public boolean isCommandDisabled(final IEssentialsCommand cmd) - { - return isCommandDisabled(cmd.getName()); - } - - @Override - public boolean isCommandDisabled(String label) - { - for (String c : config.getStringList("disabled-commands")) - { - if (!c.equalsIgnoreCase(label)) - { - continue; - } - return true; - } - return config.getBoolean("disable-" + label.toLowerCase(Locale.ENGLISH), false); - } - - @Override - public boolean isCommandRestricted(IEssentialsCommand cmd) - { - return isCommandRestricted(cmd.getName()); - } - - @Override - public boolean isCommandRestricted(String label) - { - for (String c : config.getStringList("restricted-commands")) - { - if (!c.equalsIgnoreCase(label)) - { - continue; - } - return true; - } - return config.getBoolean("restrict-" + label.toLowerCase(Locale.ENGLISH), false); - } - - @Override - public boolean isPlayerCommand(String label) - { - for (String c : config.getStringList("player-commands")) - { - if (!c.equalsIgnoreCase(label)) - { - continue; - } - return true; - } - return false; - } - - @Override - public boolean isCommandOverridden(String name) - { - for (String c : config.getStringList("overridden-commands")) - { - if (!c.equalsIgnoreCase(name)) - { - continue; - } - return true; - } - return config.getBoolean("override-" + name.toLowerCase(Locale.ENGLISH), false); - } - - @Override - public double getCommandCost(IEssentialsCommand cmd) - { - return getCommandCost(cmd.getName()); - } - - @Override - public double getCommandCost(String label) - { - double cost = config.getDouble("command-costs." + label, 0.0); - if (cost == 0.0) - { - cost = config.getDouble("cost-" + label, 0.0); - } - return cost; - } - - @Override - public String getNicknamePrefix() - { - return config.getString("nickname-prefix", "~"); - } - - @Override - public double getTeleportCooldown() - { - return config.getDouble("teleport-cooldown", 0); - } - - @Override - public double getHealCooldown() - { - return config.getDouble("heal-cooldown", 0); - } - private ConfigurationSection kits; - - public ConfigurationSection _getKits() - { - if (config.isConfigurationSection("kits")) - { - final ConfigurationSection section = config.getConfigurationSection("kits"); - final ConfigurationSection newSection = new MemoryConfiguration(); - for (String kitItem : section.getKeys(false)) - { - if (section.isConfigurationSection(kitItem)) - { - newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem)); - } - } - return newSection; - } - return null; - } - - @Override - public ConfigurationSection getKits() - { - return kits; - } - - @Override - public Map<String, Object> getKit(String name) - { - name = name.replace('.', '_').replace('/', '_'); - if (config.isConfigurationSection("kits")) - { - final ConfigurationSection kits = getKits(); - if (kits.isConfigurationSection(name)) - { - return kits.getConfigurationSection(name).getValues(true); - } - } - return null; - } - - @Override - public ChatColor getOperatorColor() throws Exception - { - String colorName = config.getString("ops-name-color", null); - - if (colorName == null) - { - return ChatColor.RED; - } - if ("none".equalsIgnoreCase(colorName) || colorName.isEmpty()) - { - throw new Exception(); - } - - try - { - return ChatColor.valueOf(colorName.toUpperCase(Locale.ENGLISH)); - } - catch (IllegalArgumentException ex) - { - } - - return ChatColor.getByChar(colorName); - } - - @Override - public int getSpawnMobLimit() - { - return config.getInt("spawnmob-limit", 10); - } - - @Override - public boolean showNonEssCommandsInHelp() - { - return config.getBoolean("non-ess-in-help", true); - } - - @Override - public boolean hidePermissionlessHelp() - { - return config.getBoolean("hide-permissionless-help", true); - } - - @Override - public int getProtectCreeperMaxHeight() - { - return config.getInt("protect.creeper.max-height", -1); - } - - @Override - public boolean areSignsDisabled() - { - return !signsEnabled; - } - - @Override - public long getBackupInterval() - { - return config.getInt("backup.interval", 1440); // 1440 = 24 * 60 - } - - @Override - public String getBackupCommand() - { - return config.getString("backup.command", null); - } - private Map<String, MessageFormat> chatFormats = new HashMap<String, MessageFormat>(); - - @Override - public MessageFormat getChatFormat(String group) - { - MessageFormat mFormat = chatFormats.get(group); - if (mFormat == null) - { - String format = config.getString("chat.group-formats." + (group == null ? "Default" : group), - config.getString("chat.format", "&7[{GROUP}]&f {DISPLAYNAME}&7:&f {MESSAGE}")); - format = Util.replaceFormat(format); - format = format.replace("{DISPLAYNAME}", "%1$s"); - format = format.replace("{GROUP}", "{0}"); - format = format.replace("{MESSAGE}", "%2$s"); - format = format.replace("{WORLDNAME}", "{1}"); - format = format.replace("{SHORTWORLDNAME}", "{2}"); - format = format.replaceAll("\\{(\\D*?)\\}", "\\[$1\\]"); - mFormat = new MessageFormat(format); - chatFormats.put(group, mFormat); - } - return mFormat; - } - - @Override - public boolean getAnnounceNewPlayers() - { - return !config.getString("newbies.announce-format", "-").isEmpty(); - } - - @Override - public IText getAnnounceNewPlayerFormat() - { - return new SimpleTextInput(Util.replaceFormat(config.getString("newbies.announce-format", "&dWelcome {DISPLAYNAME} to the server!"))); - } - - @Override - public String getNewPlayerKit() - { - return config.getString("newbies.kit", ""); - } - - @Override - public String getNewbieSpawn() - { - return config.getString("newbies.spawnpoint", "default"); - } - - @Override - public boolean getPerWarpPermission() - { - return config.getBoolean("per-warp-permission", false); - } - - @Override - public boolean getSortListByGroups() - { - return config.getBoolean("sort-list-by-groups", true); - } - - @Override - public void reloadConfig() - { - config.load(); - noGodWorlds = new HashSet<String>(config.getStringList("no-god-in-worlds")); - enabledSigns = _getEnabledSigns(); - teleportInvulnerability = _isTeleportInvulnerability(); - disableItemPickupWhileAfk = _getDisableItemPickupWhileAfk(); - registerBackInListener = _registerBackInListener(); - cancelAfkOnMove = _cancelAfkOnMove(); - getFreezeAfkPlayers = _getFreezeAfkPlayers(); - itemSpawnBl = _getItemSpawnBlacklist(); - loginAttackDelay = _loginAttackDelay(); - kits = _getKits(); - chatFormats.clear(); - } - private List<Integer> itemSpawnBl = new ArrayList<Integer>(); - - @Override - public List<Integer> itemSpawnBlacklist() - { - return itemSpawnBl; - } - - private List<Integer> _getItemSpawnBlacklist() - { - final List<Integer> epItemSpwn = new ArrayList<Integer>(); - if (ess.getItemDb() == null) - { - logger.log(Level.FINE, "Aborting ItemSpawnBL read, itemDB not yet loaded."); - return epItemSpwn; - } - for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) - { - itemName = itemName.trim(); - if (itemName.isEmpty()) - { - continue; - } - try - { - final ItemStack iStack = ess.getItemDb().get(itemName); - epItemSpwn.add(iStack.getTypeId()); - } - catch (Exception ex) - { - logger.log(Level.SEVERE, _("unknownItemInList", itemName, "item-spawn-blacklist")); - } - } - return epItemSpwn; - } - private List<EssentialsSign> enabledSigns = new ArrayList<EssentialsSign>(); - private boolean signsEnabled = false; - - @Override - public List<EssentialsSign> enabledSigns() - { - return enabledSigns; - } - - private List<EssentialsSign> _getEnabledSigns() - { - List<EssentialsSign> newSigns = new ArrayList<EssentialsSign>(); - - for (String signName : config.getStringList("enabledSigns")) - { - signName = signName.trim().toUpperCase(Locale.ENGLISH); - if (signName.isEmpty()) - { - continue; - } - if (signName.equals("COLOR") || signName.equals("COLOUR")) - { - signsEnabled = true; - continue; - } - try - { - newSigns.add(Signs.valueOf(signName).getSign()); - } - catch (Exception ex) - { - logger.log(Level.SEVERE, _("unknownItemInList", signName, "enabledSigns")); - continue; - } - signsEnabled = true; - } - return newSigns; - } - - @Override - public boolean spawnIfNoHome() - { - return config.getBoolean("spawn-if-no-home", false); - } - - @Override - public boolean warnOnBuildDisallow() - { - return config.getBoolean("protect.disable.warn-on-build-disallow", false); - } - private boolean debug = false; - - @Override - public boolean isDebug() - { - return debug || config.getBoolean("debug", false); - } - - @Override - public boolean warnOnSmite() - { - return config.getBoolean("warn-on-smite", true); - } - - @Override - public boolean permissionBasedItemSpawn() - { - return config.getBoolean("permission-based-item-spawn", false); - } - - @Override - public String getLocale() - { - return config.getString("locale", ""); - } - - @Override - public String getCurrencySymbol() - { - return config.getString("currency-symbol", "$").substring(0, 1).replaceAll("[0-9]", "$"); - } - - @Override - public boolean isTradeInStacks(int id) - { - return config.getBoolean("trade-in-stacks-" + id, false); - } - - @Override - public boolean isEcoDisabled() - { - return config.getBoolean("disable-eco", false); - } - - @Override - public boolean getProtectPreventSpawn(final String creatureName) - { - return config.getBoolean("protect.prevent.spawn." + creatureName, false); - } - - @Override - public List<Integer> getProtectList(final String configName) - { - final List<Integer> list = new ArrayList<Integer>(); - for (String itemName : config.getString(configName, "").split(",")) - { - itemName = itemName.trim(); - if (itemName.isEmpty()) - { - continue; - } - ItemStack itemStack; - try - { - itemStack = ess.getItemDb().get(itemName); - list.add(itemStack.getTypeId()); - } - catch (Exception ex) - { - logger.log(Level.SEVERE, _("unknownItemInList", itemName, configName)); - } - } - return list; - } - - @Override - public String getProtectString(final String configName) - { - return config.getString(configName, null); - } - - @Override - public boolean getProtectBoolean(final String configName, boolean def) - { - return config.getBoolean(configName, def); - } - private final static double MAXMONEY = 10000000000000.0; - - @Override - public double getMaxMoney() - { - double max = config.getDouble("max-money", MAXMONEY); - if (Math.abs(max) > MAXMONEY) - { - max = max < 0 ? -MAXMONEY : MAXMONEY; - } - return max; - } - private final static double MINMONEY = -10000000000000.0; - - @Override - public double getMinMoney() - { - double min = config.getDouble("min-money", MINMONEY); - if (min > 0) - { - min = -min; - } - if (min < MINMONEY) - { - min = MINMONEY; - } - return min; - } - - @Override - public boolean isEcoLogEnabled() - { - return config.getBoolean("economy-log-enabled", false); - } - - @Override - public boolean isEcoLogUpdateEnabled() - { - return config.getBoolean("economy-log-update-enabled", false); - } - - @Override - public boolean removeGodOnDisconnect() - { - return config.getBoolean("remove-god-on-disconnect", false); - } - - @Override - public boolean changeDisplayName() - { - return config.getBoolean("change-displayname", true); - } - - @Override - public boolean changePlayerListName() - { - return config.getBoolean("change-playerlist", false); - } - - @Override - public boolean useBukkitPermissions() - { - return config.getBoolean("use-bukkit-permissions", false); - } - - @Override - public boolean addPrefixSuffix() - { - return config.getBoolean("add-prefix-suffix", ess.getServer().getPluginManager().isPluginEnabled("EssentialsChat")); - } - - @Override - public boolean disablePrefix() - { - return config.getBoolean("disablePrefix", false); - } - - @Override - public boolean disableSuffix() - { - return config.getBoolean("disableSuffix", false); - } - - @Override - public long getAutoAfk() - { - return config.getLong("auto-afk", 300); - } - - @Override - public long getAutoAfkKick() - { - return config.getLong("auto-afk-kick", -1); - } - private boolean getFreezeAfkPlayers; - - @Override - public boolean getFreezeAfkPlayers() - { - return getFreezeAfkPlayers; - } - - private boolean _getFreezeAfkPlayers() - { - return config.getBoolean("freeze-afk-players", false); - } - private boolean cancelAfkOnMove; - - @Override - public boolean cancelAfkOnMove() - { - return cancelAfkOnMove; - } - - private boolean _cancelAfkOnMove() - { - return config.getBoolean("cancel-afk-on-move", true); - } - - @Override - public boolean areDeathMessagesEnabled() - { - return config.getBoolean("death-messages", true); - } - private Set<String> noGodWorlds = new HashSet<String>(); - - @Override - public Set<String> getNoGodWorlds() - { - return noGodWorlds; - } - - @Override - public void setDebug(final boolean debug) - { - this.debug = debug; - } - - @Override - public boolean getRepairEnchanted() - { - return config.getBoolean("repair-enchanted", true); - } - - @Override - public boolean isWorldTeleportPermissions() - { - return config.getBoolean("world-teleport-permissions", false); - } - - @Override - public boolean isWorldHomePermissions() - { - return config.getBoolean("world-home-permissions", false); - } - private boolean registerBackInListener; - - @Override - public boolean registerBackInListener() - { - return registerBackInListener; - } - - private boolean _registerBackInListener() - { - return config.getBoolean("register-back-in-listener", false); - } - private boolean disableItemPickupWhileAfk; - - @Override - public boolean getDisableItemPickupWhileAfk() - { - return disableItemPickupWhileAfk; - } - - private boolean _getDisableItemPickupWhileAfk() - { - return config.getBoolean("disable-item-pickup-while-afk", false); - } - - @Override - public EventPriority getRespawnPriority() - { - String priority = config.getString("respawn-listener-priority", "normal").toLowerCase(Locale.ENGLISH); - if ("lowest".equals(priority)) - { - return EventPriority.LOWEST; - } - if ("low".equals(priority)) - { - return EventPriority.LOW; - } - if ("normal".equals(priority)) - { - return EventPriority.NORMAL; - } - if ("high".equals(priority)) - { - return EventPriority.HIGH; - } - if ("highest".equals(priority)) - { - return EventPriority.HIGHEST; - } - return EventPriority.NORMAL; - } - - @Override - public long getTpaAcceptCancellation() - { - return config.getLong("tpa-accept-cancellation", 0); - } - - @Override - public boolean isMetricsEnabled() - { - return metricsEnabled; - } - - @Override - public void setMetricsEnabled(boolean metricsEnabled) - { - this.metricsEnabled = metricsEnabled; - } - private boolean teleportInvulnerability; - - @Override - public long getTeleportInvulnerability() - { - return config.getLong("teleport-invulnerability", 0) * 1000; - } - - private boolean _isTeleportInvulnerability() - { - return (config.getLong("teleport-invulnerability", 0) > 0); - } - - @Override - public boolean isTeleportInvulnerability() - { - return teleportInvulnerability; - } - - private long loginAttackDelay; - - private long _loginAttackDelay() - { - return config.getLong("login-attack-delay", 0) * 1000; - } - - @Override - public long getLoginAttackDelay() - { - return loginAttackDelay; - } - -} diff --git a/Essentials/src/com/earth2me/essentials/Teleport.java b/Essentials/src/com/earth2me/essentials/Teleport.java index 6569a1689..7118ed1bb 100644 --- a/Essentials/src/com/earth2me/essentials/Teleport.java +++ b/Essentials/src/com/earth2me/essentials/Teleport.java @@ -1,7 +1,16 @@ package com.earth2me.essentials; -import com.earth2me.essentials.api.ITeleport; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.utils.Util; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ITeleport; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.CooldownException; +import com.earth2me.essentials.user.UserData.TimestampType; +import com.earth2me.essentials.utils.DateUtil; +import com.earth2me.essentials.utils.LocationUtil; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Logger; @@ -111,7 +120,7 @@ public class Teleport implements Runnable, ITeleport } catch (Throwable ex) { - ess.showError(user.getBase(), ex, "teleport"); + ess.getCommandHandler().showCommandError(user.getBase(), "teleport", ex); } } catch (Exception ex) @@ -138,30 +147,21 @@ public class Teleport implements Runnable, ITeleport public void warp(String warp, Trade chargeFor, TeleportCause cause) throws Exception { - Location loc = ess.getWarps().getWarp(warp); + final Location loc = ess.getWarps().getWarp(warp); teleport(new Target(loc), chargeFor, cause); user.sendMessage(_("warpingTo", warp)); } public void cooldown(boolean check) throws Exception { - Calendar now = new GregorianCalendar(); - if (user.getLastTeleportTimestamp() > 0) + try { - double cooldown = ess.getSettings().getTeleportCooldown(); - Calendar cooldownTime = new GregorianCalendar(); - cooldownTime.setTimeInMillis(user.getLastTeleportTimestamp()); - cooldownTime.add(Calendar.SECOND, (int)cooldown); - cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); - if (cooldownTime.after(now) && !user.isAuthorized("essentials.teleport.cooldown.bypass")) - { - throw new Exception(_("timeBeforeTeleport", Util.formatDateDiff(cooldownTime.getTimeInMillis()))); - } + user.checkCooldown(TimestampType.LASTTELEPORT, ess.getRanks().getTeleportCooldown(user), !check, Permissions.TELEPORT_COOLDOWN_BYPASS); } - // if justCheck is set, don't update lastTeleport; we're just checking - if (!check) + catch (CooldownException ex) { - user.setLastTeleportTimestamp(now.getTimeInMillis()); + throw new Exception(_("timeBeforeTeleport", ex.getMessage())); + } } @@ -207,14 +207,14 @@ public class Teleport implements Runnable, ITeleport private void teleport(Target target, Trade chargeFor, TeleportCause cause) throws Exception { - double delay = ess.getSettings().getTeleportDelay(); + double delay = ess.getRanks().getTeleportDelay(user); if (chargeFor != null) { chargeFor.isAffordableFor(user); } cooldown(true); - if (delay <= 0 || user.isAuthorized("essentials.teleport.timer.bypass")) + if (delay <= 0 || Permissions.TELEPORT_TIMER_BYPASS.isAuthorized(user)) { cooldown(false); now(target, cause); @@ -229,7 +229,7 @@ public class Teleport implements Runnable, ITeleport Calendar c = new GregorianCalendar(); c.add(Calendar.SECOND, (int)delay); c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0)); - user.sendMessage(_("dontMoveMessage", Util.formatDateDiff(c.getTimeInMillis()))); + user.sendMessage(_("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); initTimer((long)(delay * 1000.0), target, chargeFor, cause); teleTimer = ess.scheduleSyncRepeatingTask(this, 10, 10); @@ -239,7 +239,7 @@ public class Teleport implements Runnable, ITeleport { cancel(); user.setLastLocation(); - user.getBase().teleport(Util.getSafeDestination(target.getLocation()), cause); + user.getBase().teleport(LocationUtil.getSafeDestination(target.getLocation()), cause); } public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception @@ -269,12 +269,28 @@ public class Teleport implements Runnable, ITeleport public void back(Trade chargeFor) throws Exception { - teleport(new Target(user.getLastLocation()), chargeFor, TeleportCause.COMMAND); + user.acquireReadLock(); + try + { + teleport(new Target(user.getData().getLastLocation().getBukkitLocation()), chargeFor, TeleportCause.COMMAND); + } + finally + { + user.unlock(); + } } public void back() throws Exception { - now(new Target(user.getLastLocation()), TeleportCause.COMMAND); + user.acquireReadLock(); + try + { + now(new Target(user.getData().getLastLocation().getBukkitLocation()), TeleportCause.COMMAND); + } + finally + { + user.unlock(); + } } public void home(Location loc, Trade chargeFor) throws Exception diff --git a/Essentials/src/com/earth2me/essentials/User.java b/Essentials/src/com/earth2me/essentials/User.java deleted file mode 100644 index f9206206a..000000000 --- a/Essentials/src/com/earth2me/essentials/User.java +++ /dev/null @@ -1,662 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.commands.IEssentialsCommand; -import com.earth2me.essentials.register.payment.Method; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Location; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class User extends UserData implements Comparable<User>, IReplyTo, IUser -{ - private CommandSender replyTo = null; - private transient User teleportRequester; - private transient boolean teleportRequestHere; - private transient boolean vanished; - private transient final Teleport teleport; - private transient long teleportRequestTime; - private transient long lastOnlineActivity; - private transient long lastActivity = System.currentTimeMillis(); - private boolean hidden = false; - private transient Location afkPosition = null; - private boolean invSee = false; - private static final Logger logger = Logger.getLogger("Minecraft"); - - User(final Player base, final IEssentials ess) - { - super(base, ess); - teleport = new Teleport(this, ess); - if (isAfk()) - { - afkPosition = getLocation(); - } - } - - User update(final Player base) - { - setBase(base); - return this; - } - - @Override - public boolean isAuthorized(final IEssentialsCommand cmd) - { - return isAuthorized(cmd, "essentials."); - } - - @Override - public boolean isAuthorized(final IEssentialsCommand cmd, final String permissionPrefix) - { - return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName())); - } - - @Override - public boolean isAuthorized(final String node) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node); - } - if (base instanceof OfflinePlayer) - { - return false; - } - - if (isOp()) - { - return true; - } - - if (isJailed()) - { - return false; - } - - try - { - return ess.getPermissionsHandler().hasPermission(base, node); - } - catch (Exception ex) - { - ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage()); - return false; - } - } - - public void healCooldown() throws Exception - { - final Calendar now = new GregorianCalendar(); - if (getLastHealTimestamp() > 0) - { - final double cooldown = ess.getSettings().getHealCooldown(); - final Calendar cooldownTime = new GregorianCalendar(); - cooldownTime.setTimeInMillis(getLastHealTimestamp()); - cooldownTime.add(Calendar.SECOND, (int)cooldown); - cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); - if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) - { - throw new Exception(_("timeBeforeHeal", Util.formatDateDiff(cooldownTime.getTimeInMillis()))); - } - } - setLastHealTimestamp(now.getTimeInMillis()); - } - - @Override - public void giveMoney(final double value) - { - giveMoney(value, null); - } - - public void giveMoney(final double value, final CommandSender initiator) - { - if (value == 0) - { - return; - } - setMoney(getMoney() + value); - sendMessage(_("addedToAccount", Util.displayCurrency(value, ess))); - if (initiator != null) - { - initiator.sendMessage(_("addedToOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName(), Util.displayCurrency(getMoney(), ess))); - } - } - - public void payUser(final User reciever, final double value) throws Exception - { - if (value == 0) - { - return; - } - if (canAfford(value)) - { - setMoney(getMoney() - value); - reciever.setMoney(reciever.getMoney() + value); - sendMessage(_("moneySentTo", Util.displayCurrency(value, ess), reciever.getDisplayName())); - reciever.sendMessage(_("moneyRecievedFrom", Util.displayCurrency(value, ess), getDisplayName())); - } - else - { - throw new Exception(_("notEnoughMoney")); - } - } - - @Override - public void takeMoney(final double value) - { - takeMoney(value, null); - } - - public void takeMoney(final double value, final CommandSender initiator) - { - if (value == 0) - { - return; - } - setMoney(getMoney() - value); - sendMessage(_("takenFromAccount", Util.displayCurrency(value, ess))); - if (initiator != null) - { - initiator.sendMessage(_("takenFromOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName(), Util.displayCurrency(getMoney(), ess))); - } - } - - @Override - public boolean canAfford(final double cost) - { - return canAfford(cost, true); - } - - public boolean canAfford(final double cost, final boolean permcheck) - { - final double mon = getMoney(); - if (!permcheck || isAuthorized("essentials.eco.loan")) - { - return (mon - cost) >= ess.getSettings().getMinMoney(); - } - return cost <= mon; - } - - public void dispose() - { - this.base = new OfflinePlayer(getName(), ess); - } - - @Override - public void setReplyTo(final CommandSender user) - { - replyTo = user; - } - - @Override - public CommandSender getReplyTo() - { - return replyTo; - } - - @Override - public int compareTo(final User other) - { - return Util.stripFormat(this.getDisplayName()).compareToIgnoreCase(Util.stripFormat(other.getDisplayName())); - } - - @Override - public boolean equals(final Object object) - { - if (!(object instanceof User)) - { - return false; - } - return this.getName().equalsIgnoreCase(((User)object).getName()); - - } - - @Override - public int hashCode() - { - return this.getName().hashCode(); - } - - public Boolean canSpawnItem(final int itemId) - { - return !ess.getSettings().itemSpawnBlacklist().contains(itemId); - } - - public Location getHome() throws Exception - { - return getHome(getHomes().get(0)); - } - - public void setHome() - { - setHome("home", getLocation()); - } - - public void setHome(final String name) - { - setHome(name, getLocation()); - } - - @Override - public void setLastLocation() - { - setLastLocation(getLocation()); - } - - public void requestTeleport(final User player, final boolean here) - { - teleportRequestTime = System.currentTimeMillis(); - teleportRequester = player; - teleportRequestHere = here; - } - - public User getTeleportRequest() - { - return teleportRequester; - } - - public boolean isTpRequestHere() - { - return teleportRequestHere; - } - - public String getNick(final boolean longnick) - { - final StringBuilder prefix = new StringBuilder(); - String nickname; - String suffix = "§f"; - final String nick = getNickname(); - if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) - { - nickname = getName(); - } - else - { - nickname = ess.getSettings().getNicknamePrefix() + nick; - } - - if (isOp()) - { - try - { - final String opPrefix = ess.getSettings().getOperatorColor().toString(); - if (opPrefix.length() > 0) - { - prefix.insert(0, opPrefix); - } - } - catch (Exception e) - { - } - } - - if (ess.getSettings().addPrefixSuffix()) - { - if (!ess.getSettings().disablePrefix()) - { - final String ptext = ess.getPermissionsHandler().getPrefix(base).replace('&', '§'); - prefix.insert(0, ptext); - } - if (!ess.getSettings().disableSuffix()) - { - final String stext = ess.getPermissionsHandler().getSuffix(base).replace('&', '§'); - suffix = stext + "§f"; - suffix = suffix.replace("§f§f", "§f"); - } - } - final String strPrefix = prefix.toString(); - String output = strPrefix + nickname + suffix; - if (!longnick && output.length() > 16) - { - output = strPrefix + nickname; - } - if (!longnick && output.length() > 16) - { - output = Util.lastCode(strPrefix) + nickname; - } - if (!longnick && output.length() > 16) - { - output = Util.lastCode(strPrefix) + nickname.substring(0, 14); - } - if (output.charAt(output.length() - 1) == '§') { - output = output.substring(0, output.length() - 1); - } - return output; - } - - public void setDisplayNick() - { - if (base.isOnline() && ess.getSettings().changeDisplayName()) - { - setDisplayName(getNick(true)); - if (ess.getSettings().changePlayerListName()) - { - String name = getNick(false); - try - { - setPlayerListName(name); - } - catch (IllegalArgumentException e) - { - if (ess.getSettings().isDebug()) - { - logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player."); - } - } - } - } - } - - @Override - public String getDisplayName() - { - return super.getDisplayName() == null ? super.getName() : super.getDisplayName(); - } - - @Override - public Teleport getTeleport() - { - return teleport; - } - - public long getLastOnlineActivity() - { - return lastOnlineActivity; - } - - public void setLastOnlineActivity(final long timestamp) - { - lastOnlineActivity = timestamp; - } - - @Override - public double getMoney() - { - if (ess.getPaymentMethod().hasMethod()) - { - try - { - final Method method = ess.getPaymentMethod().getMethod(); - if (!method.hasAccount(this.getName())) - { - throw new Exception(); - } - final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); - return account.balance(); - } - catch (Throwable ex) - { - } - } - return super.getMoney(); - } - - @Override - public void setMoney(final double value) - { - if (ess.getPaymentMethod().hasMethod()) - { - try - { - final Method method = ess.getPaymentMethod().getMethod(); - if (!method.hasAccount(this.getName())) - { - throw new Exception(); - } - final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); - account.set(value); - } - catch (Throwable ex) - { - } - } - super.setMoney(value); - Trade.log("Update", "Set", "API", getName(), new Trade(value, ess), null, null, null, ess); - } - - public void updateMoneyCache(final double value) - { - if (ess.getPaymentMethod().hasMethod() && super.getMoney() != value) - { - super.setMoney(value); - } - } - - @Override - public void setAfk(final boolean set) - { - this.setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : set); - if (set && !isAfk()) - { - afkPosition = getLocation(); - } - else if (!set && isAfk()) - { - afkPosition = null; - } - super.setAfk(set); - } - - @Override - public boolean toggleAfk() - { - final boolean now = super.toggleAfk(); - this.setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : now); - return now; - } - - @Override - public boolean isHidden() - { - return hidden; - } - - public void setHidden(final boolean hidden) - { - this.hidden = hidden; - if (hidden == true) - { - setLastLogout(getLastOnlineActivity()); - } - } - - //Returns true if status expired during this check - public boolean checkJailTimeout(final long currentTime) - { - if (getJailTimeout() > 0 && getJailTimeout() < currentTime && isJailed()) - { - setJailTimeout(0); - setJailed(false); - sendMessage(_("haveBeenReleased")); - setJail(null); - try - { - getTeleport().back(); - } - catch (Exception ex) - { - } - return true; - } - return false; - } - - //Returns true if status expired during this check - public boolean checkMuteTimeout(final long currentTime) - { - if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) - { - setMuteTimeout(0); - sendMessage(_("canTalkAgain")); - setMuted(false); - return true; - } - return false; - } - - //Returns true if status expired during this check - public boolean checkBanTimeout(final long currentTime) - { - if (getBanTimeout() > 0 && getBanTimeout() < currentTime && isBanned()) - { - setBanTimeout(0); - setBanned(false); - return true; - } - return false; - } - - public void updateActivity(final boolean broadcast) - { - if (isAfk()) - { - setAfk(false); - if (broadcast && !isHidden()) - { - setDisplayNick(); - ess.broadcastMessage(this, _("userIsNotAway", getDisplayName())); - } - } - lastActivity = System.currentTimeMillis(); - } - - public void checkActivity() - { - final long autoafkkick = ess.getSettings().getAutoAfkKick(); - 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); - - - for (Player player : ess.getServer().getOnlinePlayers()) - { - final User user = ess.getUser(player); - if (user.isAuthorized("essentials.kick.notify")) - { - player.sendMessage(_("playerKicked", Console.NAME, getName(), kickReason)); - } - } - } - final long autoafk = ess.getSettings().getAutoAfk(); - if (!isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorized("essentials.afk")) - { - setAfk(true); - if (!isHidden()) - { - setDisplayNick(); - ess.broadcastMessage(this, _("userIsAway", getDisplayName())); - } - } - } - - public Location getAfkPosition() - { - return afkPosition; - } - - @Override - public boolean toggleGodModeEnabled() - { - if (!isGodModeEnabled()) - { - setFoodLevel(20); - } - return super.toggleGodModeEnabled(); - } - - @Override - public boolean isGodModeEnabled() - { - return (super.isGodModeEnabled() && !ess.getSettings().getNoGodWorlds().contains(getLocation().getWorld().getName())) - || (isAfk() && ess.getSettings().getFreezeAfkPlayers()); - } - - public boolean isGodModeEnabledRaw() - { - return super.isGodModeEnabled(); - } - - @Override - public String getGroup() - { - return ess.getPermissionsHandler().getGroup(base); - } - - public boolean inGroup(final String group) - { - return ess.getPermissionsHandler().inGroup(base, group); - } - - public boolean canBuild() - { - if (isOp()) - { - return true; - } - return ess.getPermissionsHandler().canBuild(base, getGroup()); - } - - public long getTeleportRequestTime() - { - return teleportRequestTime; - } - - public boolean isInvSee() - { - return invSee; - } - - public void setInvSee(final boolean set) - { - invSee = set; - } - private transient long teleportInvulnerabilityTimestamp = 0; - - public void enableInvulnerabilityAfterTeleport() - { - final long time = ess.getSettings().getTeleportInvulnerability(); - if (time > 0) - { - teleportInvulnerabilityTimestamp = System.currentTimeMillis() + time; - } - } - - public void resetInvulnerabilityAfterTeleport() - { - if (teleportInvulnerabilityTimestamp != 0 - && teleportInvulnerabilityTimestamp < System.currentTimeMillis()) - { - teleportInvulnerabilityTimestamp = 0; - } - } - - public boolean hasInvulnerabilityAfterTeleport() - { - return teleportInvulnerabilityTimestamp != 0 && teleportInvulnerabilityTimestamp >= System.currentTimeMillis(); - } - - public boolean isVanished() - { - return vanished; - } - - public void toggleVanished() - { - vanished = !vanished; - if (vanished) - { - ess.getVanishedPlayers().add(getName()); - } - else - { - ess.getVanishedPlayers().remove(getName()); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/UserData.java b/Essentials/src/com/earth2me/essentials/UserData.java deleted file mode 100644 index c994eeed5..000000000 --- a/Essentials/src/com/earth2me/essentials/UserData.java +++ /dev/null @@ -1,812 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import java.io.File; -import java.util.*; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - - -public abstract class UserData extends PlayerExtension implements IConf -{ - protected final transient IEssentials ess; - private final EssentialsConf config; - - protected UserData(Player base, IEssentials ess) - { - super(base); - this.ess = ess; - File folder = new File(ess.getDataFolder(), "userdata"); - if (!folder.exists()) - { - folder.mkdirs(); - } - config = new EssentialsConf(new File(folder, Util.sanitizeFileName(base.getName()) + ".yml")); - reloadConfig(); - } - - @Override - public final void reloadConfig() - { - config.load(); - money = _getMoney(); - unlimited = _getUnlimited(); - powertools = _getPowertools(); - homes = _getHomes(); - lastLocation = _getLastLocation(); - lastTeleportTimestamp = _getLastTeleportTimestamp(); - lastHealTimestamp = _getLastHealTimestamp(); - jail = _getJail(); - mails = _getMails(); - teleportEnabled = getTeleportEnabled(); - ignoredPlayers = getIgnoredPlayers(); - godmode = _getGodModeEnabled(); - muted = getMuted(); - muteTimeout = _getMuteTimeout(); - jailed = getJailed(); - jailTimeout = _getJailTimeout(); - lastLogin = _getLastLogin(); - lastLogout = _getLastLogout(); - lastLoginAddress = _getLastLoginAddress(); - afk = getAfk(); - geolocation = _getGeoLocation(); - isSocialSpyEnabled = _isSocialSpyEnabled(); - isNPC = _isNPC(); - arePowerToolsEnabled = _arePowerToolsEnabled(); - kitTimestamps = _getKitTimestamps(); - nickname = _getNickname(); - } - private double money; - - private double _getMoney() - { - double money = ess.getSettings().getStartingBalance(); - if (config.hasProperty("money")) - { - money = config.getDouble("money", money); - } - if (Math.abs(money) > ess.getSettings().getMaxMoney()) - { - money = money < 0 ? -ess.getSettings().getMaxMoney() : ess.getSettings().getMaxMoney(); - } - return money; - } - - public double getMoney() - { - return money; - } - - public void setMoney(double value) - { - money = value; - if (Math.abs(money) > ess.getSettings().getMaxMoney()) - { - money = money < 0 ? -ess.getSettings().getMaxMoney() : ess.getSettings().getMaxMoney(); - } - config.setProperty("money", value); - config.save(); - } - private Map<String, Object> homes; - - private Map<String, Object> _getHomes() - { - if (config.isConfigurationSection("homes")) - { - return config.getConfigurationSection("homes").getValues(false); - } - return new HashMap<String, Object>(); - } - - public Location getHome(String name) throws Exception - { - Location loc = config.getLocation("homes." + name, getServer()); - if (loc == null) - { - try - { - loc = config.getLocation("homes." + getHomes().get(Integer.parseInt(name) - 1), getServer()); - } - catch (IndexOutOfBoundsException e) - { - return null; - } - catch (NumberFormatException e) - { - return null; - } - } - - return loc; - } - - public Location getHome(final Location world) - { - try - { - Location loc; - for (String home : getHomes()) - { - loc = config.getLocation("homes." + home, getServer()); - if (world.getWorld() == loc.getWorld()) - { - return loc; - } - - } - loc = config.getLocation("homes." + getHomes().get(0), getServer()); - return loc; - } - catch (Exception ex) - { - return null; - } - } - - public List<String> getHomes() - { - return new ArrayList<String>(homes.keySet()); - } - - public void setHome(String name, Location loc) - { - //Invalid names will corrupt the yaml - name = Util.sanitizeFileName(name); - homes.put(name, loc); - config.setProperty("homes." + name, loc); - config.save(); - } - - public void delHome(String name) throws Exception - { - String search = name; - if (!homes.containsKey(search)) - { - search = Util.sanitizeFileName(name); - } - if (homes.containsKey(search)) - { - homes.remove(name); - config.removeProperty("homes." + name); - config.save(); - } - else - { - throw new Exception(_("invalidHome", name)); - } - } - - public boolean hasHome() - { - if (config.hasProperty("home")) - { - return true; - } - return false; - } - private String nickname; - - public String _getNickname() - { - return config.getString("nickname"); - } - - public String getNickname() - { - return nickname; - } - - public void setNickname(String nick) - { - nickname = nick; - config.setProperty("nickname", nick); - config.save(); - } - private List<Integer> unlimited; - - private List<Integer> _getUnlimited() - { - return config.getIntegerList("unlimited"); - } - - public List<Integer> getUnlimited() - { - return unlimited; - } - - public boolean hasUnlimited(ItemStack stack) - { - return unlimited.contains(stack.getTypeId()); - } - - public void setUnlimited(ItemStack stack, boolean state) - { - if (unlimited.contains(stack.getTypeId())) - { - unlimited.remove(Integer.valueOf(stack.getTypeId())); - } - if (state) - { - unlimited.add(stack.getTypeId()); - } - config.setProperty("unlimited", unlimited); - config.save(); - } - private Map<String, Object> powertools; - - private Map<String, Object> _getPowertools() - { - if (config.isConfigurationSection("powertools")) - { - return config.getConfigurationSection("powertools").getValues(false); - } - return new HashMap<String, Object>(); - } - - public void clearAllPowertools() - { - powertools.clear(); - config.setProperty("powertools", powertools); - config.save(); - } - - @SuppressWarnings("unchecked") - public List<String> getPowertool(ItemStack stack) - { - return (List<String>)powertools.get("" + stack.getTypeId()); - } - - @SuppressWarnings("unchecked") - public List<String> getPowertool(int id) - { - return (List<String>)powertools.get("" + id); - } - - public void setPowertool(ItemStack stack, List<String> commandList) - { - if (commandList == null || commandList.isEmpty()) - { - powertools.remove("" + stack.getTypeId()); - } - else - { - powertools.put("" + stack.getTypeId(), commandList); - } - config.setProperty("powertools", powertools); - config.save(); - } - - public boolean hasPowerTools() - { - return !powertools.isEmpty(); - } - private Location lastLocation; - - private Location _getLastLocation() - { - try - { - return config.getLocation("lastlocation", getServer()); - } - catch (Exception e) - { - return null; - } - } - - public Location getLastLocation() - { - return lastLocation; - } - - public void setLastLocation(Location loc) - { - if (loc == null || loc.getWorld() == null) - { - return; - } - lastLocation = loc; - config.setProperty("lastlocation", loc); - config.save(); - } - private long lastTeleportTimestamp; - - private long _getLastTeleportTimestamp() - { - return config.getLong("timestamps.lastteleport", 0); - } - - public long getLastTeleportTimestamp() - { - return lastTeleportTimestamp; - } - - public void setLastTeleportTimestamp(long time) - { - lastTeleportTimestamp = time; - config.setProperty("timestamps.lastteleport", time); - config.save(); - } - private long lastHealTimestamp; - - private long _getLastHealTimestamp() - { - return config.getLong("timestamps.lastheal", 0); - } - - public long getLastHealTimestamp() - { - return lastHealTimestamp; - } - - public void setLastHealTimestamp(long time) - { - lastHealTimestamp = time; - config.setProperty("timestamps.lastheal", time); - config.save(); - } - private String jail; - - private String _getJail() - { - return config.getString("jail"); - } - - public String getJail() - { - return jail; - } - - public void setJail(String jail) - { - if (jail == null || jail.isEmpty()) - { - this.jail = null; - config.removeProperty("jail"); - } - else - { - this.jail = jail; - config.setProperty("jail", jail); - } - config.save(); - } - private List<String> mails; - - private List<String> _getMails() - { - return config.getStringList("mail"); - } - - public List<String> getMails() - { - return mails; - } - - public void setMails(List<String> mails) - { - if (mails == null) - { - config.removeProperty("mail"); - mails = _getMails(); - } - else - { - config.setProperty("mail", mails); - } - this.mails = mails; - config.save(); - } - - public void addMail(String mail) - { - mails.add(mail); - setMails(mails); - } - private boolean teleportEnabled; - - private boolean getTeleportEnabled() - { - return config.getBoolean("teleportenabled", true); - } - - public boolean isTeleportEnabled() - { - return teleportEnabled; - } - - public void setTeleportEnabled(boolean set) - { - teleportEnabled = set; - config.setProperty("teleportenabled", set); - config.save(); - } - - public boolean toggleTeleportEnabled() - { - boolean ret = !isTeleportEnabled(); - setTeleportEnabled(ret); - return ret; - } - - public boolean toggleSocialSpy() - { - boolean ret = !isSocialSpyEnabled(); - setSocialSpyEnabled(ret); - return ret; - } - private List<String> ignoredPlayers; - - public List<String> getIgnoredPlayers() - { - return config.getStringList("ignore"); - } - - public void setIgnoredPlayers(List<String> players) - { - if (players == null || players.isEmpty()) - { - ignoredPlayers = new ArrayList<String>(); - config.removeProperty("ignore"); - } - else - { - ignoredPlayers = players; - config.setProperty("ignore", players); - } - config.save(); - } - - public boolean isIgnoredPlayer(String name) - { - return ignoredPlayers.contains(name.toLowerCase(Locale.ENGLISH)); - } - - public void setIgnoredPlayer(String name, boolean set) - { - if (set) - { - ignoredPlayers.add(name.toLowerCase(Locale.ENGLISH)); - } - else - { - ignoredPlayers.remove(name.toLowerCase(Locale.ENGLISH)); - } - setIgnoredPlayers(ignoredPlayers); - } - private boolean godmode; - - private boolean _getGodModeEnabled() - { - return config.getBoolean("godmode", false); - } - - public boolean isGodModeEnabled() - { - return godmode; - } - - public void setGodModeEnabled(boolean set) - { - godmode = set; - config.setProperty("godmode", set); - config.save(); - } - - public boolean toggleGodModeEnabled() - { - boolean ret = !isGodModeEnabled(); - setGodModeEnabled(ret); - return ret; - } - private boolean muted; - - private boolean getMuted() - { - return config.getBoolean("muted", false); - } - - public boolean isMuted() - { - return muted; - } - - public void setMuted(boolean set) - { - muted = set; - config.setProperty("muted", set); - config.save(); - } - - public boolean toggleMuted() - { - boolean ret = !isMuted(); - setMuted(ret); - return ret; - } - private long muteTimeout; - - private long _getMuteTimeout() - { - return config.getLong("timestamps.mute", 0); - } - - public long getMuteTimeout() - { - return muteTimeout; - } - - public void setMuteTimeout(long time) - { - muteTimeout = time; - config.setProperty("timestamps.mute", time); - config.save(); - } - private boolean jailed; - - private boolean getJailed() - { - return config.getBoolean("jailed", false); - } - - public boolean isJailed() - { - return jailed; - } - - public void setJailed(boolean set) - { - jailed = set; - config.setProperty("jailed", set); - config.save(); - } - - public boolean toggleJailed() - { - boolean ret = !isJailed(); - setJailed(ret); - return ret; - } - private long jailTimeout; - - private long _getJailTimeout() - { - return config.getLong("timestamps.jail", 0); - } - - public long getJailTimeout() - { - return jailTimeout; - } - - public void setJailTimeout(long time) - { - jailTimeout = time; - config.setProperty("timestamps.jail", time); - config.save(); - } - - public String getBanReason() - { - return config.getString("ban.reason"); - } - - public void setBanReason(String reason) - { - config.setProperty("ban.reason", Util.sanitizeString(reason)); - config.save(); - } - - public long getBanTimeout() - { - return config.getLong("ban.timeout", 0); - } - - public void setBanTimeout(long time) - { - config.setProperty("ban.timeout", time); - config.save(); - } - private long lastLogin; - - private long _getLastLogin() - { - return config.getLong("timestamps.login", 0); - } - - public long getLastLogin() - { - return lastLogin; - } - - private void _setLastLogin(long time) - { - lastLogin = time; - config.setProperty("timestamps.login", time); - } - - public void setLastLogin(long time) - { - _setLastLogin(time); - _setLastLoginAddress(base.getAddress().getAddress().getHostAddress()); - config.save(); - } - private long lastLogout; - - private long _getLastLogout() - { - return config.getLong("timestamps.logout", 0); - } - - public long getLastLogout() - { - return lastLogout; - } - - public void setLastLogout(long time) - { - lastLogout = time; - config.setProperty("timestamps.logout", time); - config.save(); - } - private String lastLoginAddress; - - private String _getLastLoginAddress() - { - return config.getString("ipAddress", ""); - } - - public String getLastLoginAddress() - { - return lastLoginAddress; - } - - private void _setLastLoginAddress(String address) - { - lastLoginAddress = address; - config.setProperty("ipAddress", address); - } - private boolean afk; - - private boolean getAfk() - { - return config.getBoolean("afk", false); - } - - public boolean isAfk() - { - return afk; - } - - public void setAfk(boolean set) - { - afk = set; - config.setProperty("afk", set); - config.save(); - } - - public boolean toggleAfk() - { - boolean ret = !isAfk(); - setAfk(ret); - return ret; - } - private boolean newplayer; - private String geolocation; - - private String _getGeoLocation() - { - return config.getString("geolocation"); - } - - public String getGeoLocation() - { - return geolocation; - } - - public void setGeoLocation(String geolocation) - { - if (geolocation == null || geolocation.isEmpty()) - { - this.geolocation = null; - config.removeProperty("geolocation"); - } - else - { - this.geolocation = geolocation; - config.setProperty("geolocation", geolocation); - } - config.save(); - } - private boolean isSocialSpyEnabled; - - private boolean _isSocialSpyEnabled() - { - return config.getBoolean("socialspy", false); - } - - public boolean isSocialSpyEnabled() - { - return isSocialSpyEnabled; - } - - public void setSocialSpyEnabled(boolean status) - { - isSocialSpyEnabled = status; - config.setProperty("socialspy", status); - config.save(); - } - private boolean isNPC; - - private boolean _isNPC() - { - return config.getBoolean("npc", false); - } - - public boolean isNPC() - { - return isNPC; - } - - public void setNPC(boolean set) - { - isNPC = set; - config.setProperty("npc", set); - config.save(); - } - private boolean arePowerToolsEnabled; - - public boolean arePowerToolsEnabled() - { - return arePowerToolsEnabled; - } - - public void setPowerToolsEnabled(boolean set) - { - arePowerToolsEnabled = set; - config.setProperty("powertoolsenabled", set); - config.save(); - } - - public boolean togglePowerToolsEnabled() - { - boolean ret = !arePowerToolsEnabled(); - setPowerToolsEnabled(ret); - return ret; - } - - private boolean _arePowerToolsEnabled() - { - return config.getBoolean("powertoolsenabled", true); - } - private Map<String, Object> kitTimestamps; - - private Map<String, Object> _getKitTimestamps() - { - - if (config.isConfigurationSection("timestamps.kits")) - { - return config.getConfigurationSection("timestamps.kits").getValues(false); - } - return new HashMap<String, Object>(); - } - - public Long getKitTimestamp(final String name) - { - final Number num = (Number)kitTimestamps.get(name.toLowerCase(Locale.ENGLISH)); - return num == null ? null : num.longValue(); - } - - public void setKitTimestamp(final String name, final long time) - { - kitTimestamps.put(name.toLowerCase(Locale.ENGLISH), time); - config.setProperty("timestamps.kits", kitTimestamps); - config.save(); - } - - public void save() - { - config.save(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/UserMap.java b/Essentials/src/com/earth2me/essentials/UserMap.java deleted file mode 100644 index 94b504241..000000000 --- a/Essentials/src/com/earth2me/essentials/UserMap.java +++ /dev/null @@ -1,142 +0,0 @@ -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.util.concurrent.UncheckedExecutionException; -import java.io.File; -import java.util.Collections; -import java.util.Set; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.ExecutionException; -import org.bukkit.entity.Player; - - -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 ConcurrentSkipListSet<String> keys = new ConcurrentSkipListSet<String>(); - - public UserMap(final IEssentials ess) - { - super(); - this.ess = ess; - loadAllUsersAsync(ess); - } - - private void loadAllUsersAsync(final IEssentials ess) - { - ess.scheduleAsyncDelayedTask(new Runnable() - { - @Override - public void run() - { - final File userdir = new File(ess.getDataFolder(), "userdata"); - if (!userdir.exists()) - { - return; - } - keys.clear(); - users.invalidateAll(); - for (String string : userdir.list()) - { - if (!string.endsWith(".yml")) - { - continue; - } - final String name = string.substring(0, string.length() - 4); - keys.add(Util.sanitizeFileName(name)); - } - } - }); - } - - public boolean userExists(final String name) - { - return keys.contains(Util.sanitizeFileName(name)); - } - - public User getUser(final String name) - { - try - { - return users.get(name); - } - catch (ExecutionException ex) - { - return null; - } - catch (UncheckedExecutionException ex) - { - return null; - } - } - - @Override - public User load(final String name) throws Exception - { - String sanitizedName = Util.sanitizeFileName(name); - if (!sanitizedName.equals(name)) - { - User user = getUser(sanitizedName); - if (user == null) - { - throw new Exception("User not found!"); - } - else - { - return user; - } - } - for (Player player : ess.getServer().getOnlinePlayers()) - { - if (player.getName().equalsIgnoreCase(name)) - { - keys.add(sanitizedName); - return new User(player, ess); - } - } - final File userFile = getUserFile2(sanitizedName); - if (userFile.exists()) - { - keys.add(sanitizedName); - return new User(new OfflinePlayer(name, ess), ess); - } - throw new Exception("User not found!"); - } - - @Override - public void reloadConfig() - { - loadAllUsersAsync(ess); - } - - public void removeUser(final String name) - { - keys.remove(Util.sanitizeFileName(name)); - users.invalidate(Util.sanitizeFileName(name)); - users.invalidate(name); - } - - public Set<String> getAllUniqueUsers() - { - return Collections.unmodifiableSet(keys); - } - - public int getUniqueUsers() - { - return keys.size(); - } - - public File getUserFile(final String name) - { - return getUserFile2(Util.sanitizeFileName(name)); - } - - private File getUserFile2(final String name) - { - final File userFolder = new File(ess.getDataFolder(), "userdata"); - return new File(userFolder, name + ".yml"); - } -} diff --git a/Essentials/src/com/earth2me/essentials/Util.java b/Essentials/src/com/earth2me/essentials/Util.java deleted file mode 100644 index 112477ecb..000000000 --- a/Essentials/src/com/earth2me/essentials/Util.java +++ /dev/null @@ -1,621 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.*; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.bukkit.Location; -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 -{ - private Util() - { - } - private final static Logger logger = Logger.getLogger("Minecraft"); - private final static Pattern INVALIDFILECHARS = Pattern.compile("[^a-z0-9]"); - private final static Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); - - public static String sanitizeFileName(final String name) - { - final String newName = INVALIDFILECHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); - return newName; - } - - public static String sanitizeString(final String string) - { - return INVALIDCHARS.matcher(string).replaceAll(""); - } - - public static String formatDateDiff(long date) - { - Calendar c = new GregorianCalendar(); - c.setTimeInMillis(date); - Calendar now = new GregorianCalendar(); - return Util.formatDateDiff(now, c); - } - - public static String formatDateDiff(Calendar fromDate, Calendar toDate) - { - boolean future = false; - if (toDate.equals(fromDate)) - { - return _("now"); - } - if (toDate.after(fromDate)) - { - future = true; - } - - StringBuilder sb = new StringBuilder(); - int[] types = new int[] - { - Calendar.YEAR, - Calendar.MONTH, - Calendar.DAY_OF_MONTH, - Calendar.HOUR_OF_DAY, - Calendar.MINUTE, - Calendar.SECOND - }; - String[] names = new String[] - { - _("year"), - _("years"), - _("month"), - _("months"), - _("day"), - _("days"), - _("hour"), - _("hours"), - _("minute"), - _("minutes"), - _("second"), - _("seconds") - }; - int accuracy = 0; - for (int i = 0; i < types.length; i++) - { - if (accuracy > 2) - { - break; - } - int diff = dateDiff(types[i], fromDate, toDate, future); - if (diff > 0) - { - accuracy++; - sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]); - } - } - if (sb.length() == 0) - { - return "now"; - } - return sb.toString().trim(); - } - - private static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future) - { - int diff = 0; - long savedDate = fromDate.getTimeInMillis(); - while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate))) - { - savedDate = fromDate.getTimeInMillis(); - fromDate.add(type, future ? 1 : -1); - diff++; - } - diff--; - fromDate.setTimeInMillis(savedDate); - return diff; - } - - public static long parseDateDiff(String time, boolean future) throws Exception - { - Pattern timePattern = Pattern.compile( - "(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?" - + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?" - + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?" - + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?" - + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?" - + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?" - + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE); - Matcher m = timePattern.matcher(time); - int years = 0; - int months = 0; - int weeks = 0; - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - boolean found = false; - while (m.find()) - { - if (m.group() == null || m.group().isEmpty()) - { - continue; - } - for (int i = 0; i < m.groupCount(); i++) - { - if (m.group(i) != null && !m.group(i).isEmpty()) - { - found = true; - break; - } - } - if (found) - { - if (m.group(1) != null && !m.group(1).isEmpty()) - { - years = Integer.parseInt(m.group(1)); - } - if (m.group(2) != null && !m.group(2).isEmpty()) - { - months = Integer.parseInt(m.group(2)); - } - if (m.group(3) != null && !m.group(3).isEmpty()) - { - weeks = Integer.parseInt(m.group(3)); - } - if (m.group(4) != null && !m.group(4).isEmpty()) - { - days = Integer.parseInt(m.group(4)); - } - if (m.group(5) != null && !m.group(5).isEmpty()) - { - hours = Integer.parseInt(m.group(5)); - } - if (m.group(6) != null && !m.group(6).isEmpty()) - { - minutes = Integer.parseInt(m.group(6)); - } - if (m.group(7) != null && !m.group(7).isEmpty()) - { - seconds = Integer.parseInt(m.group(7)); - } - break; - } - } - if (!found) - { - throw new Exception(_("illegalDate")); - } - Calendar c = new GregorianCalendar(); - if (years > 0) - { - c.add(Calendar.YEAR, years * (future ? 1 : -1)); - } - if (months > 0) - { - c.add(Calendar.MONTH, months * (future ? 1 : -1)); - } - if (weeks > 0) - { - c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1)); - } - if (days > 0) - { - c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1)); - } - if (hours > 0) - { - c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1)); - } - if (minutes > 0) - { - c.add(Calendar.MINUTE, minutes * (future ? 1 : -1)); - } - if (seconds > 0) - { - c.add(Calendar.SECOND, seconds * (future ? 1 : -1)); - } - - Calendar max = new GregorianCalendar(); - max.add(Calendar.YEAR, 10); - if (c.after(max)) { - return max.getTimeInMillis(); - } - return c.getTimeInMillis(); - } - // The player can stand inside these materials - private static final Set<Integer> AIR_MATERIALS = new HashSet<Integer>(); - private static final HashSet<Byte> AIR_MATERIALS_TARGET = new HashSet<Byte>(); - - static - { - AIR_MATERIALS.add(Material.AIR.getId()); - AIR_MATERIALS.add(Material.SAPLING.getId()); - AIR_MATERIALS.add(Material.POWERED_RAIL.getId()); - AIR_MATERIALS.add(Material.DETECTOR_RAIL.getId()); - AIR_MATERIALS.add(Material.LONG_GRASS.getId()); - AIR_MATERIALS.add(Material.DEAD_BUSH.getId()); - AIR_MATERIALS.add(Material.YELLOW_FLOWER.getId()); - AIR_MATERIALS.add(Material.RED_ROSE.getId()); - AIR_MATERIALS.add(Material.BROWN_MUSHROOM.getId()); - AIR_MATERIALS.add(Material.RED_MUSHROOM.getId()); - AIR_MATERIALS.add(Material.TORCH.getId()); - AIR_MATERIALS.add(Material.REDSTONE_WIRE.getId()); - AIR_MATERIALS.add(Material.SEEDS.getId()); - AIR_MATERIALS.add(Material.SIGN_POST.getId()); - AIR_MATERIALS.add(Material.WOODEN_DOOR.getId()); - AIR_MATERIALS.add(Material.LADDER.getId()); - AIR_MATERIALS.add(Material.RAILS.getId()); - AIR_MATERIALS.add(Material.WALL_SIGN.getId()); - AIR_MATERIALS.add(Material.LEVER.getId()); - AIR_MATERIALS.add(Material.STONE_PLATE.getId()); - AIR_MATERIALS.add(Material.IRON_DOOR_BLOCK.getId()); - AIR_MATERIALS.add(Material.WOOD_PLATE.getId()); - AIR_MATERIALS.add(Material.REDSTONE_TORCH_OFF.getId()); - AIR_MATERIALS.add(Material.REDSTONE_TORCH_ON.getId()); - AIR_MATERIALS.add(Material.STONE_BUTTON.getId()); - AIR_MATERIALS.add(Material.SNOW.getId()); - AIR_MATERIALS.add(Material.SUGAR_CANE_BLOCK.getId()); - AIR_MATERIALS.add(Material.DIODE_BLOCK_OFF.getId()); - AIR_MATERIALS.add(Material.DIODE_BLOCK_ON.getId()); - AIR_MATERIALS.add(Material.TRAP_DOOR.getId()); - AIR_MATERIALS.add(Material.PUMPKIN_STEM.getId()); - AIR_MATERIALS.add(Material.MELON_STEM.getId()); - AIR_MATERIALS.add(Material.VINE.getId()); - AIR_MATERIALS.add(Material.FENCE_GATE.getId()); - AIR_MATERIALS.add(Material.WATER_LILY.getId()); - AIR_MATERIALS.add(Material.NETHER_FENCE.getId()); - AIR_MATERIALS.add(Material.NETHER_WARTS.getId()); - - for (Integer integer : AIR_MATERIALS) - { - AIR_MATERIALS_TARGET.add(integer.byteValue()); - } - AIR_MATERIALS_TARGET.add((byte)Material.WATER.getId()); - AIR_MATERIALS_TARGET.add((byte)Material.STATIONARY_WATER.getId()); - } - - public static Location getTarget(final LivingEntity entity) throws Exception - { - final Block block = entity.getTargetBlock(AIR_MATERIALS_TARGET, 300); - if (block == null) - { - throw new Exception("Not targeting a block"); - } - return block.getLocation(); - } - - public static Location getSafeDestination(final Location loc) throws Exception - { - if (loc == null || loc.getWorld() == null) - { - throw new Exception(_("destinationNotSet")); - } - final World world = loc.getWorld(); - int x = loc.getBlockX(); - int y = (int)Math.round(loc.getY()); - int z = loc.getBlockZ(); - - while (isBlockAboveAir(world, x, y, z)) - { - y -= 1; - if (y < 0) - { - break; - } - } - - while (isBlockUnsafe(world, x, y, z)) - { - y += 1; - if (y >= world.getHighestBlockYAt(x, z)) - { - x += 1; - break; - } - } - while (isBlockUnsafe(world, x, y, z)) - { - y -= 1; - if (y <= 1) - { - x += 1; - y = world.getHighestBlockYAt(x, z); - if (x - 32 > loc.getBlockX()) - { - throw new Exception(_("holeInFloor")); - } - } - } - return new Location(world, x + 0.5D, y, z + 0.5D, loc.getYaw(), loc.getPitch()); - } - - private static boolean isBlockAboveAir(final World world, final int x, final int y, final int z) - { - return AIR_MATERIALS.contains(world.getBlockAt(x, y - 1, z).getType().getId()); - } - - public static boolean isBlockUnsafe(final World world, final int x, final int y, final int z) - { - final Block below = world.getBlockAt(x, y - 1, z); - if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA) - { - return true; - } - - if (below.getType() == Material.FIRE) - { - return true; - } - - if ((!AIR_MATERIALS.contains(world.getBlockAt(x, y, z).getType().getId())) - || (!AIR_MATERIALS.contains(world.getBlockAt(x, y + 1, z).getType().getId()))) - { - return true; - } - 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 dFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US)); - - public static String formatAsCurrency(final double value) - { - String str = dFormat.format(value); - if (str.endsWith(".00")) - { - str = str.substring(0, str.length() - 3); - } - return str; - } - - public static String displayCurrency(final double value, final IEssentials ess) - { - return _("currency", ess.getSettings().getCurrencySymbol(), formatAsCurrency(value)); - } - - public static String shortCurrency(final double value, final IEssentials ess) - { - return ess.getSettings().getCurrencySymbol() + formatAsCurrency(value); - } - - public static double roundDouble(final double d) - { - return Math.round(d * 100.0) / 100.0; - } - - public static boolean isInt(final String sInt) - { - try - { - Integer.parseInt(sInt); - } - catch (NumberFormatException e) - { - return false; - } - return true; - } - - public static String joinList(Object... list) - { - return joinList(", ", list); - } - - public static String joinList(String seperator, Object... list) - { - StringBuilder buf = new StringBuilder(); - for (Object each : list) - { - if (buf.length() > 0) - { - buf.append(seperator); - } - - if (each instanceof Collection) - { - buf.append(joinList(seperator, ((Collection)each).toArray())); - } - else - { - try - { - buf.append(each.toString()); - } - catch (Exception e) - { - buf.append(each.toString()); - } - } - } - return buf.toString(); - } - - public static String lastCode(final String input) { - int pos = input.lastIndexOf("§"); - if (pos == -1 || (pos + 1) == input.length()) { - return ""; - } - return input.substring(pos, pos + 2); - } - - private static transient final Pattern URL_PATTERN = Pattern.compile("((?:(?:https?)://)?[\\w-_\\.]{2,})\\.([a-z]{2,3}(?:/\\S+)?)"); - private static transient final Pattern VANILLA_PATTERN = Pattern.compile("\u00A7+[0-9A-FK-ORa-fk-or]"); - private static transient final Pattern REPLACE_PATTERN = Pattern.compile("&([0-9a-fk-or])"); - private static transient final Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00A7+[0-9A-Fa-f]"); - private static transient final Pattern VANILLA_MAGIC_PATTERN = Pattern.compile("\u00A7+[Kk]"); - private static transient final Pattern VANILLA_FORMAT_PATTERN = Pattern.compile("\u00A7+[L-ORl-or]"); - private static transient final Pattern REPLACE_COLOR_PATTERN = Pattern.compile("&([0-9a-f])"); - private static transient final Pattern REPLACE_MAGIC_PATTERN = Pattern.compile("&(k)"); - private static transient final Pattern REPLACE_FORMAT_PATTERN = Pattern.compile("&([l-or])"); - - public static String stripFormat(final String input) - { - if (input == null) - { - return null; - } - return VANILLA_PATTERN.matcher(input).replaceAll(""); - } - - public static String replaceFormat(final String input) - { - if (input == null) - { - return null; - } - return REPLACE_PATTERN.matcher(input).replaceAll("\u00a7$1"); - } - - public static String blockURL(final String input) - { - if (input == null) - { - return null; - } - String text = URL_PATTERN.matcher(input).replaceAll("$1 $2"); - while (URL_PATTERN.matcher(text).find()) - { - text = URL_PATTERN.matcher(text).replaceAll("$1 $2"); - } - return text; - } - - public static String formatString(final IUser user, final String permBase, final String input) - { - if (input == null) - { - return null; - } - String message; - if (user.isAuthorized(permBase + ".color")) - { - message = Util.replaceColor(input, REPLACE_COLOR_PATTERN); - } - else - { - message = Util.stripColor(input, VANILLA_COLOR_PATTERN); - } - if (user.isAuthorized(permBase + ".magic")) - { - message = Util.replaceColor(message, REPLACE_MAGIC_PATTERN); - } - else - { - message = Util.stripColor(message, VANILLA_MAGIC_PATTERN); - } - if (user.isAuthorized(permBase + ".format")) - { - message = Util.replaceColor(message, REPLACE_FORMAT_PATTERN); - } - else - { - message = Util.stripColor(message, VANILLA_FORMAT_PATTERN); - } - return message; - } - - public static String formatMessage(final IUser user, final String permBase, final String input) - { - if (input == null) - { - return null; - } - String message = formatString(user, permBase, input); - if (!user.isAuthorized(permBase + ".url")) - { - message = Util.blockURL(message); - } - return message; - } - - private static String stripColor(final String input, final Pattern pattern) - { - return pattern.matcher(input).replaceAll(""); - } - - private static String replaceColor(final String input, final Pattern pattern) - { - return pattern.matcher(input).replaceAll("\u00a7$1"); - } -} diff --git a/Essentials/src/com/earth2me/essentials/Warps.java b/Essentials/src/com/earth2me/essentials/Warps.java index ece987aba..bbf01678b 100644 --- a/Essentials/src/com/earth2me/essentials/Warps.java +++ b/Essentials/src/com/earth2me/essentials/Warps.java @@ -1,121 +1,121 @@ package com.earth2me.essentials; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IWarp; +import com.earth2me.essentials.api.IWarps; +import com.earth2me.essentials.api.InvalidNameException; import com.earth2me.essentials.commands.WarpNotFoundException; +import com.earth2me.essentials.settings.WarpHolder; +import com.earth2me.essentials.storage.StorageObjectMap; 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.Server; -public class Warps implements IConf +public class Warps extends StorageObjectMap<IWarp> implements IWarps { - private static final Logger logger = Logger.getLogger("Minecraft"); - private final Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>(); - private final File warpsFolder; - private final Server server; + private static final Logger logger = Bukkit.getLogger(); - public Warps(Server server, File dataFolder) + public Warps(IEssentials ess) { - this.server = server; - warpsFolder = new File(dataFolder, "warps"); - if (!warpsFolder.exists()) - { - warpsFolder.mkdirs(); - } - reloadConfig(); + super(ess, "warps"); } + @Override public boolean isEmpty() { - return warpPoints.isEmpty(); + return getKeySize() == 0; } - public Collection<String> getWarpNames() + @Override + public Collection<String> getList() { - final List<String> keys = new ArrayList<String>(); - for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) + final List<String> names = new ArrayList<String>(); + for (String key : getAllKeys()) { - keys.add(stringIgnoreCase.getString()); + IWarp warp = getObject(key); + if (warp == null) + { + continue; + } + warp.acquireReadLock(); + try + { + names.add(warp.getData().getName()); + } + finally + { + warp.unlock(); + } } - Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); - return keys; + Collections.sort(names, String.CASE_INSENSITIVE_ORDER); + return names; } - public Location getWarp(String warp) throws Exception + @Override + public Location getWarp(final String name) throws Exception { - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); - if (conf == null) + IWarp warp = getObject(name); + if (warp == null) { - throw new WarpNotFoundException(); + throw new WarpNotFoundException(_("warpNotExist")); } - return conf.getLocation(null, server); - } - - public void setWarp(String name, Location loc) throws Exception - { - String filename = Util.sanitizeFileName(name); - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); - if (conf == null) + warp.acquireReadLock(); + try { - File confFile = new File(warpsFolder, filename + ".yml"); - if (confFile.exists()) - { - throw new Exception(_("similarWarpExist")); - } - conf = new EssentialsConf(confFile); - warpPoints.put(new StringIgnoreCase(name), conf); + return warp.getData().getLocation().getBukkitLocation(); + } + finally + { + warp.unlock(); } - conf.setProperty(null, loc); - conf.setProperty("name", name); - conf.save(); } - public void delWarp(String name) throws Exception + @Override + public void setWarp(final String name, final Location loc) throws Exception + { + setWarp(name, new com.earth2me.essentials.storage.Location(loc)); + } + + public void setWarp(final String name, final com.earth2me.essentials.storage.Location loc) throws Exception { - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); - if (conf == null) + IWarp warp = getObject(name); + if (warp == null) + { + warp = new WarpHolder(name, ess); + } + warp.acquireWriteLock(); + try { - throw new Exception(_("warpNotExist")); + warp.getData().setLocation(loc); } - if (!conf.getFile().delete()) + finally { - throw new Exception(_("warpDeleteError")); + warp.unlock(); } - warpPoints.remove(new StringIgnoreCase(name)); } @Override - public final void reloadConfig() + public void removeWarp(final String name) throws Exception { - warpPoints.clear(); - File[] listOfFiles = warpsFolder.listFiles(); - if (listOfFiles.length >= 1) - { - for (int i = 0; i < listOfFiles.length; i++) - { - String filename = listOfFiles[i].getName(); - if (listOfFiles[i].isFile() && filename.endsWith(".yml")) - { - try - { - EssentialsConf conf = new EssentialsConf(listOfFiles[i]); - conf.load(); - String name = conf.getString("name"); - if (name != null) - { - warpPoints.put(new StringIgnoreCase(name), conf); - } - } - catch (Exception ex) - { - logger.log(Level.WARNING, _("loadWarpError", filename), ex); - } - } - } - } + removeObject(name); + } + + @Override + public File getWarpFile(String name) throws InvalidNameException + { + return getStorageFile(name); + } + + @Override + public IWarp load(String name) throws Exception + { + final IWarp warp = new WarpHolder(name, ess); + warp.onReload(); + return warp; } diff --git a/Essentials/src/com/earth2me/essentials/Worth.java b/Essentials/src/com/earth2me/essentials/Worth.java deleted file mode 100644 index b597bd3e8..000000000 --- a/Essentials/src/com/earth2me/essentials/Worth.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.earth2me.essentials; - -import java.io.File; -import java.util.Locale; -import java.util.logging.Logger; -import org.bukkit.inventory.ItemStack; - - -public class Worth implements IConf -{ - private static final Logger logger = Logger.getLogger("Minecraft"); - private final EssentialsConf config; - - public Worth(File dataFolder) - { - config = new EssentialsConf(new File(dataFolder, "worth.yml")); - config.setTemplateName("/worth.yml"); - config.load(); - } - - public double getPrice(ItemStack itemStack) - { - String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - double result; - result = config.getDouble("worth." + itemname + "." + itemStack.getDurability(), Double.NaN); - if (Double.isNaN(result)) - { - result = config.getDouble("worth." + itemname + ".0", Double.NaN); - } - if (Double.isNaN(result)) - { - result = config.getDouble("worth." + itemname, Double.NaN); - } - if (Double.isNaN(result)) - { - result = config.getDouble("worth-" + itemStack.getTypeId(), Double.NaN); - } - return result; - } - - public void setPrice(ItemStack itemStack, double price) - { - if (itemStack.getType().getData() == null) - { - config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), price); - } - else - { - // Bukkit-bug: getDurability still contains the correct value, while getData().getData() is 0. - config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "") + "." + itemStack.getDurability(), price); - } - config.removeProperty("worth-" + itemStack.getTypeId()); - config.save(); - } - - @Override - public void reloadConfig() - { - config.load(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/ChargeException.java b/Essentials/src/com/earth2me/essentials/api/ChargeException.java index 2fa4c7289..5b157ce63 100644 --- a/Essentials/src/com/earth2me/essentials/ChargeException.java +++ b/Essentials/src/com/earth2me/essentials/api/ChargeException.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.api; public class ChargeException extends Exception diff --git a/Essentials/src/com/earth2me/essentials/api/Economy.java b/Essentials/src/com/earth2me/essentials/api/Economy.java deleted file mode 100644 index 6ed1829b3..000000000 --- a/Essentials/src/com/earth2me/essentials/api/Economy.java +++ /dev/null @@ -1,311 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.EssentialsConf; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import java.io.File; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.entity.Player; - - -/** - * Instead of using this api directly, we recommend to use the register plugin: - * http://bit.ly/RegisterMethod - */ -public final class Economy -{ - private Economy() - { - } - private static final Logger logger = Logger.getLogger("Minecraft"); - private static IEssentials ess; - private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded."; - - /** - * @param aEss the ess to set - */ - public static void setEss(IEssentials aEss) - { - ess = aEss; - } - - private static void createNPCFile(String name) - { - File folder = new File(ess.getDataFolder(), "userdata"); - if (!folder.exists()) - { - folder.mkdirs(); - } - EssentialsConf npcConfig = new EssentialsConf(new File(folder, Util.sanitizeFileName(name) + ".yml")); - npcConfig.load(); - npcConfig.setProperty("npc", true); - npcConfig.setProperty("money", ess.getSettings().getStartingBalance()); - npcConfig.save(); - } - - private static void deleteNPC(String name) - { - File folder = new File(ess.getDataFolder(), "userdata"); - if (!folder.exists()) - { - folder.mkdirs(); - } - File config = new File(folder, Util.sanitizeFileName(name) + ".yml"); - EssentialsConf npcConfig = new EssentialsConf(config); - npcConfig.load(); - if (npcConfig.hasProperty("npc") && npcConfig.getBoolean("npc", false)) - { - if (!config.delete()) - { - logger.log(Level.WARNING, _("deleteFileError", config)); - } - ess.getUserMap().removeUser(name); - } - } - - private static User getUserByName(String name) - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - User user; - Player player = ess.getServer().getPlayer(name); - if (player != null) - { - user = ess.getUser(player); - } - else - { - user = ess.getOfflineUser(name); - } - return user; - } - - /** - * Returns the balance of a user - * @param name Name of the user - * @return balance - * @throws UserDoesNotExistException - */ - public static double getMoney(String name) throws UserDoesNotExistException - { - User user = getUserByName(name); - if (user == null) - { - throw new UserDoesNotExistException(name); - } - return user.getMoney(); - } - - /** - * Sets the balance of a user - * @param name Name of the user - * @param balance The balance you want to set - * @throws UserDoesNotExistException If a user by that name does not exists - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance - */ - public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException - { - User user = getUserByName(name); - if (user == null) - { - throw new UserDoesNotExistException(name); - } - if (balance < ess.getSettings().getMinMoney()) - { - throw new NoLoanPermittedException(); - } - if (balance < 0.0 && !user.isAuthorized("essentials.eco.loan")) - { - throw new NoLoanPermittedException(); - } - user.setMoney(balance); - } - - /** - * Adds money to the balance of a user - * @param name Name of the user - * @param amount The money you want to add - * @throws UserDoesNotExistException If a user by that name does not exists - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance - */ - public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException - { - double result = getMoney(name) + amount; - setMoney(name, result); - } - - /** - * Substracts money from the balance of a user - * @param name Name of the user - * @param amount The money you want to substract - * @throws UserDoesNotExistException If a user by that name does not exists - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance - */ - public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException - { - double result = getMoney(name) - amount; - setMoney(name, result); - } - - /** - * Divides the balance of a user by a value - * @param name Name of the user - * @param value The balance is divided by this value - * @throws UserDoesNotExistException If a user by that name does not exists - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance - */ - public static void divide(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException - { - double result = getMoney(name) / value; - setMoney(name, result); - } - - /** - * Multiplies the balance of a user by a value - * @param name Name of the user - * @param value The balance is multiplied by this value - * @throws UserDoesNotExistException If a user by that name does not exists - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance - */ - public static void multiply(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException - { - double result = getMoney(name) * value; - setMoney(name, result); - } - - /** - * Resets the balance of a user to the starting balance - * @param name Name of the user - * @throws UserDoesNotExistException If a user by that name does not exists - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance - */ - public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - setMoney(name, ess.getSettings().getStartingBalance()); - } - - /** - * @param name Name of the user - * @param amount The amount of money the user should have - * @return true, if the user has more or an equal amount of money - * @throws UserDoesNotExistException If a user by that name does not exists - */ - public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException - { - return amount <= getMoney(name); - } - - /** - * @param name Name of the user - * @param amount The amount of money the user should have - * @return true, if the user has more money - * @throws UserDoesNotExistException If a user by that name does not exists - */ - public static boolean hasMore(String name, double amount) throws UserDoesNotExistException - { - return amount < getMoney(name); - } - - /** - * @param name Name of the user - * @param amount The amount of money the user should not have - * @return true, if the user has less money - * @throws UserDoesNotExistException If a user by that name does not exists - */ - public static boolean hasLess(String name, double amount) throws UserDoesNotExistException - { - return amount > getMoney(name); - } - - /** - * Test if the user has a negative balance - * @param name Name of the user - * @return true, if the user has a negative balance - * @throws UserDoesNotExistException If a user by that name does not exists - */ - public static boolean isNegative(String name) throws UserDoesNotExistException - { - return getMoney(name) < 0.0; - } - - /** - * Formats the amount of money like all other Essentials functions. - * Example: $100000 or $12345.67 - * @param amount The amount of money - * @return Formatted money - */ - public static String format(double amount) - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - return Util.displayCurrency(amount, ess); - } - - /** - * Test if a player exists to avoid the UserDoesNotExistException - * @param name Name of the user - * @return true, if the user exists - */ - public static boolean playerExists(String name) - { - return getUserByName(name) != null; - } - - /** - * Test if a player is a npc - * @param name Name of the player - * @return true, if it's a npc - * @throws UserDoesNotExistException - */ - public static boolean isNPC(String name) throws UserDoesNotExistException - { - User user = getUserByName(name); - if (user == null) - { - throw new UserDoesNotExistException(name); - } - return user.isNPC(); - } - - /** - * Creates dummy files for a npc, if there is no player yet with that name. - * @param name Name of the player - * @return true, if a new npc was created - */ - public static boolean createNPC(String name) - { - User user = getUserByName(name); - if (user == null) - { - createNPCFile(name); - return true; - } - return false; - } - - /** - * Deletes a user, if it is marked as npc. - * @param name Name of the player - * @throws UserDoesNotExistException - */ - public static void removeNPC(String name) throws UserDoesNotExistException - { - User user = getUserByName(name); - if (user == null) - { - throw new UserDoesNotExistException(name); - } - deleteNPC(name); - } -} diff --git a/Essentials/src/com/earth2me/essentials/api/IAlternativeCommandsHandler.java b/Essentials/src/com/earth2me/essentials/api/IAlternativeCommandsHandler.java deleted file mode 100644 index 11619bca4..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IAlternativeCommandsHandler.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.earth2me.essentials.api; - -import java.util.Map; -import org.bukkit.command.PluginCommand; - - -public interface IAlternativeCommandsHandler -{ - Map<String, String> disabledCommands(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IBackup.java b/Essentials/src/com/earth2me/essentials/api/IBackup.java new file mode 100644 index 000000000..8af074c54 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IBackup.java @@ -0,0 +1,7 @@ +package com.earth2me.essentials.api; + + +public interface IBackup extends Runnable +{ + public void startTask(); +} diff --git a/Essentials/src/com/earth2me/essentials/api/ICommandHandler.java b/Essentials/src/com/earth2me/essentials/api/ICommandHandler.java new file mode 100644 index 000000000..f756c16c4 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/ICommandHandler.java @@ -0,0 +1,20 @@ +package com.earth2me.essentials.api; + +import java.util.Map; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; + + +public interface ICommandHandler extends IReload +{ + Map<String, String> disabledCommands(); + + public void removePlugin(Plugin plugin); + + public void addPlugin(Plugin plugin); + + boolean handleCommand(CommandSender sender, Command command, String commandLabel, String[] args); + + void showCommandError(CommandSender sender, String commandLabel, Throwable exception); +} diff --git a/Essentials/src/com/earth2me/essentials/api/IEconomy.java b/Essentials/src/com/earth2me/essentials/api/IEconomy.java new file mode 100644 index 000000000..092d86c88 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IEconomy.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.api; + + +public interface IEconomy extends IReload +{ + public double getMoney(String name) throws UserDoesNotExistException; + + public void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException; + + public void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException; + + public String format(double amount); + + public boolean playerExists(String name); + + public boolean isNPC(String name) throws UserDoesNotExistException; + + public boolean createNPC(String name); + + public void removeNPC(String name) throws UserDoesNotExistException; +} diff --git a/Essentials/src/com/earth2me/essentials/api/IEssentials.java b/Essentials/src/com/earth2me/essentials/api/IEssentials.java index c04bed0bd..42c9a964d 100644 --- a/Essentials/src/com/earth2me/essentials/api/IEssentials.java +++ b/Essentials/src/com/earth2me/essentials/api/IEssentials.java @@ -1,17 +1,19 @@ package com.earth2me.essentials.api; -import com.earth2me.essentials.perm.IPermissionsHandler; -import com.earth2me.essentials.register.payment.Methods; +import com.earth2me.essentials.listener.TntExplodeListener; +import com.earth2me.essentials.economy.register.Methods; import org.bukkit.World; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -public interface IEssentials extends Plugin, IReload +public interface IEssentials extends Plugin { void addReloadListener(IReload listener); - IUser getUser(Object base); + IUser getUser(Player player); + + IUser getUser(String playerName); int broadcastMessage(IUser sender, String message); @@ -19,7 +21,11 @@ public interface IEssentials extends Plugin, IReload ISettings getSettings(); - IJails getJail(); + IRanks getRanks(); + + IJails getJails(); + + IKits getKits(); IWarps getWarps(); @@ -29,7 +35,9 @@ public interface IEssentials extends Plugin, IReload IUserMap getUserMap(); - IEssentialsEconomy getEconomy(); + IBackup getBackup(); + + ICommandHandler getCommandHandler(); World getWorld(String name); @@ -43,9 +51,14 @@ public interface IEssentials extends Plugin, IReload int scheduleSyncRepeatingTask(Runnable run, long delay, long period); - IPermissionsHandler getPermissionsHandler(); + //IPermissionsHandler getPermissionsHandler(); + void reload(); + + TntExplodeListener getTNTListener(); + + void setRanks(IRanks groups); - IAlternativeCommandsHandler getAlternativeCommandsHandler(); + void removeReloadListener(IReload groups); - void showCommandError(CommandSender sender, String commandLabel, Throwable exception); + IEconomy getEconomy(); } diff --git a/Essentials/src/com/earth2me/essentials/api/IEssentialsEconomy.java b/Essentials/src/com/earth2me/essentials/api/IEssentialsEconomy.java deleted file mode 100644 index 72fb89d26..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IEssentialsEconomy.java +++ /dev/null @@ -1,37 +0,0 @@ -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; -} diff --git a/Essentials/src/com/earth2me/essentials/IEssentialsModule.java b/Essentials/src/com/earth2me/essentials/api/IEssentialsModule.java index 69a1a494c..cc185980a 100644 --- a/Essentials/src/com/earth2me/essentials/IEssentialsModule.java +++ b/Essentials/src/com/earth2me/essentials/api/IEssentialsModule.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.api; public interface IEssentialsModule diff --git a/Essentials/src/com/earth2me/essentials/api/IItemDb.java b/Essentials/src/com/earth2me/essentials/api/IItemDb.java index ee4819215..29f97488c 100644 --- a/Essentials/src/com/earth2me/essentials/api/IItemDb.java +++ b/Essentials/src/com/earth2me/essentials/api/IItemDb.java @@ -3,9 +3,11 @@ package com.earth2me.essentials.api; import org.bukkit.inventory.ItemStack; -public interface IItemDb +public interface IItemDb extends IReload { + ItemStack get(final String name, final IUser user) throws Exception; + ItemStack get(final String name, final int quantity) throws Exception; - + ItemStack get(final String name) throws Exception; } diff --git a/Essentials/src/com/earth2me/essentials/api/IJails.java b/Essentials/src/com/earth2me/essentials/api/IJails.java index e19b76837..fb8d2f090 100644 --- a/Essentials/src/com/earth2me/essentials/api/IJails.java +++ b/Essentials/src/com/earth2me/essentials/api/IJails.java @@ -14,7 +14,7 @@ public interface IJails extends IReload void removeJail(String jail) throws Exception; - void sendToJail(com.earth2me.essentials.IUser user, String jail) throws Exception; + void sendToJail(IUser user, String jail) throws Exception; void setJail(String jailName, Location loc) throws Exception; } diff --git a/Essentials/src/com/earth2me/essentials/api/IKits.java b/Essentials/src/com/earth2me/essentials/api/IKits.java new file mode 100644 index 000000000..85ca4cdea --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IKits.java @@ -0,0 +1,18 @@ +package com.earth2me.essentials.api; + +import com.earth2me.essentials.settings.Kit; +import java.util.Collection; + + +public interface IKits extends IReload +{ + Kit getKit(String kit) throws Exception; + + void sendKit(IUser user, String kit) throws Exception; + + void sendKit(IUser user, Kit kit) throws Exception; + + Collection<String> getList() throws Exception; + + boolean isEmpty(); +} diff --git a/Essentials/src/com/earth2me/essentials/api/IPermission.java b/Essentials/src/com/earth2me/essentials/api/IPermission.java new file mode 100644 index 000000000..d388bff47 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IPermission.java @@ -0,0 +1,17 @@ +package com.earth2me.essentials.api; + +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public interface IPermission +{ + String getPermission(); + + boolean isAuthorized(CommandSender sender); + + Permission getBukkitPermission(); + + PermissionDefault getPermissionDefault(); +} diff --git a/Essentials/src/com/earth2me/essentials/api/IRanks.java b/Essentials/src/com/earth2me/essentials/api/IRanks.java new file mode 100644 index 000000000..e29b31302 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IRanks.java @@ -0,0 +1,25 @@ +package com.earth2me.essentials.api; + +import java.text.MessageFormat; + + +public interface IRanks +{ + String getMainGroup(IUser player); + + boolean inGroup(IUser player, String groupname); + + double getHealCooldown(IUser player); + + double getTeleportCooldown(IUser player); + + double getTeleportDelay(IUser player); + + String getPrefix(IUser player); + + String getSuffix(IUser player); + + int getHomeLimit(IUser player); + + MessageFormat getChatFormat(IUser player); +} diff --git a/Essentials/src/com/earth2me/essentials/api/IReplyTo.java b/Essentials/src/com/earth2me/essentials/api/IReplyTo.java new file mode 100644 index 000000000..3003ca3df --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IReplyTo.java @@ -0,0 +1,11 @@ +package com.earth2me.essentials.api; + +import org.bukkit.command.CommandSender; + + +public interface IReplyTo +{ + void setReplyTo(CommandSender user); + + CommandSender getReplyTo(); +} diff --git a/Essentials/src/com/earth2me/essentials/api/ISettings.java b/Essentials/src/com/earth2me/essentials/api/ISettings.java index eff65ad87..a445d21b4 100644 --- a/Essentials/src/com/earth2me/essentials/api/ISettings.java +++ b/Essentials/src/com/earth2me/essentials/api/ISettings.java @@ -6,5 +6,9 @@ import com.earth2me.essentials.storage.IStorageObjectHolder; public interface ISettings extends IStorageObjectHolder<Settings> { - + public String getLocale(); + + public boolean isDebug(); + + public void setDebug(boolean b); } diff --git a/Essentials/src/com/earth2me/essentials/api/ITeleport.java b/Essentials/src/com/earth2me/essentials/api/ITeleport.java index 5b9a19757..3a5f25f78 100644 --- a/Essentials/src/com/earth2me/essentials/api/ITeleport.java +++ b/Essentials/src/com/earth2me/essentials/api/ITeleport.java @@ -1,10 +1,28 @@ package com.earth2me.essentials.api; +import com.earth2me.essentials.economy.Trade; import org.bukkit.Location; +import org.bukkit.entity.Entity; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public interface ITeleport { void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception; + + void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception; + + void back(Trade chargeFor) throws Exception; + + void teleport(Location bed, Trade charge, TeleportCause teleportCause) throws Exception; + + void teleport(Entity entity, Trade chargeFor, TeleportCause cause) throws Exception; + + void home(IUser player, String toLowerCase, Trade charge) throws Exception; + + void respawn(Trade charge, TeleportCause teleportCause) throws Exception; + + void back() throws Exception; + + public void warp(String name, Trade charge, TeleportCause teleportCause) throws Exception; } diff --git a/Essentials/src/com/earth2me/essentials/api/IUser.java b/Essentials/src/com/earth2me/essentials/api/IUser.java index 5d2f9d4b8..091b141df 100644 --- a/Essentials/src/com/earth2me/essentials/api/IUser.java +++ b/Essentials/src/com/earth2me/essentials/api/IUser.java @@ -1,43 +1,110 @@ package com.earth2me.essentials.api; -import com.earth2me.essentials.commands.IEssentialsCommand; +import com.earth2me.essentials.storage.IStorageObjectHolder; +import com.earth2me.essentials.user.CooldownException; +import com.earth2me.essentials.user.UserData; +import java.util.List; import org.bukkit.Location; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; -public interface IUser extends Player, IReload +public interface IUser extends Player, IStorageObjectHolder<UserData>, IReload, IReplyTo, Comparable<IUser> { - long getLastTeleportTimestamp(); + Player getBase(); - boolean isAuthorized(String node); + double getMoney(); - boolean isAuthorized(IEssentialsCommand cmd); + void takeMoney(double value); - boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix); + void takeMoney(double value, CommandSender initiator); - void setLastTeleportTimestamp(long time); + void giveMoney(double value); - Location getLastLocation(); + void giveMoney(double value, CommandSender initiator); - Player getBase(); + void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException; - double getMoney(); + void giveItems(List<ItemStack> itemStacks, Boolean canSpew) throws ChargeException; - void takeMoney(double value); - - void giveMoney(double value); + void setMoney(double value); - String getGroup(); + void payUser(final IUser reciever, final double value) throws Exception; void setLastLocation(); Location getHome(String name) throws Exception; - Location getHome(Location loc) throws Exception; + Location getHome(Location loc); boolean isHidden(); - + ITeleport getTeleport(); - - void setJail(String jail); + + void checkCooldown(UserData.TimestampType cooldownType, double cooldown, boolean set, IPermission bypassPermission) throws CooldownException; + + boolean toggleAfk(); + + void updateActivity(boolean broadcast); + + void updateDisplayName(); + + boolean checkJailTimeout(long currentTime); + + boolean checkMuteTimeout(long currentTime); + + boolean checkBanTimeout(long currentTime); + + long getTimestamp(UserData.TimestampType name); + + void setTimestamp(UserData.TimestampType name, long value); + + void setLastOnlineActivity(long currentTime); + + void checkActivity(); + + long getLastOnlineActivity(); + + boolean isGodModeEnabled(); + + boolean isIgnoringPlayer(String name); + + void setIgnoredPlayer(String name, boolean set); + + Location getAfkPosition(); + + boolean toggleGodModeEnabled(); + + void dispose(); + + void updateCompass(); + + List<String> getHomes(); + + void addMail(String string); + + boolean toggleMuted(); + + boolean toggleSocialSpy(); + + void requestTeleport(IUser user, boolean b); + + boolean isTeleportRequestHere(); + + IUser getTeleportRequester(); + + boolean toggleTeleportEnabled(); + + long getTeleportRequestTime(); + + boolean gotMailInfo(); + + List<String> getMails(); + + public boolean canAfford(double money); + + public void updateMoneyCache(double userMoney); + + public boolean canAfford(double amount, boolean b); } diff --git a/Essentials/src/com/earth2me/essentials/api/IUserMap.java b/Essentials/src/com/earth2me/essentials/api/IUserMap.java index 9e609ab37..fbe6cfa0e 100644 --- a/Essentials/src/com/earth2me/essentials/api/IUserMap.java +++ b/Essentials/src/com/earth2me/essentials/api/IUserMap.java @@ -2,19 +2,22 @@ package com.earth2me.essentials.api; import java.io.File; import java.util.Set; +import org.bukkit.entity.Player; -public interface IUserMap +public interface IUserMap extends IReload { boolean userExists(final String name); - IUser getUser(final String name); + IUser getUser(final Player player); - void removeUser(final String name); + IUser getUser(final String playerName); + + void removeUser(final String name) throws InvalidNameException; Set<String> getAllUniqueUsers(); int getUniqueUsers(); - File getUserFile(final String name); + File getUserFile(final String name) throws InvalidNameException; } diff --git a/Essentials/src/com/earth2me/essentials/api/IWarp.java b/Essentials/src/com/earth2me/essentials/api/IWarp.java new file mode 100644 index 000000000..f08e5757d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IWarp.java @@ -0,0 +1,9 @@ +package com.earth2me.essentials.api; + +import com.earth2me.essentials.settings.Warp; +import com.earth2me.essentials.storage.IStorageObjectHolder; + + +public interface IWarp extends IStorageObjectHolder<Warp> +{ +} diff --git a/Essentials/src/com/earth2me/essentials/api/IWarps.java b/Essentials/src/com/earth2me/essentials/api/IWarps.java index 14779e327..2a98ecc64 100644 --- a/Essentials/src/com/earth2me/essentials/api/IWarps.java +++ b/Essentials/src/com/earth2me/essentials/api/IWarps.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.api; +import java.io.File; import java.util.Collection; import org.bukkit.Location; @@ -8,9 +9,13 @@ public interface IWarps extends IReload { Location getWarp(String warp) throws Exception; - Collection<String> getWarps(); + Collection<String> getList(); void removeWarp(String name) throws Exception; void setWarp(String name, Location loc) throws Exception; + + public boolean isEmpty(); + + public File getWarpFile(String name) throws InvalidNameException; } diff --git a/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java b/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java new file mode 100644 index 000000000..951c66b17 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java @@ -0,0 +1,10 @@ +package com.earth2me.essentials.api; + + +public class InvalidNameException extends Exception +{ + public InvalidNameException(Throwable thrwbl) + { + super(thrwbl); + } +} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IPermission.java b/Essentials/src/com/earth2me/essentials/api/server/IPermission.java new file mode 100644 index 000000000..3b5cf2eb4 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/server/IPermission.java @@ -0,0 +1,5 @@ +package com.earth2me.essentials.api.server; + +public interface IPermission { + +} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IPermissionsManager.java b/Essentials/src/com/earth2me/essentials/api/server/IPermissionsManager.java new file mode 100644 index 000000000..d8f017e20 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/server/IPermissionsManager.java @@ -0,0 +1,8 @@ +package com.earth2me.essentials.api.server; + +public interface IPermissionsManager { + + IPermission registerPermission(); + + boolean checkPermission(IPlayer player, IPermission perm); +} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IPlayer.java b/Essentials/src/com/earth2me/essentials/api/server/IPlayer.java new file mode 100644 index 000000000..7d0899e81 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/server/IPlayer.java @@ -0,0 +1,5 @@ +package com.earth2me.essentials.api.server; + +public interface IPlayer { + +} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IServer.java b/Essentials/src/com/earth2me/essentials/api/server/IServer.java new file mode 100644 index 000000000..2c267b6cb --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/server/IServer.java @@ -0,0 +1,5 @@ +package com.earth2me.essentials.api.server; + +public interface IServer { + +} diff --git a/Essentials/src/com/earth2me/essentials/backup/Backup.java b/Essentials/src/com/earth2me/essentials/backup/Backup.java new file mode 100644 index 000000000..2da391af9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/backup/Backup.java @@ -0,0 +1,153 @@ +package com.earth2me.essentials.backup; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IBackup; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import java.util.logging.Logger; +import lombok.Cleanup; +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + + +public class Backup implements Runnable, IBackup +{ + private static final Logger LOGGER = Bukkit.getLogger(); + private transient final Server server; + private transient final IEssentials ess; + private transient final AtomicBoolean running = new AtomicBoolean(false); + private transient int taskId = -1; + private transient final AtomicBoolean active = new AtomicBoolean(false); + + public Backup(final IEssentials ess) + { + this.ess = ess; + server = ess.getServer(); + if (server.getOnlinePlayers().length > 0) + { + startTask(); + } + } + + @Override + public final void startTask() + { + if (running.compareAndSet(false, true)) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final long interval = settings.getData().getGeneral().getBackup().getInterval() * 1200; // minutes -> ticks + if (interval < 1200) + { + running.set(false); + return; + } + taskId = ess.scheduleSyncRepeatingTask(this, interval, interval); + } + } + + @Override + public void run() + { + if (!active.compareAndSet(false, true)) + { + return; + } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final String command = settings.getData().getGeneral().getBackup().getCommand(); + if (command == null || command.isEmpty()) + { + return; + } + LOGGER.log(Level.INFO, _("backupStarted")); + final CommandSender consoleSender = server.getConsoleSender(); + server.dispatchCommand(consoleSender, "save-all"); + server.dispatchCommand(consoleSender, "save-off"); + + ess.scheduleAsyncDelayedTask(new BackupRunner(command)); + } + + + private class BackupRunner implements Runnable + { + private final transient String command; + + public BackupRunner(final String command) + { + this.command = command; + } + + @Override + public void run() + { + try + { + final ProcessBuilder childBuilder = new ProcessBuilder(command); + childBuilder.redirectErrorStream(true); + childBuilder.directory(ess.getDataFolder().getParentFile().getParentFile()); + final Process child = childBuilder.start(); + final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream())); + try + { + child.waitFor(); + String line; + do + { + line = reader.readLine(); + if (line != null) + { + LOGGER.log(Level.INFO, line); + } + } + while (line != null); + } + finally + { + reader.close(); + } + } + catch (InterruptedException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + finally + { + ess.scheduleSyncDelayedTask(new EnableSavingRunner()); + } + } + } + + + private class EnableSavingRunner implements Runnable + { + @Override + public void run() + { + server.dispatchCommand(server.getConsoleSender(), "save-on"); + if (server.getOnlinePlayers().length == 0) + { + running.set(false); + if (taskId != -1) + { + server.getScheduler().cancelTask(taskId); + } + } + + active.set(false); + LOGGER.log(Level.INFO, _("backupFinished")); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/Enchantments.java b/Essentials/src/com/earth2me/essentials/bukkit/Enchantments.java index ed0051c46..f8e22ccb3 100644 --- a/Essentials/src/com/earth2me/essentials/Enchantments.java +++ b/Essentials/src/com/earth2me/essentials/bukkit/Enchantments.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.bukkit; import java.util.HashMap; import java.util.Locale; @@ -9,8 +9,13 @@ import java.util.regex.Pattern; import org.bukkit.enchantments.Enchantment; -public class Enchantments +public final class Enchantments { + + private Enchantments() + { + } + private static final transient Pattern NUMPATTERN = Pattern.compile("\\d+"); private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>(); @@ -87,7 +92,7 @@ public class Enchantments ENCHANTMENTS.put("infinity", Enchantment.ARROW_INFINITE); } - public static Enchantment getByName(String name) { + public static Enchantment getByName(final String name) { Enchantment enchantment; if (NUMPATTERN.matcher(name).matches()) { enchantment = Enchantment.getById(Integer.parseInt(name)); diff --git a/Essentials/src/com/earth2me/essentials/bukkit/EssentialsPlugin.java b/Essentials/src/com/earth2me/essentials/bukkit/EssentialsPlugin.java new file mode 100644 index 000000000..f58f2e5b6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/bukkit/EssentialsPlugin.java @@ -0,0 +1,7 @@ +package com.earth2me.essentials.bukkit; + +import org.bukkit.plugin.java.JavaPlugin; + +public class EssentialsPlugin extends JavaPlugin { + //TODO +} diff --git a/Essentials/src/com/earth2me/essentials/Mob.java b/Essentials/src/com/earth2me/essentials/bukkit/Mob.java index 38c11a81a..3d78b2a82 100644 --- a/Essentials/src/com/earth2me/essentials/Mob.java +++ b/Essentials/src/com/earth2me/essentials/bukkit/Mob.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.bukkit; import static com.earth2me.essentials.I18n._; import java.util.Collections; diff --git a/Essentials/src/com/earth2me/essentials/bukkit/Server.java b/Essentials/src/com/earth2me/essentials/bukkit/Server.java new file mode 100644 index 000000000..1c10d9a7b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/bukkit/Server.java @@ -0,0 +1,9 @@ +package com.earth2me.essentials.bukkit; + +import com.earth2me.essentials.api.server.IServer; +import lombok.Delegate; + +public class Server implements IServer { + @Delegate + private org.bukkit.Server server; +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java index c71883571..a571ec652 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java @@ -1,23 +1,20 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import org.bukkit.entity.Player; +import org.bukkit.permissions.PermissionDefault; public class Commandafk extends EssentialsCommand { - public Commandafk() - { - super("afk"); - } - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (args.length > 0 && user.isAuthorized("essentials.afk.others")) + if (args.length > 0 && Permissions.AFK_OTHERS.isAuthorized(user)) { - User afkUser = ess.getUser(ess.getServer().matchPlayer(args[0])); + IUser afkUser = ess.getUser((Player)ess.getServer().matchPlayer(args[0])); if (afkUser != null) { toggleAfk(afkUser); @@ -29,7 +26,7 @@ public class Commandafk extends EssentialsCommand } } - private void toggleAfk(User user) + private void toggleAfk(IUser user) { user.setDisplayNick(); if (!user.toggleAfk()) @@ -50,4 +47,10 @@ public class Commandafk extends EssentialsCommand } } } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java index 968d0012c..eea30448d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java @@ -1,21 +1,15 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.utils.LocationUtil; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.entity.TNTPrimed; public class Commandantioch extends EssentialsCommand { - public Commandantioch() - { - super("antioch"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0) { @@ -23,7 +17,7 @@ public class Commandantioch extends EssentialsCommand ess.broadcastMessage(user, "who being naughty in My sight, shall snuff it."); } - final Location loc = Util.getTarget(user); + final Location loc = LocationUtil.getTarget(user); loc.getWorld().spawn(loc, TNTPrimed.class); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandback.java b/Essentials/src/com/earth2me/essentials/commands/Commandback.java index d2ed98e69..e2c1b266a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandback.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandback.java @@ -1,20 +1,14 @@ 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 com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; public class Commandback extends EssentialsCommand { - public Commandback() - { - super("back"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (user.getWorld() != user.getLastLocation().getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.world." + user.getLastLocation().getWorld().getName())) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java index 38644c680..c00a0d435 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java @@ -1,20 +1,14 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.Backup; import static com.earth2me.essentials.I18n._; -import org.bukkit.Server; +import com.earth2me.essentials.api.IBackup; import org.bukkit.command.CommandSender; public class Commandbackup extends EssentialsCommand { - public Commandbackup() - { - super("backup"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { final Backup backup = ess.getBackup(); if (backup == null) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java index 15c3c9088..4e8b8f8af 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java @@ -1,21 +1,16 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import org.bukkit.command.CommandSender; public class Commandbalance extends EssentialsCommand { - public Commandbalance() - { - super("balance"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -25,11 +20,10 @@ public class Commandbalance extends EssentialsCommand } @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { final double bal = (args.length < 1 - || !(user.isAuthorized("essentials.balance.others") - || user.isAuthorized("essentials.balance.other")) + || !Permissions.BALANCE_OTHERS.isAuthorized(user) ? user : getPlayer(server, args, 0, true)).getMoney(); user.sendMessage(_("balance", Util.displayCurrency(bal, ess))); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java index 6c5e96b9f..1508a134f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java @@ -1,24 +1,19 @@ 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 com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.utils.textreader.ArrayListInput; +import com.earth2me.essentials.utils.textreader.TextPager; import java.text.DateFormat; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.locks.ReentrantReadWriteLock; -import org.bukkit.Server; import org.bukkit.command.CommandSender; public class Commandbalancetop extends EssentialsCommand { - public Commandbalancetop() - { - super("balancetop"); - } private static final int CACHETIME = 2 * 60 * 1000; public static final int MINUSERS = 50; private static ArrayListInput cache = new ArrayListInput(); @@ -26,7 +21,7 @@ public class Commandbalancetop extends EssentialsCommand private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { int page = 0; boolean force = false; @@ -110,7 +105,7 @@ public class Commandbalancetop extends EssentialsCommand double totalMoney = 0d; for (String u : ess.getUserMap().getAllUniqueUsers()) { - final User user = ess.getUserMap().getUser(u); + final IUser user = ess.getUserMap().getUser(u); if (user != null) { final double userMoney = user.getMoney(); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandban.java b/Essentials/src/com/earth2me/essentials/commands/Commandban.java index ca6707088..88c605f4e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandban.java @@ -2,31 +2,29 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; import org.bukkit.Server; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.Ban; +import lombok.Cleanup; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandban extends EssentialsCommand { - public Commandban() - { - super("ban"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(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, true); + @Cleanup + final IUser user = getPlayer(args, 0, true); if (!user.isOnline()) { - if (sender instanceof Player - && !ess.getUser(sender).isAuthorized("essentials.ban.offline")) + if (Permissions.BAN_EXEMPT.isAuthorized(user)) { sender.sendMessage(_("banExempt")); return; @@ -34,18 +32,20 @@ public class Commandban extends EssentialsCommand } else { - if (user.isAuthorized("essentials.ban.exempt")) + if (Permissions.BAN_OFFLINE.isAuthorized(sender)) { sender.sendMessage(_("banExempt")); return; } } + user.acquireWriteLock(); String banReason; + user.getData().setBan(new Ban()); if (args.length > 1) { banReason = getFinalArg(args, 1); - user.setBanReason(banReason); + user.getData().getBan().setReason(banReason); } else { @@ -59,8 +59,8 @@ public class Commandban extends EssentialsCommand for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); - if (player.isAuthorized("essentials.ban.notify")) + final IUser player = ess.getUser(onlinePlayer); + if (Permissions.BAN_NOTIFY.isAuthorized(player)) { onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason)); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java index 5459bd8fc..c9d4caa89 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java @@ -1,27 +1,24 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import lombok.Cleanup; import org.bukkit.command.CommandSender; public class Commandbanip extends EssentialsCommand { - public Commandbanip() - { - super("banip"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - final User player = ess.getUser(args[0]); + @Cleanup + final IUser player = ess.getUser(args[0]); + player.acquireReadLock(); if (player == null) { @@ -30,12 +27,12 @@ public class Commandbanip extends EssentialsCommand } else { - final String ipAddress = player.getLastLoginAddress(); + final String ipAddress = player.getData().getIpAddress(); if (ipAddress.length() == 0) { throw new Exception(_("playerNotFound")); } - ess.getServer().banIP(player.getLastLoginAddress()); + ess.getServer().banIP(player.getData().getIpAddress()); sender.sendMessage(_("banIpAddress")); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java index 5dd22503a..aa5645c85 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java @@ -1,22 +1,16 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.utils.LocationUtil; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.TreeType; public class Commandbigtree extends EssentialsCommand { - public Commandbigtree() - { - super("bigtree"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { TreeType tree; if (args.length > 0 && args[0].equalsIgnoreCase("redwood")) @@ -36,8 +30,8 @@ public class Commandbigtree extends EssentialsCommand throw new NotEnoughArgumentsException(); } - final Location loc = Util.getTarget(user); - final Location safeLocation = Util.getSafeDestination(loc); + final Location loc = LocationUtil.getTarget(user); + final Location safeLocation = LocationUtil.getSafeDestination(loc); final boolean success = user.getWorld().generateTree(safeLocation, tree); if (success) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java index 242fa9b53..6d2d7bb04 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java @@ -1,11 +1,11 @@ package com.earth2me.essentials.commands; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; import java.util.ArrayList; import java.util.List; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.ItemStack; @@ -13,14 +13,9 @@ import org.bukkit.inventory.ItemStack; public class Commandbreak extends EssentialsCommand { - public Commandbreak() - { - super("break"); - } - //TODO: Switch to use util class @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { final Block block = user.getTargetBlock(null, 20); if (block == null) @@ -31,7 +26,7 @@ public class Commandbreak extends EssentialsCommand { throw new NoChargeException(); } - if (block.getType() == Material.BEDROCK && !user.isAuthorized("essentials.break.bedrock")) + if (block.getType() == Material.BEDROCK && !Permissions.BREAK_BEDROCK.isAuthorized(user)) { throw new Exception(_("noBreakBedrock")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java index 95bb967c6..572da8f67 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java @@ -1,19 +1,13 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import org.bukkit.Server; import org.bukkit.command.CommandSender; public class Commandbroadcast extends EssentialsCommand { - public Commandbroadcast() - { - super("broadcast"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java index 5d8d38ce7..08b8739b5 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java @@ -1,20 +1,14 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandburn extends EssentialsCommand { - public Commandburn() - { - super("burn"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java index ef2502b9b..fea6c024f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java @@ -1,25 +1,20 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.List; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandclearinventory extends EssentialsCommand { - public Commandclearinventory() - { - super("clearinventory"); - } - //TODO: Cleanup @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (args.length > 0 && user.isAuthorized("essentials.clearinventory.others")) + if (args.length > 0 && Permissions.CLEARINVENTORY_OTHERS.isAuthorized(user)) { //TODO: Fix fringe user match case. if (args[0].length() >= 3) @@ -59,7 +54,7 @@ public class Commandclearinventory extends EssentialsCommand } @Override - protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java index 25f8c34f6..7314f8b6e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java @@ -1,19 +1,13 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; public class Commandcompass extends EssentialsCommand { - public Commandcompass() - { - super("compass"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { final int bearing = (int)(user.getLocation().getYaw() + 180 + 360) % 360; String dir; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java index c4d0a6946..629d00592 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java @@ -1,28 +1,26 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.Locale; -import org.bukkit.Server; +import lombok.Cleanup; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; public class Commanddelhome extends EssentialsCommand { - public Commanddelhome() - { - super("delhome"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - User user = ess.getUser(sender); + @Cleanup + IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; String name; String[] expandedArg; @@ -37,9 +35,9 @@ public class Commanddelhome extends EssentialsCommand expandedArg = args; } - if (expandedArg.length > 1 && (user == null || user.isAuthorized("essentials.delhome.others"))) + if (expandedArg.length > 1 && (user == null || Permissions.DELHOME_OTHERS.isAuthorized(user))) { - user = getPlayer(server, expandedArg, 0, true); + user = getPlayer(expandedArg, 0, true); name = expandedArg[1]; } else if (user == null) @@ -54,7 +52,8 @@ public class Commanddelhome extends EssentialsCommand /* * if (name.equalsIgnoreCase("bed")) { throw new Exception("You cannot remove the vanilla home point"); } */ - user.delHome(name.toLowerCase(Locale.ENGLISH)); + user.acquireWriteLock(); + user.getData().removeHome(name.toLowerCase(Locale.ENGLISH)); sender.sendMessage(_("deleteHome", name)); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java index 5c2c957e4..9daae2fad 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java @@ -1,19 +1,13 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import org.bukkit.Server; import org.bukkit.command.CommandSender; public class Commanddeljail extends EssentialsCommand { - public Commanddeljail() - { - super("deljail"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java index 5eab72b33..482652b15 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java @@ -1,25 +1,19 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import org.bukkit.Server; import org.bukkit.command.CommandSender; public class Commanddelwarp extends EssentialsCommand { - public Commanddelwarp() - { - super("delwarp"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - ess.getWarps().delWarp(args[0]); + ess.getWarps().removeWarp(args[0]); sender.sendMessage(_("deleteWarp", args[0])); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java index 6c4fa2647..73d3c7150 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java @@ -1,19 +1,13 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; public class Commanddepth extends EssentialsCommand { - public Commanddepth() - { - super("depth"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { final int depth = user.getLocation().getBlockY() - 63; if (depth > 0) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java index dd6d6ad0d..3269d2114 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java @@ -1,22 +1,18 @@ package com.earth2me.essentials.commands; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; import java.util.Locale; -import org.bukkit.Server; +import lombok.Cleanup; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandeco extends EssentialsCommand { - public Commandeco() - { - super("eco"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { @@ -38,7 +34,7 @@ public class Commandeco extends EssentialsCommand { for (String sUser : ess.getUserMap().getAllUniqueUsers()) { - final User player = ess.getUser(sUser); + final IUser player = ess.getUser(sUser); switch (cmd) { case GIVE: @@ -53,7 +49,10 @@ public class Commandeco extends EssentialsCommand break; case RESET: - player.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount); + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); break; } } @@ -62,7 +61,7 @@ public class Commandeco extends EssentialsCommand { for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); + final IUser player = ess.getUser(onlinePlayer); switch (cmd) { case GIVE: @@ -78,14 +77,17 @@ public class Commandeco extends EssentialsCommand break; case RESET: - player.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount); + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); break; } } } else { - final User player = getPlayer(server, args, 1, true); + final IUser player = getPlayer(args, 1, true); switch (cmd) { case GIVE: @@ -101,7 +103,9 @@ public class Commandeco extends EssentialsCommand break; case RESET: - player.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount); + @Cleanup ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); break; } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java index 51a909d29..114f51a4d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java @@ -1,25 +1,23 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.Enchantments; +import com.earth2me.essentials.bukkit.Enchantments; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import java.util.*; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.EnchantPermissions; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; public class Commandenchant extends EssentialsCommand { - 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 + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { final ItemStack stack = user.getItemInHand(); if (stack == null) @@ -32,7 +30,7 @@ public class Commandenchant extends EssentialsCommand 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)) + if (enchantmentslist.contains(enchantmentName) || EnchantPermissions.getPermission(enchantmentName).isAuthorized(user)) { enchantmentslist.add(entry.getKey()); //enchantmentslist.add(enchantmentName); @@ -78,7 +76,7 @@ public class Commandenchant extends EssentialsCommand } } - public static Enchantment getEnchantment(final String name, final User user) throws Exception + public static Enchantment getEnchantment(final String name, final IUser user) throws Exception { final Enchantment enchantment = Enchantments.getByName(name); @@ -87,7 +85,7 @@ public class Commandenchant extends EssentialsCommand throw new Exception(_("enchantmentNotFound")); } final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); - if (user != null && !user.isAuthorized("essentials.enchant." + enchantmentName)) + if (user != null && !EnchantPermissions.getPermission(enchantmentName).isAuthorized(user)) { throw new Exception(_("enchantmentPerm", enchantmentName)); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java index ca746c5a8..e2668e562 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java @@ -1,7 +1,6 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Util; import com.earth2me.essentials.metrics.Metrics; import java.io.IOException; import java.util.HashMap; @@ -10,7 +9,6 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; @@ -19,26 +17,23 @@ import org.bukkit.entity.Player; public class Commandessentials extends EssentialsCommand { - public Commandessentials() - { - super("essentials"); - } private transient int taskid; private final transient Map<Player, Block> noteBlocks = new HashMap<Player, Block>(); @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { - if (args.length == 0) { - run_disabled(server, sender, commandLabel, args); + if (args.length == 0) + { + run_disabled(sender, args); } else if (args[0].equalsIgnoreCase("debug")) { - run_debug(server, sender, commandLabel, args); + run_debug(sender, args); } else if (args[0].equalsIgnoreCase("nya")) { - run_nya(server, sender, commandLabel, args); + run_nya(sender, args); } else if (args[0].equalsIgnoreCase("moo")) { @@ -51,37 +46,42 @@ public class Commandessentials extends EssentialsCommand else { run_reload(server, sender, commandLabel, args); } + else + { + run_reload(sender, args); + } } - - private void run_disabled(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + + private void run_disabled(final CommandSender sender, final String[] args) throws Exception { sender.sendMessage("Essentials " + ess.getDescription().getVersion()); sender.sendMessage("/<command> <reload/debug>"); sender.sendMessage(_("blockList")); final StringBuilder disabledCommands = new StringBuilder(); - for (Map.Entry<String, String> entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet()) + for (Map.Entry<String, String> entry : ess.getCommandHandler().disabledCommands().entrySet()) { - if (disabledCommands.length() > 0) { + if (disabledCommands.length() > 0) + { disabledCommands.append(", "); } disabledCommands.append(entry.getKey()).append(" => ").append(entry.getValue()); } sender.sendMessage(disabledCommands.toString()); } - - private void run_debug(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + + private void run_debug(final CommandSender sender, final String[] args) throws Exception { ess.getSettings().setDebug(!ess.getSettings().isDebug()); sender.sendMessage("Essentials " + ess.getDescription().getVersion() + " debug mode " + (ess.getSettings().isDebug() ? "enabled" : "disabled")); } - - private void run_reload(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + + private void run_reload(final CommandSender sender, final String[] args) throws Exception { ess.reload(); sender.sendMessage(_("essentialsReload", ess.getDescription().getVersion())); } - - private void run_nya(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + + private void run_nya(final CommandSender sender, final String[] args) throws Exception { final Map<String, Byte> noteMap = new HashMap<String, Byte>(); noteMap.put("1F#", (byte)0x0); @@ -108,60 +108,60 @@ public class Commandessentials extends EssentialsCommand noteMap.put("2D#", (byte)(0x9 + 0xC)); noteMap.put("2E", (byte)(0xA + 0xC)); noteMap.put("2F", (byte)(0xB + 0xC)); - if (!noteBlocks.isEmpty()) + if (!noteBlocks.isEmpty()) + { + return; + } + final String tuneStr = "1D#,1E,2F#,,2A#,1E,1D#,1E,2F#,2B,2D#,2E,2D#,2A#,2B,,2F#,,1D#,1E,2F#,2B,2C#,2A#,2B,2C#,2E,2D#,2E,2C#,,2F#,,2G#,,1D,1D#,,1C#,1D,1C#,1B,,1B,,1C#,,1D,,1D,1C#,1B,1C#,1D#,2F#,2G#,1D#,2F#,1C#,1D#,1B,1C#,1B,1D#,,2F#,,2G#,1D#,2F#,1C#,1D#,1B,1D,1D#,1D,1C#,1B,1C#,1D,,1B,1C#,1D#,2F#,1C#,1D,1C#,1B,1C#,,1B,,1C#,,2F#,,2G#,,1D,1D#,,1C#,1D,1C#,1B,,1B,,1C#,,1D,,1D,1C#,1B,1C#,1D#,2F#,2G#,1D#,2F#,1C#,1D#,1B,1C#,1B,1D#,,2F#,,2G#,1D#,2F#,1C#,1D#,1B,1D,1D#,1D,1C#,1B,1C#,1D,,1B,1C#,1D#,2F#,1C#,1D,1C#,1B,1C#,,1B,,1B,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1B,,"; + final String[] tune = tuneStr.split(","); + for (Player player : server.getOnlinePlayers()) + { + final Location loc = player.getLocation(); + loc.add(0, 3, 0); + while (loc.getBlockY() < player.getLocation().getBlockY() + 10 && loc.getBlock().getTypeId() != 0) + { + loc.add(0, 1, 0); + } + if (loc.getBlock().getTypeId() == 0) { - return; + noteBlocks.put(player, loc.getBlock()); + player.sendBlockChange(loc, Material.NOTE_BLOCK, (byte)0); } - final String tuneStr = "1D#,1E,2F#,,2A#,1E,1D#,1E,2F#,2B,2D#,2E,2D#,2A#,2B,,2F#,,1D#,1E,2F#,2B,2C#,2A#,2B,2C#,2E,2D#,2E,2C#,,2F#,,2G#,,1D,1D#,,1C#,1D,1C#,1B,,1B,,1C#,,1D,,1D,1C#,1B,1C#,1D#,2F#,2G#,1D#,2F#,1C#,1D#,1B,1C#,1B,1D#,,2F#,,2G#,1D#,2F#,1C#,1D#,1B,1D,1D#,1D,1C#,1B,1C#,1D,,1B,1C#,1D#,2F#,1C#,1D,1C#,1B,1C#,,1B,,1C#,,2F#,,2G#,,1D,1D#,,1C#,1D,1C#,1B,,1B,,1C#,,1D,,1D,1C#,1B,1C#,1D#,2F#,2G#,1D#,2F#,1C#,1D#,1B,1C#,1B,1D#,,2F#,,2G#,1D#,2F#,1C#,1D#,1B,1D,1D#,1D,1C#,1B,1C#,1D,,1B,1C#,1D#,2F#,1C#,1D,1C#,1B,1C#,,1B,,1B,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1B,,"; - final String[] tune = tuneStr.split(","); - for (Player player : server.getOnlinePlayers()) + } + taskid = ess.scheduleSyncRepeatingTask(new Runnable() + { + int i = 0; + + @Override + public void run() { - final Location loc = player.getLocation(); - loc.add(0, 3, 0); - while (loc.getBlockY() < player.getLocation().getBlockY() + 10 && loc.getBlock().getTypeId() != 0) + final String note = tune[i]; + i++; + if (i >= tune.length) { - loc.add(0, 1, 0); + Commandessentials.this.stopTune(); } - if (loc.getBlock().getTypeId() == 0) + if (note.isEmpty()) { - noteBlocks.put(player, loc.getBlock()); - loc.getBlock().setType(Material.NOTE_BLOCK); + return; } - } - taskid = ess.scheduleSyncRepeatingTask(new Runnable() - { - int i = 0; - - @Override - public void run() + Map<Player, Block> noteBlocks = Commandessentials.this.noteBlocks; + for (Player onlinePlayer : server.getOnlinePlayers()) { - final String note = tune[i]; - i++; - if (i >= tune.length) - { - Commandessentials.this.stopTune(); - } - if (note.isEmpty()) + final Block block = noteBlocks.get(onlinePlayer); + if (block == null || block.getType() != Material.NOTE_BLOCK) { - return; - } - Map<Player, Block> noteBlocks = Commandessentials.this.noteBlocks; - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final Block block = noteBlocks.get(onlinePlayer); - if (block == null || block.getType() != Material.NOTE_BLOCK) - { - continue; - } - onlinePlayer.playNote(block.getLocation(), (byte)0, noteMap.get(note)); + continue; } + onlinePlayer.playNote(block.getLocation(), (byte)0, noteMap.get(note)); } - }, 20, 2); + } + }, 20, 2); } private void stopTune() { - ess.getScheduler().cancelTask(taskid); + ess.getServer().getScheduler().cancelTask(taskid); for (Block block : noteBlocks.values()) { if (block.getType() == Material.NOTE_BLOCK) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandext.java b/Essentials/src/com/earth2me/essentials/commands/Commandext.java index 3855e7b68..8e689506a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandext.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandext.java @@ -1,32 +1,26 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandext extends EssentialsCommand { - public Commandext() - { - super("ext"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - extinguishPlayers(server, sender, args[0]); + extinguishPlayers(sender, args[0]); } @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -35,10 +29,10 @@ public class Commandext extends EssentialsCommand return; } - extinguishPlayers(server, user, commandLabel); + extinguishPlayers(user, args[0]); } - private void extinguishPlayers(final Server server, final CommandSender sender, final String name) throws Exception + private void extinguishPlayers(final CommandSender sender, final String name) throws Exception { for (Player matchPlayer : server.matchPlayer(name)) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java b/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java index 0c1579835..e7c8f9fe4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java @@ -1,26 +1,21 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; 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 + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (args.length > 0 && user.isAuthorized("essentials.feed.others")) + if (args.length > 0 && Permissions.FEED_OTHERS.isAuthorized(user)) { - feedOtherPlayers(server,user,args[0]); + feedOtherPlayers(user, args[0]); } else { @@ -29,8 +24,8 @@ public class Commandfeed extends EssentialsCommand user.sendMessage(_("feed")); } } - - private void feedOtherPlayers(final Server server, final CommandSender sender, final String name) + + private void feedOtherPlayers(final CommandSender sender, final String name) { final List<Player> players = server.matchPlayer(name); if (players.isEmpty()) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java b/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java index 671d0f72b..f13f3ee75 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java @@ -1,7 +1,6 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; import org.bukkit.entity.Fireball; import org.bukkit.entity.SmallFireball; import org.bukkit.util.Vector; @@ -9,13 +8,8 @@ import org.bukkit.util.Vector; public class Commandfireball extends EssentialsCommand { - public Commandfireball() - { - super("fireball"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { boolean small = false; if (args.length > 0 && args[0].equalsIgnoreCase("small")) @@ -23,7 +17,7 @@ public class Commandfireball extends EssentialsCommand small = true; } final Vector direction = user.getEyeLocation().getDirection().multiply(2); - Fireball fireball = user.getWorld().spawn(user.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), small ? SmallFireball.class : Fireball.class); + final Fireball fireball = user.getWorld().spawn(user.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), small ? SmallFireball.class : Fireball.class); fireball.setShooter(user.getBase()); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java b/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java index 5fdc69d68..72153265e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java @@ -1,38 +1,33 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.Locale; import org.bukkit.GameMode; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandgamemode extends EssentialsCommand { - public Commandgamemode() - { - super("gamemode"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - gamemodeOtherPlayers(server, sender, args); + gamemodeOtherPlayers(sender, args[0]); } @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (args.length > 0 && args[0].trim().length() > 2 && user.isAuthorized("essentials.gamemode.others")) + if (args.length > 0 && !args[0].trim().isEmpty() && Permissions.GAMEMODE_OTHERS.isAuthorized(user)) { - gamemodeOtherPlayers(server, user, args); + gamemodeOtherPlayers(user, args[0]); return; } @@ -40,11 +35,11 @@ public class Commandgamemode extends EssentialsCommand user.sendMessage(_("gameMode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName())); } - private void gamemodeOtherPlayers(final Server server, final CommandSender sender, final String[] args) + private void gamemodeOtherPlayers(final CommandSender sender, final String name) { for (Player matchPlayer : server.matchPlayer(args[0])) { - final User player = ess.getUser(matchPlayer); + final IUser player = ess.getUser(matchPlayer); if (player.isHidden()) { continue; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java index d9b08b50f..4097c5e83 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java @@ -9,13 +9,8 @@ import org.bukkit.command.CommandSender; public class Commandgc extends EssentialsCommand { - public Commandgc() - { - super("gc"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { float tps = ess.getTimer().getAverageTPS(); ChatColor color; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java index c985ef725..dfccdd31c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java @@ -1,24 +1,19 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.command.CommandSender; public class Commandgetpos extends EssentialsCommand { - public Commandgetpos() - { - super("getpos"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (args.length > 0 && user.isAuthorized("essentials.getpos.others")) + if (args.length > 0 && Permissions.GETPOS_OTHERS.isAuthorized(user)) { - final User otherUser = getPlayer(server, args, 0); + final IUser otherUser = getPlayer(args, 0); if (!otherUser.isHidden() || user.isAuthorized("essentials.list.hidden")) { outputPosition(user, otherUser.getLocation(), user.getLocation()); @@ -30,13 +25,13 @@ public class Commandgetpos extends EssentialsCommand } @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(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); + final IUser user = getPlayer(args, 0); outputPosition(sender, user.getLocation(), null); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java index 21903e98b..aea29cbf3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java @@ -1,13 +1,12 @@ package com.earth2me.essentials.commands; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.GivePermissions; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import com.earth2me.essentials.User; import com.earth2me.essentials.Util; import java.util.Locale; import org.bukkit.ChatColor; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; @@ -16,35 +15,24 @@ import org.bukkit.inventory.ItemStack; public class Commandgive extends EssentialsCommand { - public Commandgive() - { - super("give"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } + + final IUser giveTo = getPlayer(args, 0); - final ItemStack stack = ess.getItemDb().get(args[1]); + final ItemStack stack = ess.getItemDb().get(args[1], giveTo); final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (sender instanceof Player - && (ess.getSettings().permissionBasedItemSpawn() - ? (!ess.getUser(sender).isAuthorized("essentials.give.item-all") - && !ess.getUser(sender).isAuthorized("essentials.give.item-" + itemname) - && !ess.getUser(sender).isAuthorized("essentials.give.item-" + stack.getTypeId())) - : (!ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt") - && !ess.getUser(sender).canSpawnItem(stack.getTypeId())))) + if (!GivePermissions.getPermission(stack.getType()).isAuthorized(sender)) { throw new Exception(_("cantSpawnItem", itemname)); } - final User giveTo = getPlayer(server, args, 0); - if (args.length > 3 && Util.isInt(args[2]) && Util.isInt(args[3])) { stack.setAmount(Integer.parseInt(args[2])); @@ -53,15 +41,7 @@ public class Commandgive extends EssentialsCommand else 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) { @@ -72,7 +52,7 @@ public class Commandgive extends EssentialsCommand { continue; } - final Enchantment enchantment = Commandenchant.getEnchantment(split[0], sender instanceof Player ? ess.getUser(sender) : null); + final Enchantment enchantment = Commandenchant.getEnchantment(split[0], sender instanceof Player ? ess.getUser((Player)sender) : null); int level; if (split.length > 1) { @@ -90,18 +70,12 @@ public class Commandgive extends EssentialsCommand { throw new Exception(_("cantSpawnItem", "Air")); } + + giveTo.giveItems(stack, false); //TODO: TL this. 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")) - { - InventoryWorkaround.addItem(giveTo.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack); - } - else - { - InventoryWorkaround.addItem(giveTo.getInventory(), true, stack); - } - giveTo.updateInventory(); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java index 6e611d869..037c8cb50 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java @@ -1,47 +1,42 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandgod extends EssentialsCommand { - public Commandgod() - { - super("god"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - godOtherPlayers(server, sender, args[0]); + godOtherPlayers(sender, args[0]); } @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (args.length > 0 && args[0].trim().length() > 2 && user.isAuthorized("essentials.god.others")) + if (args.length > 0 && !args[0].trim().isEmpty() && Permissions.GOD_OTHERS.isAuthorized(user)) { - godOtherPlayers(server, user, args[0]); + godOtherPlayers(user, args[0]); return; } user.sendMessage(_("godMode", (user.toggleGodModeEnabled() ? _("enabled") : _("disabled")))); } - private void godOtherPlayers(final Server server, final CommandSender sender, final String name) + private void godOtherPlayers(final CommandSender sender, final String name) { for (Player matchPlayer : server.matchPlayer(name)) { - final User player = ess.getUser(matchPlayer); + final IUser player = ess.getUser(matchPlayer); if (player.isHidden()) { continue; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java index 82678c96e..fe620b390 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java @@ -1,55 +1,47 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.UserData.TimestampType; import java.util.List; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandheal extends EssentialsCommand { - public Commandheal() - { - super("heal"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (args.length > 0 && user.isAuthorized("essentials.heal.others")) + if (args.length > 0 && Permissions.HEAL_OTHERS.isAuthorized(user)) { - if (!user.isAuthorized("essentials.heal.cooldown.bypass")) - { - user.healCooldown(); - } - healOtherPlayers(server, user, args[0]); + user.checkCooldown(TimestampType.LASTHEAL, ess.getRanks().getHealCooldown(user), true, Permissions.HEAL_COOLDOWN_BYPASS); + + healOtherPlayers(user, args[0]); return; } - if (!user.isAuthorized("essentials.heal.cooldown.bypass")) - { - user.healCooldown(); - } + user.checkCooldown(TimestampType.LASTHEAL, ess.getRanks().getHealCooldown(user), true, Permissions.HEAL_COOLDOWN_BYPASS); + user.setHealth(20); user.setFoodLevel(20); user.sendMessage(_("heal")); } @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - healOtherPlayers(server, sender, args[0]); + healOtherPlayers(sender, args[0]); } - private void healOtherPlayers(final Server server, final CommandSender sender, final String name) + private void healOtherPlayers(final CommandSender sender, final String name) { final List<Player> players = server.matchPlayer(name); if (players.isEmpty()) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java index 6339359f1..e6fb2e2eb 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java @@ -1,8 +1,13 @@ package com.earth2me.essentials.commands; +import com.earth2me.essentials.utils.textreader.TextInput; +import com.earth2me.essentials.utils.textreader.IText; +import com.earth2me.essentials.utils.textreader.TextPager; +import com.earth2me.essentials.utils.textreader.HelpInput; +import com.earth2me.essentials.utils.textreader.KeywordReplacer; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.textreader.*; import java.util.Locale; import org.bukkit.Server; @@ -11,13 +16,8 @@ import org.bukkit.command.CommandSender; public class Commandhelp extends EssentialsCommand { - public Commandhelp() - { - super("help"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { IText output; String pageStr = args.length > 0 ? args[0] : null; @@ -52,7 +52,7 @@ public class Commandhelp extends EssentialsCommand } @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { sender.sendMessage(_("helpConsole")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java index 948cfa769..42a69b4b1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java @@ -1,22 +1,17 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.logging.Level; -import org.bukkit.Server; import org.bukkit.entity.Player; public class Commandhelpop extends EssentialsCommand { - public Commandhelpop() - { - super("helpop"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -27,8 +22,8 @@ public class Commandhelpop extends EssentialsCommand logger.log(Level.INFO, message); for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); - if (!player.isAuthorized("essentials.helpop.receive")) + final IUser player = ess.getUser(onlinePlayer); + if (!Permissions.HELPOP_RECEIVE.isAuthorized(player)) { continue; } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java index 2c91a06c9..27e93d39e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java @@ -1,42 +1,37 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.List; import java.util.Locale; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandhome extends EssentialsCommand { - public Commandhome() - { - super("home"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); charge.isAffordableFor(user); - User player = user; + IUser player = user; String homeName = ""; String[] nameParts; if (args.length > 0) { nameParts = args[0].split(":"); - if (nameParts[0].length() == args[0].length() || !user.isAuthorized("essentials.home.others")) + if (nameParts[0].length() == args[0].length() || !Permissions.HOME_OTHERS.isAuthorized(user)) { homeName = nameParts[0]; } else { - player = getPlayer(server, nameParts, 0, true); + player = getPlayer(nameParts, 0, true); if (nameParts.length > 1) { homeName = nameParts[1]; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandignore.java b/Essentials/src/com/earth2me/essentials/commands/Commandignore.java index 93dd029a8..9b3ff71cc 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandignore.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandignore.java @@ -1,39 +1,34 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; public class Commandignore extends EssentialsCommand { - public Commandignore() - { - super("ignore"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - User player; + IUser player; try { - player = getPlayer(server, args, 0); + player = getPlayer(args, 0); } catch (NoSuchFieldException ex) { - player = ess.getOfflineUser(args[0]); + player = ess.getUser(args[0]); } if (player == null) { throw new Exception(_("playerNotFound")); } final String name = player.getName(); - if (user.isIgnoredPlayer(name)) + user.acquireWriteLock(); + if (user.isIgnoringPlayer(name)) { user.setIgnoredPlayer(name, false); user.sendMessage(_("unignorePlayer", player.getName())); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java b/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java index afe1add72..924e0a74a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java @@ -1,22 +1,16 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.textreader.IText; -import com.earth2me.essentials.textreader.KeywordReplacer; -import com.earth2me.essentials.textreader.TextInput; -import com.earth2me.essentials.textreader.TextPager; -import org.bukkit.Server; +import com.earth2me.essentials.utils.textreader.IText; +import com.earth2me.essentials.utils.textreader.KeywordReplacer; +import com.earth2me.essentials.utils.textreader.TextInput; +import com.earth2me.essentials.utils.textreader.TextPager; import org.bukkit.command.CommandSender; public class Commandinfo extends EssentialsCommand { - public Commandinfo() - { - super("info"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { final IText input = new TextInput(sender, "info", true, ess); final IText output = new KeywordReplacer(input, sender, ess); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java index a4a659e97..fd6a6a167 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java @@ -1,21 +1,16 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.user.Inventory; import java.util.Arrays; -import org.bukkit.Server; import org.bukkit.inventory.ItemStack; public class Commandinvsee extends EssentialsCommand { - public Commandinvsee() - { - super("invsee"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java index 0e35dda71..1ea96ff60 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java @@ -1,44 +1,38 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.ItemPermissions; import java.util.Locale; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; public class Commanditem extends EssentialsCommand { - public Commanditem() - { - super("item"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - final ItemStack stack = ess.getItemDb().get(args[0]); + final ItemStack stack = ess.getItemDb().get(args[0], user); 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()))) + if (!ItemPermissions.getPermission(stack.getType()).isAuthorized(user)) { throw new Exception(_("cantSpawnItem", itemname)); } try { - if (args.length > 1 && Integer.parseInt(args[1]) > 0) + stack.setAmount(Integer.parseInt(args[1])); + } + + if (args.length > 2) + { + for (int i = 2; i < args.length; i++) { stack.setAmount(Integer.parseInt(args[1])); } @@ -83,16 +77,9 @@ public class Commanditem extends EssentialsCommand throw new Exception(_("cantSpawnItem", "Air")); } + user.giveItems(stack, false); + final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); - user.sendMessage(_("itemSpawn", stack.getAmount(), displayName)); - if (user.isAuthorized("essentials.oversizedstacks")) - { - InventoryWorkaround.addItem(user.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack); - } - else - { - InventoryWorkaround.addItem(user.getInventory(), true, stack); - } - user.updateInventory(); + user.sendMessage(_("itemSpawn", stack.getAmount(), displayName)); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java b/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java index c35656c72..6d0a17037 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -8,13 +7,8 @@ import org.bukkit.inventory.ItemStack; public class Commanditemdb extends EssentialsCommand { - public Commanditemdb() - { - super("itemdb"); - } - @Override - protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { ItemStack itemStack = null; if (args.length < 1) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java index 051bcf710..7e50c78e2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java @@ -1,19 +1,13 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; import org.bukkit.command.CommandSender; public class Commandjails extends EssentialsCommand { - public Commandjails() - { - super("jails"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { sender.sendMessage("§7" + Util.joinList(" ", ess.getJails().getList())); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java index ab73c6e01..4d4388b84 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java @@ -1,30 +1,24 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.utils.LocationUtil; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandjump extends EssentialsCommand { - public Commandjump() - { - super("jump"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { Location loc; final Location cloc = user.getLocation(); try { - loc = Util.getTarget(user); + loc = LocationUtil.getTarget(user); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); @@ -34,7 +28,7 @@ public class Commandjump extends EssentialsCommand throw new Exception(_("jumpError"), ex); } - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); charge.isAffordableFor(user); user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); throw new NoChargeException(); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java index 3e2e08b50..fe11efcea 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java @@ -2,29 +2,24 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandkick extends EssentialsCommand { - public Commandkick() - { - super("kick"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(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); - if (sender instanceof Player && user.isAuthorized("essentials.kick.exempt")) + final IUser user = getPlayer(args, 0); + if (Permissions.KICK_EXEMPT.isAuthorized(user)) { throw new Exception(_("kickExempt")); } @@ -34,8 +29,8 @@ public class Commandkick extends EssentialsCommand for (Player onlinePlayer : server.getOnlinePlayers()) { - User player = ess.getUser(onlinePlayer); - if (player.isAuthorized("essentials.kick.notify")) + final IUser player = ess.getUser(onlinePlayer); + if (Permissions.KICK_NOTIFY.isAuthorized(player)) { onlinePlayer.sendMessage(_("playerKicked", senderName, user.getName(), kickReason)); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java index 4722b7d68..bd22d30c9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java @@ -1,20 +1,14 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandkickall extends EssentialsCommand { - public Commandkickall() - { - super("kickall"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { for (Player onlinePlayer : server.getOnlinePlayers()) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java index 77994f156..81e998b34 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java @@ -1,7 +1,6 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent; @@ -9,13 +8,8 @@ import org.bukkit.event.entity.EntityDamageEvent; public class Commandkill extends EssentialsCommand { - public Commandkill() - { - super("kill"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java index d918eeffb..d8868e2c4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java @@ -1,40 +1,21 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.Mob; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.bukkit.Mob; import java.util.Collections; 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.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.Ocelot; -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.entity.*; import org.bukkit.event.entity.EntityDeathEvent; public class Commandkillall extends EssentialsCommand { - public Commandkillall() - { - super("killall"); - } - //TODO: Tidy - missed this during command cleanup @Override - public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { String type = "all"; int radius = -1; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java index a545adf60..bab73b196 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java @@ -1,25 +1,39 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.*; import static com.earth2me.essentials.I18n._; -import java.util.*; -import org.bukkit.Server; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.KitPermissions; +import com.earth2me.essentials.settings.Kit; +import java.util.Collection; +import java.util.Locale; import org.bukkit.command.CommandSender; public class Commandkit extends EssentialsCommand { - public Commandkit() - { - super("kit"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { - listKits(user); + Collection<String> kitList = ess.getKits().getList(); + if (kitList.isEmpty()) + { + user.sendMessage(_("noKits")); + } + else + { + for (String kitName : kitList) + { + if (!KitPermissions.getPermission(kitName).isAuthorized(user)) + { + kitList.remove(kitName); + } + } + user.sendMessage(_("kits", Util.joinList(kitList))); + } throw new NoChargeException(); } else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) @@ -47,11 +61,14 @@ public class Commandkit extends EssentialsCommand { final User userTo = getPlayer(server, args, 1, true); final String kitName = args[0].toLowerCase(Locale.ENGLISH); + final Kit kit = ess.getKits().getKit(kitName); - final Map<String, Object> kit = ess.getSettings().getKit(kitName); - final List<String> items = Kit.getItems(userTo, kit); - Kit.expandItems(ess, userTo, items); + if (!KitPermissions.getPermission(kitName).isAuthorized(user)) + { + throw new Exception(_("noKitPermission", "essentials.kit." + kitName)); + } + //TODO: Check kit delay sender.sendMessage(_("kitGive", kitName)); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java b/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java index 9db608235..602f324ad 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java @@ -1,10 +1,17 @@ package com.earth2me.essentials.commands; +<<<<<<< HEAD import com.earth2me.essentials.Mob; import com.earth2me.essentials.User; import java.util.Random; import org.bukkit.Location; import org.bukkit.Server; +======= +import com.earth2me.essentials.bukkit.Mob; +import com.earth2me.essentials.api.IUser; +import java.util.Random; +import org.bukkit.Location; +>>>>>>> 3.0 import org.bukkit.entity.Ocelot; @@ -12,6 +19,7 @@ public class Commandkittycannon extends EssentialsCommand { private static Random random = new Random(); +<<<<<<< HEAD public Commandkittycannon() { super("kittycannon"); @@ -19,6 +27,10 @@ public class Commandkittycannon extends EssentialsCommand @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception +======= + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception +>>>>>>> 3.0 { final Mob cat = Mob.OCELOT; final Ocelot ocelot = (Ocelot)cat.spawn(user, server, user.getEyeLocation()); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java index 810ef0b33..3eda786c9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java @@ -1,8 +1,10 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import lombok.Cleanup; import org.bukkit.command.CommandSender; import org.bukkit.entity.LightningStrike; import org.bukkit.entity.Player; @@ -10,21 +12,16 @@ import org.bukkit.entity.Player; public class Commandlightning extends EssentialsCommand { - public Commandlightning() - { - super("lightning"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { - User user = null; + IUser user = null; if (sender instanceof Player) { user = ess.getUser(((Player)sender)); } - if ((args.length < 1 || !user.isAuthorized("essentials.lightning.others")) & user != null) + if ((args.length < 1 || !Permissions.LIGHTNING_OTHERS.isAuthorized(user)) && user != null) { user.getWorld().strikeLightning(user.getTargetBlock(null, 600).getLocation()); return; @@ -63,7 +60,10 @@ public class Commandlightning extends EssentialsCommand { matchPlayer.setHealth(matchPlayer.getHealth() < 5 ? 0 : matchPlayer.getHealth() - 5); } - if (ess.getSettings().warnOnSmite()) + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (settings.getData().getCommands().getLightning().isWarnPlayer()) { matchPlayer.sendMessage(_("lightningSmited")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java index c981f45c1..0a433ad7e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java @@ -1,33 +1,23 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import com.earth2me.essentials.Util; import java.util.*; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandlist extends EssentialsCommand { - public Commandlist() - { - super("list"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { boolean showhidden = false; - if (sender instanceof Player) - { - if (ess.getUser(sender).isAuthorized("essentials.list.hidden")) - { - showhidden = true; - } - } - else + if (Permissions.LIST_HIDDEN.isAuthorized(sender)) { showhidden = true; } @@ -51,21 +41,33 @@ public class Commandlist extends EssentialsCommand } sender.sendMessage(online); - if (ess.getSettings().getSortListByGroups()) + boolean sortListByGroups = false; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + sortListByGroups = settings.getData().getCommands().getList().isSortByGroups(); + } + finally { - Map<String, List<User>> sort = new HashMap<String, List<User>>(); + settings.unlock(); + } + + if (sortListByGroups) + { + Map<String, List<IUser>> sort = new HashMap<String, List<IUser>>(); for (Player OnlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(OnlinePlayer); + final IUser player = ess.getUser(OnlinePlayer); if (player.isHidden() && !showhidden) { continue; } - final String group = player.getGroup(); - List<User> list = sort.get(group); + final String group = ess.getRanks().getMainGroup(player); + List<IUser> list = sort.get(group); if (list == null) { - list = new ArrayList<User>(); + list = new ArrayList<IUser>(); sort.put(group, list); } list.add(player); @@ -75,11 +77,11 @@ public class Commandlist extends EssentialsCommand for (String group : groups) { final StringBuilder groupString = new StringBuilder(); - groupString.append(_("listGroupTag", Util.replaceFormat(group))); - final List<User> users = sort.get(group); + groupString.append(_("listGroupTag",Util.replaceColor(group))); + final List<IUser> users = sort.get(group); Collections.sort(users); boolean first = true; - for (User user : users) + for (IUser user : users) { if (!first) { @@ -89,9 +91,17 @@ public class Commandlist extends EssentialsCommand { first = false; } - if (user.isAfk()) + user.acquireReadLock(); + try + { + if (user.getData().isAfk()) + { + groupString.append(_("listAfkTag")); + } + } + finally { - groupString.append(_("listAfkTag")); + user.unlock(); } if (user.isHidden()) { @@ -106,10 +116,10 @@ public class Commandlist extends EssentialsCommand } else { - final List<User> users = new ArrayList<User>(); + final List<IUser> users = new ArrayList<IUser>(); for (Player OnlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(OnlinePlayer); + final IUser player = ess.getUser(OnlinePlayer); if (player.isHidden() && !showhidden) { continue; @@ -121,7 +131,7 @@ public class Commandlist extends EssentialsCommand final StringBuilder onlineUsers = new StringBuilder(); onlineUsers.append(_("connectedPlayers")); boolean first = true; - for (User user : users) + for (IUser user : users) { if (!first) { @@ -131,9 +141,17 @@ public class Commandlist extends EssentialsCommand { first = false; } - if (user.isAfk()) + user.acquireReadLock(); + try + { + if (user.getData().isAfk()) + { + onlineUsers.append(_("listAfkTag")); + } + } + finally { - onlineUsers.append(_("listAfkTag")); + user.unlock(); } if (user.isHidden()) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java index 7a2dad1b1..db39d1c01 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java @@ -1,8 +1,9 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.List; import org.bukkit.Server; import org.bukkit.command.CommandSender; @@ -11,19 +12,14 @@ import org.bukkit.entity.Player; public class Commandmail extends EssentialsCommand { - public Commandmail() - { - super("mail"); - } - //TODO: Tidy this up @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { - final List<String> mail = user.getMails(); - if (mail.isEmpty()) + final List<String> mail = user.getData().getMails(); + if (mail == null || mail.isEmpty()) { user.sendMessage(_("noMail")); throw new NoChargeException(); @@ -37,26 +33,26 @@ public class Commandmail extends EssentialsCommand } if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { - if (!user.isAuthorized("essentials.mail.send")) + if (!Permissions.MAIL_SEND.isAuthorized(user)) { throw new Exception(_("noPerm", "essentials.mail.send")); } Player player = server.getPlayer(args[1]); - User u; + IUser u; if (player != null) { u = ess.getUser(player); } else { - u = ess.getOfflineUser(args[1]); + u = ess.getUser(args[1]); } if (u == null) { throw new Exception(_("playerNeverOnServer", args[1])); } - if (!u.isIgnoredPlayer(user.getName())) + if (!u.isIgnoringPlayer(user.getName())) { final String mail = Util.sanitizeString(Util.stripFormat(getFinalArg(args, 2))); u.addMail(user.getName() + ": " + mail); @@ -66,7 +62,7 @@ public class Commandmail extends EssentialsCommand } if (args.length > 1 && "sendall".equalsIgnoreCase(args[0])) { - if (!user.isAuthorized("essentials.mail.sendall")) + if (!Permissions.MAIL_SENDALL.isAuthorized(user)) { throw new Exception(_("noPerm", "essentials.mail.sendall")); } @@ -76,7 +72,8 @@ public class Commandmail extends EssentialsCommand } if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { - user.setMails(null); + user.acquireWriteLock(); + user.getData().setMails(null); user.sendMessage(_("mailCleared")); return; } @@ -84,27 +81,27 @@ public class Commandmail extends EssentialsCommand } @Override - protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { - throw new Exception(_("onlyPlayers", commandLabel + " read")); + throw new Exception(_("onlyPlayers", commandName + " read")); } else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { - throw new Exception(_("onlyPlayers", commandLabel + " clear")); + throw new Exception(_("onlyPlayers", commandName + " clear")); } else if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { Player player = server.getPlayer(args[1]); - User u; + IUser u; if (player != null) { u = ess.getUser(player); } else { - u = ess.getOfflineUser(args[1]); + u = ess.getUser(args[1]); } if (u == null) { @@ -122,14 +119,14 @@ public class Commandmail extends EssentialsCommand { //allow sending from console without "send" argument, since it's the only thing the console can do Player player = server.getPlayer(args[0]); - User u; + IUser u; if (player != null) { u = ess.getUser(player); } else { - u = ess.getOfflineUser(args[0]); + u = ess.getUser(args[0]); } if (u == null) { @@ -157,7 +154,7 @@ public class Commandmail extends EssentialsCommand { for (String username : ess.getUserMap().getAllUniqueUsers()) { - User user = ess.getUserMap().getUser(username); + IUser user = ess.getUserMap().getUser(username); if (user != null) { user.addMail(message); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandme.java b/Essentials/src/com/earth2me/essentials/commands/Commandme.java index 4322592d4..8477c98bc 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandme.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandme.java @@ -1,22 +1,17 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; public class Commandme extends EssentialsCommand { - public Commandme() - { - super("me"); - } - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (user.isMuted()) + if (user.getData().isMuted()) { throw new Exception(_("voiceSilenced")); } @@ -27,7 +22,14 @@ public class Commandme extends EssentialsCommand } String message = getFinalArg(args, 0); - message = Util.formatMessage(user, "essentials.chat", message); + if (Permissions.CHAT_COLOR.isAuthorized(user)) + { + message = Util.replaceColor(message); + } + else { + message = Util.stripColor(message); + } + user.setDisplayNick(); ess.broadcastMessage(user, _("action", user.getDisplayName(), message)); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java index 3fce3110c..bbf9ede4c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java @@ -1,49 +1,55 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.ItemPermissions; +import com.earth2me.essentials.permissions.Permissions; 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 + public void run(final IUser 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())) + int defaultStackSize = 0; + int oversizedStackSize = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + defaultStackSize = settings.getData().getGeneral().getDefaultStacksize(); + oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); + } + finally + { + settings.unlock(); + } + if (stack.getAmount() >= (Permissions.OVERSIZEDSTACKS.isAuthorized(user) + ? oversizedStackSize + : defaultStackSize > 0 ? defaultStackSize : 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()))) + if (!ItemPermissions.getPermission(stack.getType()).isAuthorized(user)) { throw new Exception(_("cantSpawnItem", itemname)); } - if (user.isAuthorized("essentials.oversizedstacks")) + if (Permissions.OVERSIZEDSTACKS.isAuthorized(user)) { - stack.setAmount(ess.getSettings().getOversizedStackSize()); + stack.setAmount(oversizedStackSize); } else { - stack.setAmount(stack.getMaxStackSize()); + stack.setAmount(defaultStackSize > 0 ? defaultStackSize : stack.getMaxStackSize()); } user.updateInventory(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java index 0031504e8..c1d1e92bf 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java @@ -1,22 +1,16 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.textreader.IText; -import com.earth2me.essentials.textreader.KeywordReplacer; -import com.earth2me.essentials.textreader.TextInput; -import com.earth2me.essentials.textreader.TextPager; -import org.bukkit.Server; +import com.earth2me.essentials.utils.textreader.IText; +import com.earth2me.essentials.utils.textreader.KeywordReplacer; +import com.earth2me.essentials.utils.textreader.TextInput; +import com.earth2me.essentials.utils.textreader.TextPager; import org.bukkit.command.CommandSender; public class Commandmotd extends EssentialsCommand { - public Commandmotd() - { - super("motd"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { final IText input = new TextInput(sender, "motd", true, ess); final IText output = new KeywordReplacer(input, sender, ess); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java index 2e1011e3b..8cc683e55 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java @@ -2,24 +2,20 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IReplyTo; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IReplyTo; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.List; -import org.bukkit.Server; +import lombok.Cleanup; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandmsg extends EssentialsCommand { - public Commandmsg() - { - super("msg"); - } - @Override - public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2 || args[0].trim().isEmpty() || args[1].trim().isEmpty()) { @@ -29,12 +25,21 @@ public class Commandmsg extends EssentialsCommand String message = getFinalArg(args, 1); if (sender instanceof Player) { - User user = ess.getUser(sender); - if (user.isMuted()) + @Cleanup + IUser user = ess.getUser((Player)sender); + user.acquireReadLock(); + if (user.getData().isMuted()) { throw new Exception(_("voiceSilenced")); } - message = Util.formatMessage(user, "essentials.msg", message); + if (Permissions.MSG_COLOR.isAuthorized(user)) + { + message = Util.replaceColor(message); + } + else + { + message = Util.stripColor(message); + } } else { @@ -49,7 +54,7 @@ public class Commandmsg extends EssentialsCommand if (args[0].equalsIgnoreCase(Console.NAME)) { sender.sendMessage(_("msgFormat", translatedMe, Console.NAME, message)); - CommandSender cs = Console.getCommandSender(server); + CommandSender cs = server.getConsoleSender(); cs.sendMessage(_("msgFormat", senderName, translatedMe, message)); replyTo.setReplyTo(cs); Console.getConsoleReplyTo().setReplyTo(sender); @@ -66,7 +71,7 @@ public class Commandmsg extends EssentialsCommand int i = 0; for (Player matchedPlayer : matchedPlayers) { - final User u = ess.getUser(matchedPlayer); + final IUser u = ess.getUser(matchedPlayer); if (u.isHidden()) { i++; @@ -80,8 +85,8 @@ public class Commandmsg extends EssentialsCommand for (Player matchedPlayer : matchedPlayers) { sender.sendMessage(_("msgFormat", translatedMe, matchedPlayer.getDisplayName(), message)); - final User matchedUser = ess.getUser(matchedPlayer); - if (sender instanceof Player && (matchedUser.isIgnoredPlayer(((Player)sender).getName()) || matchedUser.isHidden())) + final IUser matchedUser = ess.getUser(matchedPlayer); + if (sender instanceof Player && (matchedUser.isIgnoringPlayer(((Player)sender).getName()) || matchedUser.isHidden())) { continue; } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java index 3e70cc507..b537c5a96 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java @@ -1,29 +1,29 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.UserData.TimestampType; +import com.earth2me.essentials.utils.DateUtil; +import lombok.Cleanup; import org.bukkit.command.CommandSender; public class Commandmute extends EssentialsCommand { - public Commandmute() - { - super("mute"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - final User player = getPlayer(server, args, 0, true); - if (!player.isMuted() && player.isAuthorized("essentials.mute.exempt")) + @Cleanup + final IUser player = getPlayer(args, 0, true); + player.acquireReadLock(); + if (!player.getData().isMuted() && Permissions.MUTE_EXEMPT.isAuthorized(player)) { throw new Exception(_("muteExempt")); } @@ -31,20 +31,20 @@ public class Commandmute extends EssentialsCommand if (args.length > 1) { String time = getFinalArg(args, 1); - muteTimestamp = Util.parseDateDiff(time, true); + muteTimestamp = DateUtil.parseDateDiff(time, true); } - player.setMuteTimeout(muteTimestamp); + player.setTimestamp(TimestampType.MUTE, muteTimestamp); final boolean muted = player.toggleMuted(); sender.sendMessage( muted ? (muteTimestamp > 0 - ? _("mutedPlayerFor", player.getDisplayName(), Util.formatDateDiff(muteTimestamp)) + ? _("mutedPlayerFor", player.getDisplayName(), DateUtil.formatDateDiff(muteTimestamp)) : _("mutedPlayer", player.getDisplayName())) : _("unmutedPlayer", player.getDisplayName())); player.sendMessage( muted ? (muteTimestamp > 0 - ? _("playerMutedFor", Util.formatDateDiff(muteTimestamp)) + ? _("playerMutedFor", DateUtil.formatDateDiff(muteTimestamp)) : _("playerMuted")) : _("playerUnmuted")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java index c13c1489d..fc1450445 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java @@ -1,9 +1,9 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -11,30 +11,26 @@ 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 + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { long radius = 200; - User otherUser = null; + + IUser otherUser = null; if (args.length > 0) { try { - radius = Long.parseLong(args[0]); + otherUser = getPlayer(args, 0); } - catch (NumberFormatException e) + catch (Exception ex) { try { - otherUser = getPlayer(server, args, 0); + radius = Long.parseLong(args[0]); } - catch (Exception ex) + catch (NumberFormatException e) { } } @@ -49,9 +45,9 @@ public class Commandnear extends EssentialsCommand } } } - if (otherUser == null || user.isAuthorized("essentials.near.others")) + if (otherUser == null || Permissions.NEAR_OTHERS.isAuthorized(user)) { - user.sendMessage(_("nearbyPlayers", getLocal(server, otherUser == null ? user : otherUser, radius))); + user.sendMessage(_("nearbyPlayers", getLocal(otherUser == null ? user : otherUser, radius))); } else { @@ -60,13 +56,13 @@ public class Commandnear extends EssentialsCommand } @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length == 0) { throw new NotEnoughArgumentsException(); } - final User otherUser = getPlayer(server, args, 0); + final IUser otherUser = getPlayer(args, 0); long radius = 200; if (args.length > 1) { @@ -78,10 +74,10 @@ public class Commandnear extends EssentialsCommand { } } - sender.sendMessage(_("nearbyPlayers", getLocal(server, otherUser, radius))); + sender.sendMessage(_("nearbyPlayers", getLocal(otherUser, radius))); } - private String getLocal(final Server server, final User user, final long radius) + private String getLocal(final IUser user, final long radius) { final Location loc = user.getLocation(); final World world = loc.getWorld(); @@ -90,7 +86,7 @@ public class Commandnear extends EssentialsCommand for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); + final IUser player = ess.getUser(onlinePlayer); if (!player.equals(user) && !player.isHidden()) { final Location playerLoc = player.getLocation(); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java index 808e0be70..edbefafaf 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java @@ -1,9 +1,12 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.Locale; +import lombok.Cleanup; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -11,43 +14,44 @@ import org.bukkit.entity.Player; public class Commandnick extends EssentialsCommand { - public Commandnick() - { - super("nick"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - if (!ess.getSettings().changeDisplayName()) + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getChat().getChangeDisplayname()) { throw new Exception(_("nickDisplayName")); } if (args.length > 1) { - if (!user.isAuthorized("essentials.nick.others")) + if (!Permissions.NICK_OTHERS.isAuthorized(user)) { throw new Exception(_("nickOthersPermission")); } - setNickname(server, getPlayer(server, args, 0), formatNickname(user, args[1])); + setNickname(getPlayer(args, 0), formatNickname(user, args[1])); user.sendMessage(_("nickChanged")); return; } - setNickname(server, user, formatNickname(user, args[0])); + setNickname(user, formatNickname(user, args[0])); } @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } - if (!ess.getSettings().changeDisplayName()) + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getChat().getChangeDisplayname()) { throw new Exception(_("nickDisplayName")); } @@ -57,14 +61,14 @@ public class Commandnick extends EssentialsCommand } else { - setNickname(server, getPlayer(server, args, 0), formatNickname(null, args[1])); + setNickname(getPlayer(args, 0), formatNickname(null, args[1])); } sender.sendMessage(_("nickChanged")); } - private String formatNickname(final User user, final String nick) + private String formatNickname(final IUser user, final String nick) { - if (user == null) + if (user == null || Permissions.NICK_COLOR.isAuthorized(user)) { return Util.replaceFormat(nick); } @@ -80,7 +84,7 @@ public class Commandnick extends EssentialsCommand { try { - setNickname(server, ess.getUser(player), "off"); + setNickname(ess.getUser(player), "off"); } catch (Exception ex) { @@ -88,7 +92,7 @@ public class Commandnick extends EssentialsCommand } } - private void setNickname(final Server server, final User target, final String nick) throws Exception + private void setNickname(final IUser target, final String nick) throws Exception { if (!nick.matches("^[a-zA-Z_0-9\u00a7]+$")) { @@ -96,8 +100,8 @@ public class Commandnick extends EssentialsCommand } else if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick)) { - target.setNickname(null); - target.setDisplayNick(); + target.getData().setNickname(null); + target.updateDisplayName(); target.sendMessage(_("nickNoMore")); } else @@ -117,8 +121,8 @@ public class Commandnick extends EssentialsCommand } } - target.setNickname(nick); - target.setDisplayNick(); + target.getData().setNickname(nick); + target.updateDisplayName(); target.sendMessage(_("nickSet", target.getDisplayName() + "§7.")); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java b/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java index 60b1e3111..4f6e3933a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -14,13 +13,8 @@ import org.bukkit.entity.TNTPrimed; public class Commandnuke extends EssentialsCommand { - public Commandnuke() - { - super("nuke"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException { List<Player> targets; if (args.length > 0) @@ -29,7 +23,7 @@ public class Commandnuke extends EssentialsCommand int pos = 0; for (String arg : args) { - targets.add(getPlayer(server, args, pos)); + targets.add(getPlayer(args, pos)); pos++; } } @@ -51,7 +45,7 @@ public class Commandnuke extends EssentialsCommand { for (int z = -10; z <= 10; z += 5) { - final Location tntloc = new Location(world, loc.getBlockX() + x, world.getHighestBlockYAt(loc) + 64, loc.getBlockZ() + z); + final Location tntloc = new Location(world, loc.getBlockX() + x, world.getMaxHeight(), loc.getBlockZ() + z); final TNTPrimed tnt = world.spawn(tntloc, TNTPrimed.class); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java index 01e1fcffb..f79f0150b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java @@ -1,27 +1,21 @@ 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 com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; import org.bukkit.entity.Player; public class Commandpay extends EssentialsCommand { - public Commandpay() - { - super("pay"); - } - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } - + if (args[0] == "") { throw new NotEnoughArgumentsException("You need to specify a player to pay."); @@ -32,7 +26,7 @@ public class Commandpay extends EssentialsCommand Boolean foundUser = false; for (Player p : server.matchPlayer(args[0])) { - User u = ess.getUser(p); + IUser u = ess.getUser(p); if (u.isHidden()) { continue; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandping.java b/Essentials/src/com/earth2me/essentials/commands/Commandping.java index 43aa18d5f..5da879907 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandping.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandping.java @@ -1,25 +1,18 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Util; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; public class Commandping extends EssentialsCommand { - public Commandping() - { - super("ping"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { - - sender.sendMessage(_("pong")); + user.sendMessage(_("pong")); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java index d1d0fb582..9f0cf006a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java @@ -1,32 +1,28 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.inventory.ItemStack; public class Commandpowertool extends EssentialsCommand { - public Commandpowertool() - { - super("powertool"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { String command = getFinalArg(args, 0); // check to see if this is a clear all command if (command != null && command.equalsIgnoreCase("d:")) { - user.clearAllPowertools(); + user.acquireWriteLock(); + user.getData().clearAllPowertools(); user.sendMessage(_("powerToolClearAll")); return; } @@ -38,7 +34,7 @@ public class Commandpowertool extends EssentialsCommand } final String itemName = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replaceAll("_", " "); - List<String> powertools = user.getPowertool(itemStack); + List<String> powertools = user.getData().getPowertool(itemStack.getType()); if (command != null && !command.isEmpty()) { if (command.equalsIgnoreCase("l:")) @@ -68,7 +64,7 @@ public class Commandpowertool extends EssentialsCommand { if (command.startsWith("a:")) { - if (!user.isAuthorized("essentials.powertool.append")) + if (!Permissions.POWERTOOL_APPEND.isAuthorized(user)) { throw new Exception(_("noPerm", "essentials.powertool.append")); } @@ -106,6 +102,7 @@ public class Commandpowertool extends EssentialsCommand user.setPowerToolsEnabled(true); user.sendMessage(_("powerToolsEnabled")); } - user.setPowertool(itemStack, powertools); + user.acquireWriteLock(); + user.getData().setPowertool(itemStack.getType(), powertools); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java index c8b737dfa..24481bcec 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java @@ -1,26 +1,22 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; public class Commandpowertooltoggle extends EssentialsCommand { - public Commandpowertooltoggle() - { - super("powertooltoggle"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - if (!user.hasPowerTools()) + if (!user.getData().hasPowerTools()) { user.sendMessage(_("noPowerTools")); return; } - user.sendMessage(user.togglePowerToolsEnabled() + user.acquireWriteLock(); + user.getData().setPowerToolsEnabled(!user.getData().isPowerToolsEnabled()); + user.sendMessage(user.getData().isPowerToolsEnabled() ? _("powerToolsEnabled") : _("powerToolsDisabled")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java b/Essentials/src/com/earth2me/essentials/commands/Commandptime.java index 738b8db1a..c4c6e21a3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandptime.java @@ -1,10 +1,10 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.DescParseTickFormat; +import com.earth2me.essentials.utils.DescParseTickFormat; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.*; -import org.bukkit.Server; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -22,13 +22,8 @@ public class Commandptime extends EssentialsCommand getAliases.add("display"); } - public Commandptime() - { - super("ptime"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { // Which Players(s) / Users(s) are we interested in? String userSelector = null; @@ -36,7 +31,7 @@ public class Commandptime extends EssentialsCommand { userSelector = args[1]; } - Set<User> users = getUsers(server, sender, userSelector); + Set<IUser> users = getUsers(sender, userSelector); // If no arguments we are reading the time if (args.length == 0) @@ -45,8 +40,8 @@ public class Commandptime extends EssentialsCommand return; } - User user = ess.getUser(sender); - if ((!users.contains(user) || users.size() > 1) && user != null && !user.isAuthorized("essentials.ptime.others")) + IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; + if ((!users.contains(user) || users.size() > 1) && user != null && !Permissions.PTIME_OTHERS.isAuthorized(user)) { user.sendMessage(_("pTimeOthersPermission")); return; @@ -89,14 +84,14 @@ public class Commandptime extends EssentialsCommand /** * Used to get the time and inform */ - private void getUsersTime(final CommandSender sender, final Collection<User> users) + private void getUsersTime(final CommandSender sender, final Collection<IUser> users) { if (users.size() > 1) { sender.sendMessage(_("pTimePlayers")); } - for (User user : users) + for (IUser user : users) { if (user.getPlayerTimeOffset() == 0) { @@ -120,13 +115,13 @@ public class Commandptime extends EssentialsCommand /** * Used to set the time and inform of the change */ - private void setUsersTime(final CommandSender sender, final Collection<User> users, final Long ticks, Boolean relative) + private void setUsersTime(final CommandSender sender, final Collection<IUser> users, final Long ticks, Boolean relative) { // Update the time if (ticks == null) { // Reset - for (User user : users) + for (IUser user : users) { user.resetPlayerTime(); } @@ -134,7 +129,7 @@ public class Commandptime extends EssentialsCommand else { // Set - for (User user : users) + for (IUser user : users) { final World world = user.getWorld(); long time = user.getPlayerTime(); @@ -149,7 +144,7 @@ public class Commandptime extends EssentialsCommand } final StringBuilder msg = new StringBuilder(); - for (User user : users) + for (IUser user : users) { if (msg.length() > 0) { @@ -181,13 +176,13 @@ public class Commandptime extends EssentialsCommand /** * Used to parse an argument of the type "users(s) selector" */ - private Set<User> getUsers(final Server server, final CommandSender sender, final String selector) throws Exception + private Set<IUser> getUsers(final CommandSender sender, final String selector) throws Exception { - final Set<User> users = new TreeSet<User>(new UserNameComparator()); + final Set<IUser> users = new TreeSet<IUser>(); // If there is no selector we want the sender itself. Or all users if sender isn't a user. if (selector == null) { - final User user = ess.getUser(sender); + final IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; if (user == null) { for (Player player : server.getOnlinePlayers()) @@ -203,7 +198,7 @@ public class Commandptime extends EssentialsCommand } // Try to find the user with name = selector - User user = null; + IUser user = null; final List<Player> matchedPlayers = server.matchPlayer(selector); if (!matchedPlayers.isEmpty()) { @@ -231,13 +226,3 @@ public class Commandptime extends EssentialsCommand return users; } } - - -class UserNameComparator implements Comparator<User> -{ - @Override - public int compare(User a, User b) - { - return a.getName().compareTo(b.getName()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandr.java b/Essentials/src/com/earth2me/essentials/commands/Commandr.java index 9b585509d..feb183b23 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandr.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandr.java @@ -2,23 +2,18 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IReplyTo; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IReplyTo; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandr extends EssentialsCommand { - public Commandr() - { - super("r"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -31,8 +26,15 @@ public class Commandr extends EssentialsCommand if (sender instanceof Player) { - User user = ess.getUser(sender); - message = Util.formatMessage(user, "essentials.msg", message); + IUser user = ess.getUser((Player)sender); + if (Permissions.MSG_COLOR.isAuthorized(user)) + { + message = Util.replaceFormat(message); + } + else + { + message = Util.replaceFormat(message); + } replyTo = user; senderName = user.getDisplayName(); } @@ -54,8 +56,8 @@ public class Commandr extends EssentialsCommand sender.sendMessage(_("msgFormat", _("me"), targetName, message)); if (target instanceof Player) { - User player = ess.getUser(target); - if (player.isIgnoredPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME)) + IUser player = ess.getUser((Player)target); + if (player.isIgnoringPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME)) { return; } @@ -74,4 +76,10 @@ public class Commandr extends EssentialsCommand } } } + + @Override + public String getPermission() + { + return "essentials.msg"; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java index c99018211..9d69d2ad6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java @@ -1,40 +1,39 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; import java.util.Locale; -import org.bukkit.Server; +import lombok.Cleanup; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandrealname extends EssentialsCommand { - public Commandrealname() - { - super("realname"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } + @Cleanup + final ISettings settings = ess.getSettings(); final String whois = args[0].toLowerCase(Locale.ENGLISH); for (Player onlinePlayer : server.getOnlinePlayers()) { - final User u = ess.getUser(onlinePlayer); + final IUser u = ess.getUser(onlinePlayer); if (u.isHidden()) { continue; } u.setDisplayNick(); final String displayName = Util.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH); + settings.acquireReadLock(); if (!whois.equals(displayName) - && !displayName.equals(Util.stripFormat(ess.getSettings().getNicknamePrefix()) + whois) + && !displayName.equals(Util.stripFormat(settings.getData().getChat().getNicknamePrefix()) + whois) && !whois.equalsIgnoreCase(u.getName())) { continue; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java b/Essentials/src/com/earth2me/essentials/commands/Commandremove.java index 912434f08..05d27a3bc 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandremove.java @@ -1,10 +1,9 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; 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.*; @@ -12,12 +11,6 @@ import org.bukkit.entity.*; public class Commandremove extends EssentialsCommand { - public Commandremove() - { - super("remove"); - } - - private enum ToRemove { DROPS, @@ -29,7 +22,7 @@ public class Commandremove extends EssentialsCommand } @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -64,7 +57,7 @@ public class Commandremove extends EssentialsCommand } @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java index d621109f7..05715b515 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java @@ -1,24 +1,22 @@ package com.earth2me.essentials.commands; +import com.earth2me.essentials.api.ChargeException; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.*; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.inventory.ItemStack; public class Commandrepair extends EssentialsCommand { - public Commandrepair() - { - super("repair"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -34,8 +32,7 @@ public class Commandrepair extends EssentialsCommand } if (!item.getEnchantments().isEmpty() - && !ess.getSettings().getRepairEnchanted() - && !user.isAuthorized("essentials.repair.enchanted")) + && !Permissions.REPAIR_ENCHANTED.isAuthorized(user)) { throw new Exception(_("repairEnchanted")); } @@ -58,7 +55,7 @@ public class Commandrepair extends EssentialsCommand final List<String> repaired = new ArrayList<String>(); repairItems(user.getInventory().getContents(), user, repaired); - if (user.isAuthorized("essentials.repair.armor")) + if (Permissions.REPAIR_ARMOR.isAuthorized(user)) { repairItems(user.getInventory().getArmorContents(), user, repaired); } @@ -116,8 +113,7 @@ public class Commandrepair extends EssentialsCommand continue; } if (!item.getEnchantments().isEmpty() - && !ess.getSettings().getRepairEnchanted() - && !user.isAuthorized("essentials.repair.enchanted")) + && !Permissions.REPAIR_ENCHANTED.isAuthorized(user)) { continue; } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java index d87c4f41b..da0a3eaec 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java @@ -1,22 +1,16 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.textreader.IText; -import com.earth2me.essentials.textreader.KeywordReplacer; -import com.earth2me.essentials.textreader.TextInput; -import com.earth2me.essentials.textreader.TextPager; -import org.bukkit.Server; +import com.earth2me.essentials.utils.textreader.IText; +import com.earth2me.essentials.utils.textreader.KeywordReplacer; +import com.earth2me.essentials.utils.textreader.TextInput; +import com.earth2me.essentials.utils.textreader.TextPager; import org.bukkit.command.CommandSender; public class Commandrules extends EssentialsCommand { - public Commandrules() - { - super("rules"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(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); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java b/Essentials/src/com/earth2me/essentials/commands/Commandseen.java index 24f1f9c41..5dcaa0f2a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandseen.java @@ -1,33 +1,30 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Location; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.UserData.TimestampType; +import com.earth2me.essentials.utils.DateUtil; +import lombok.Cleanup; import org.bukkit.command.CommandSender; public class Commandseen extends EssentialsCommand { - public Commandseen() - { - super("seen"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { - seen(server, sender, args, true, true); + seen(sender,args,true); } - + @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - seen(server, user, args, user.isAuthorized("essentials.seen.banreason"), user.isAuthorized("essentials.seen.extra")); + seen(user,args,Permissions.SEEN_BANREASON.isAuthorized(user)); } - - protected void seen(final Server server, final CommandSender sender, final String[] args, final boolean showBan, final boolean extra) throws Exception + + protected void seen (final CommandSender sender, final String[] args, final boolean show) throws Exception { if (args.length < 1) { @@ -35,26 +32,24 @@ public class Commandseen extends EssentialsCommand } try { - User player = getPlayer(server, args, 0); + IUser u = getPlayer(args, 0); player.setDisplayNick(); - sender.sendMessage(_("seenOnline", player.getDisplayName(), Util.formatDateDiff(player.getLastLogin()))); - if (extra) - { - sender.sendMessage(_("whoisIPAddress", player.getAddress().getAddress().toString())); - } + sender.sendMessage(_("seenOnline", u.getDisplayName(), DateUtil.formatDateDiff(u.getTimestamp(TimestampType.LOGIN)))); } catch (NoSuchFieldException e) { - User player = ess.getOfflineUser(args[0]); - if (player == null) + @Cleanup + IUser u = ess.getUser(args[0]); + u.acquireReadLock(); + if (u == null) { throw new Exception(_("playerNotFound")); } player.setDisplayNick(); - sender.sendMessage(_("seenOffline", player.getName(), Util.formatDateDiff(player.getLastLogout()))); - if (player.isBanned()) + sender.sendMessage(_("seenOffline", u.getDisplayName(), DateUtil.formatDateDiff(u.getTimestamp(TimestampType.LOGOUT)))); + if (u.isBanned()) { - sender.sendMessage(_("whoisBanned", showBan ? player.getBanReason() : _("true"))); + sender.sendMessage(_("whoisBanned", show ? u.getData().getBan().getReason() : _("true"))); } if (extra) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java index 5958a5c0f..0b56843cd 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java @@ -1,26 +1,20 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; import java.util.Locale; import java.util.logging.Level; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.inventory.ItemStack; public class Commandsell extends EssentialsCommand { - public Commandsell() - { - super("sell"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -74,7 +68,7 @@ public class Commandsell extends EssentialsCommand sellItem(user, is, args, false); } - private void sellItem(User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception + private void sellItem(IUser user, ItemStack is, String[] args, boolean isBulkSell) throws Exception { if (is == null || is.getType() == Material.AIR) { @@ -92,16 +86,11 @@ public class Commandsell extends EssentialsCommand } double worth = ess.getWorth().getPrice(is); boolean stack = args.length > 1 && args[1].endsWith("s"); - boolean requireStack = ess.getSettings().isTradeInStacks(id); if (Double.isNaN(worth)) { throw new Exception(_("itemCannotBeSold")); } - if (requireStack && !stack) - { - throw new Exception(_("itemMustBeStacked")); - } int max = 0; @@ -135,10 +124,6 @@ public class Commandsell extends EssentialsCommand amount += max; } - if (requireStack) - { - amount -= amount % is.getType().getMaxStackSize(); - } if (amount > max || amount < 1) { if (!isBulkSell) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java index f622094d2..5ef850264 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java @@ -1,20 +1,17 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import java.util.HashMap; import java.util.Locale; -import org.bukkit.Server; +import lombok.Cleanup; public class Commandsethome extends EssentialsCommand { - public Commandsethome() - { - super("sethome"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, String[] args) throws Exception + public void run(final IUser user, final String commandLabel, String[] args) throws Exception { if (args.length > 0) { @@ -27,20 +24,25 @@ public class Commandsethome extends EssentialsCommand if (args.length < 2) { - if (user.isAuthorized("essentials.sethome.multiple")) + if (Permissions.SETHOME_MULTIPLE.isAuthorized(user)) { if ("bed".equals(args[0].toLowerCase(Locale.ENGLISH))) { throw new NotEnoughArgumentsException(); } - if ((user.isAuthorized("essentials.sethome.multiple.unlimited")) || (user.getHomes().size() < ess.getSettings().getHomeLimit(user)) + if ((user.getHomes().size() < ess.getRanks().getHomeLimit(user)) || (user.getHomes().contains(args[0].toLowerCase(Locale.ENGLISH)))) { - user.setHome(args[0].toLowerCase(Locale.ENGLISH)); + user.acquireWriteLock(); + if (user.getData().getHomes() == null) + { + user.getData().setHomes(new HashMap<String, com.earth2me.essentials.storage.Location>()); + } + user.getData().getHomes().put(args[0].toLowerCase(Locale.ENGLISH), new com.earth2me.essentials.storage.Location(user.getLocation())); } else { - throw new Exception(_("maxHomes", ess.getSettings().getHomeLimit(user))); + throw new Exception(_("maxHomes", ess.getRanks().getHomeLimit(user))); } } @@ -51,19 +53,16 @@ public class Commandsethome extends EssentialsCommand } else { - if (user.isAuthorized("essentials.sethome.others")) + if (Permissions.SETHOME_OTHERS.isAuthorized(user)) { - User usersHome = ess.getUser(ess.getServer().getPlayer(args[0])); - if (usersHome == null) - { - usersHome = ess.getOfflineUser(args[0]); - } + @Cleanup + IUser usersHome = ess.getUser(ess.getServer().getPlayer(args[0])); if (usersHome == null) { throw new Exception(_("playerNotFound")); } String name = args[1].toLowerCase(Locale.ENGLISH); - if (!user.isAuthorized("essentials.sethome.multiple")) + if (!Permissions.SETHOME_MULTIPLE.isAuthorized(user)) { name = "home"; } @@ -71,13 +70,24 @@ public class Commandsethome extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - usersHome.setHome(name, user.getLocation()); + + usersHome.acquireWriteLock(); + if (usersHome.getData().getHomes() == null) + { + usersHome.getData().setHomes(new HashMap<String, com.earth2me.essentials.storage.Location>()); + } + usersHome.getData().getHomes().put(name, new com.earth2me.essentials.storage.Location(user.getLocation())); } } } else { - user.setHome(); + user.acquireWriteLock(); + if (user.getData().getHomes() == null) + { + user.getData().setHomes(new HashMap<String, com.earth2me.essentials.storage.Location>()); + } + user.getData().getHomes().put("home", new com.earth2me.essentials.storage.Location(user.getLocation())); } user.sendMessage(_("homeSet", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java index 877da4d26..fea08f7a0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java @@ -1,20 +1,13 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; public class Commandsetjail extends EssentialsCommand { - public Commandsetjail() - { - super("setjail"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetspawn.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetspawn.java new file mode 100644 index 000000000..3af7e711f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetspawn.java @@ -0,0 +1,17 @@ +package com.earth2me.essentials.commands; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.settings.SpawnsHolder; + + +public class Commandsetspawn extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final String group = args.length > 0 ? getFinalArg(args, 0) : "default"; + ((SpawnsHolder)module).setSpawn(user.getLocation(), group); + user.sendMessage(_("spawnSet", group)); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java index 42da62b85..72b42fe7c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java @@ -1,45 +1,41 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.api.IWarps; import com.earth2me.essentials.Util; import com.earth2me.essentials.Warps; import org.bukkit.Location; -import org.bukkit.Server; public class Commandsetwarp extends EssentialsCommand { - public Commandsetwarp() - { - super("setwarp"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - - if (args[0].matches("[0-9]+")) { + + if (args[0].matches("[0-9]+")) + { throw new NotEnoughArgumentsException(); } final Location loc = user.getLocation(); - final Warps warps = ess.getWarps(); + final IWarps warps = ess.getWarps(); Location warpLoc = null; try { warpLoc = warps.getWarp(args[0]); } - catch (Exception ex) + catch (WarpNotFoundException ex) { } - if (warpLoc == null || user.isAuthorized("essentials.warp.overwrite." + Util.sanitizeFileName(args[0]))) + if (warpLoc == null || user.hasPermission("essentials.warp.overwrite." + args[0])) { warps.setWarp(args[0], loc); } @@ -47,6 +43,7 @@ public class Commandsetwarp extends EssentialsCommand { throw new Exception(_("warpOverwrite")); } + user.sendMessage(_("warpSet", args[0])); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java index 91a1dd657..e42c11651 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java @@ -1,21 +1,42 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender; import org.bukkit.inventory.ItemStack; public class Commandsetworth extends EssentialsCommand { - public Commandsetworth() + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - super("setworth"); + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + ItemStack stack; + String price; + + if (args.length == 1) + { + stack = user.getInventory().getItemInHand(); + price = args[0]; + } + else + { + stack = ess.getItemDb().get(args[0]); + price = args[1]; + } + + ess.getWorth().setPrice(stack, Double.parseDouble(price)); + user.sendMessage(_("worthSet")); } @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java b/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java index 6080642a1..86ae15fc8 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java @@ -1,19 +1,13 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; public class Commandsocialspy extends EssentialsCommand { - public Commandsocialspy() - { - super("socialspy"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { user.sendMessage("§7SocialSpy " + (user.toggleSocialSpy() ? _("enabled") : _("disabled"))); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawn.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawn.java new file mode 100644 index 000000000..0edcf870c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawn.java @@ -0,0 +1,55 @@ +package com.earth2me.essentials.commands; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.settings.SpawnsHolder; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandspawn extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + if (args.length > 0 && Permissions.SPAWN_OTHERS.isAuthorized(user)) + { + final IUser otherUser = getPlayer(args, 0); + respawn(otherUser, null); + if (!otherUser.equals(user)) + { + otherUser.sendMessage(_("teleportAtoB", user.getDisplayName(), "spawn")); + user.sendMessage(_("teleporting")); + } + } + else + { + respawn(user, null); + } + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + final IUser user = getPlayer(args, 0); + respawn(user, null); + user.sendMessage(_("teleportAtoB", user.getDisplayName(), "spawn")); + sender.sendMessage(_("teleporting")); + } + + private void respawn(final IUser user, final Trade charge) throws Exception + { + final SpawnsHolder spawns = (SpawnsHolder)this.module; + final Location spawn = spawns.getSpawn(ess.getRanks().getMainGroup(user)); + user.getTeleport().teleport(spawn, charge, TeleportCause.COMMAND); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java index d2b50137d..c68290c65 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java @@ -2,30 +2,30 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.*; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.bukkit.Mob; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.SpawnerPermissions; +import com.earth2me.essentials.utils.LocationUtil; +import com.earth2me.essentials.utils.Util; import java.util.Locale; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.block.CreatureSpawner; import org.bukkit.entity.EntityType; public class Commandspawner extends EssentialsCommand { - public Commandspawner() - { - super("spawner"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1 || args[0].length() < 2) { throw new NotEnoughArgumentsException(_("mobsAvailable", Util.joinList(Mob.getMobList()))); } - final Location target = Util.getTarget(user); + final Location target = LocationUtil.getTarget(user); if (target == null || target.getBlock().getType() != Material.MOB_SPAWNER) { throw new Exception(_("mobSpawnTarget")); @@ -51,7 +51,24 @@ public class Commandspawner extends EssentialsCommand charge.isAffordableFor(user); try { + String name = args[0]; + + Mob mob = null; + mob = Mob.fromName(name); + if (mob == null) + { + user.sendMessage(_("invalidMob")); + return; + } + if (!SpawnerPermissions.getPermission(mob.name).isAuthorized(user)) + { + throw new Exception(_("unableToSpawnMob")); + } + final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); + charge.isAffordableFor(user); ((CreatureSpawner)target.getBlock().getState()).setSpawnedType(mob.getType()); + charge.charge(user); + user.sendMessage(_("setSpawner", mob.name)); } catch (Throwable ex) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java index 2546a76dd..c9c8a2a4b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java @@ -1,14 +1,17 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Mob; -import com.earth2me.essentials.Mob.MobException; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.bukkit.Mob; +import com.earth2me.essentials.bukkit.Mob.MobException; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.SpawnmobPermissions; +import com.earth2me.essentials.utils.LocationUtil; +import com.earth2me.essentials.utils.Util; +import java.util.HashSet; import java.util.*; import org.bukkit.DyeColor; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.entity.*; import org.bukkit.entity.Villager.Profession; @@ -17,13 +20,8 @@ import org.bukkit.material.Colorable; public class Commandspawnmob extends EssentialsCommand { - public Commandspawnmob() - { - super("spawnmob"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -31,7 +29,7 @@ public class Commandspawnmob extends EssentialsCommand final Set<String> availableList = new HashSet<String>(); for (String mob : mobList) { - if (user.isAuthorized("essentials.spawnmob." + mob.toLowerCase())) + if (SpawnmobPermissions.getPermission(mob).isAuthorized(user)) { availableList.add(mob); } @@ -76,27 +74,23 @@ public class Commandspawnmob extends EssentialsCommand throw new Exception(_("invalidMob")); } - if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) - { - throw new Exception(_("disabledToSpawnMob")); - } - if (!user.isAuthorized("essentials.spawnmob." + mob.name.toLowerCase())) + if (!SpawnmobPermissions.getPermission(mob.name).isAuthorized(user)) { throw new Exception(_("noPermToSpawnMob")); } - final Block block = Util.getTarget(user).getBlock(); + final Block block = LocationUtil.getTarget(user).getBlock(); if (block == null) { throw new Exception(_("unableToSpawnMob")); } - User otherUser = null; + IUser otherUser = null; if (args.length >= 3) { - otherUser = getPlayer(ess.getServer(), args, 2); + otherUser = getPlayer(args, 2); } final Location loc = (otherUser == null) ? block.getLocation() : otherUser.getLocation(); - final Location sloc = Util.getSafeDestination(loc); + final Location sloc = LocationUtil.getSafeDestination(loc); try { spawnedMob = mob.spawn(user, server, sloc); @@ -115,11 +109,7 @@ public class Commandspawnmob extends EssentialsCommand return; } - if (ess.getSettings().getProtectPreventSpawn(mobMount.getType().toString().toLowerCase(Locale.ENGLISH))) - { - throw new Exception(_("disabledToSpawnMob")); - } - if (!user.isAuthorized("essentials.spawnmob." + mobMount.name.toLowerCase())) + if (!SpawnmobPermissions.getPermission(mobMount.name).isAuthorized(user)) { throw new Exception(_("noPermToSpawnMob")); } @@ -144,7 +134,17 @@ public class Commandspawnmob extends EssentialsCommand if (args.length >= 2) { int mobCount = Integer.parseInt(args[1]); - int serverLimit = ess.getSettings().getSpawnMobLimit(); + int serverLimit = 1; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + serverLimit = settings.getData().getCommands().getSpawnmob().getLimit(); + } + finally + { + settings.unlock(); + } if (mobCount > serverLimit) { mobCount = serverLimit; @@ -198,7 +198,7 @@ public class Commandspawnmob extends EssentialsCommand } } - private void changeMobData(final EntityType type, final Entity spawned, String data, final User user) throws Exception + private void changeMobData(final EntityType type, final Entity spawned, String data, final IUser user) throws Exception { data = data.toLowerCase(Locale.ENGLISH); @@ -278,5 +278,20 @@ public class Commandspawnmob extends EssentialsCommand } } } + if (type == EntityType.OCELOT) + { + if (data.contains("siamese")) + { + ((Ocelot)spawned).setCatType(Ocelot.Type.SIAMESE_CAT); + } + if (data.contains("red")) + { + ((Ocelot)spawned).setCatType(Ocelot.Type.RED_CAT); + } + if (data.contains("black")) + { + ((Ocelot)spawned).setCatType(Ocelot.Type.BLACK_CAT); + } + } } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java index 23083fa3d..9d94bef89 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java @@ -1,29 +1,24 @@ package com.earth2me.essentials.commands; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; public class Commandsudo extends EssentialsCommand { - public Commandsudo() - { - super("sudo"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } - final User user = getPlayer(server, args, 0, false); + final IUser user = getPlayer(args, 0, false); final String command = args[1]; final String[] arguments = new String[args.length - 2]; if (arguments.length > 0) @@ -31,7 +26,7 @@ public class Commandsudo extends EssentialsCommand System.arraycopy(args, 2, arguments, 0, args.length - 2); } - if (user.isAuthorized("essentials.sudo.exempt")) + if (Permissions.SUDO_EXEMPT.isAuthorized(user)) { throw new Exception(_("sudoExempt")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java index 84c9fc489..1c6b99c32 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java @@ -1,22 +1,16 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; import org.bukkit.event.entity.EntityDamageEvent; public class Commandsuicide extends EssentialsCommand { - public Commandsuicide() - { - super("suicide"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - EntityDamageEvent ede = new EntityDamageEvent(user.getBase(), EntityDamageEvent.DamageCause.SUICIDE, Short.MAX_VALUE); + EntityDamageEvent ede = new EntityDamageEvent(user.getBase(), EntityDamageEvent.DamageCause.SUICIDE, 1000); server.getPluginManager().callEvent(ede); user.damage(Short.MAX_VALUE); user.sendMessage(_("suicideMessage")); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java index 25c457a20..4068f8d18 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java @@ -2,32 +2,29 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.Ban; +import com.earth2me.essentials.utils.DateUtil; +import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandtempban extends EssentialsCommand { - public Commandtempban() - { - super("tempban"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } - final User user = getPlayer(server, args, 0, true); + final IUser user = getPlayer(args, 0, true); if (!user.isOnline()) { - if (sender instanceof Player - && !ess.getUser(sender).isAuthorized("essentials.tempban.offline")) + if (Permissions.TEMPBAN_OFFLINE.isAuthorized(sender)) { sender.sendMessage(_("tempbanExempt")); return; @@ -35,26 +32,28 @@ public class Commandtempban extends EssentialsCommand } else { - if (user.isAuthorized("essentials.tempban.exempt")) + if (Permissions.TEMPBAN_EXEMPT.isAuthorized(user)) { sender.sendMessage(_("tempbanExempt")); return; } } final String time = getFinalArg(args, 1); - final long banTimestamp = Util.parseDateDiff(time, true); + final long banTimestamp = DateUtil.parseDateDiff(time, true); - final String banReason = _("tempBanned", Util.formatDateDiff(banTimestamp)); - user.setBanReason(banReason); - user.setBanTimeout(banTimestamp); + final String banReason = _("tempBanned", DateUtil.formatDateDiff(banTimestamp)); + user.acquireWriteLock(); + user.getData().setBan(new Ban()); + user.getData().getBan().setReason(banReason); + user.getData().getBan().setTimeout(banTimestamp); user.setBanned(true); user.kickPlayer(banReason); final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); - if (player.isAuthorized("essentials.ban.notify")) + final IUser player = ess.getUser(onlinePlayer); + if (Permissions.BAN_NOTIFY.isAuthorized(player)) { onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason)); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java b/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java index 3cb60e6e3..23c2e13b9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java @@ -1,20 +1,14 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; import org.bukkit.World; public class Commandthunder extends EssentialsCommand { - public Commandthunder() - { - super("thunder"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java index 8e5b7c017..9b28f5d6c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java @@ -1,24 +1,20 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.DescParseTickFormat; +import com.earth2me.essentials.utils.DescParseTickFormat; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import com.earth2me.essentials.Util; import java.util.*; -import org.bukkit.Server; import org.bukkit.World; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; public class Commandtime extends EssentialsCommand { - public Commandtime() - { - super("time"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { final List<String> argList = new ArrayList<String>(Arrays.asList(args)); if ((argList.remove("set") || argList.remove("add")) && Util.isInt(argList.get(0))) @@ -33,7 +29,7 @@ public class Commandtime extends EssentialsCommand { worldSelector = validArgs[1]; } - final Set<World> worlds = getWorlds(server, sender, worldSelector); + final Set<World> worlds = getWorlds(sender, worldSelector); // If no arguments we are reading the time if (validArgs.length == 0) @@ -42,10 +38,9 @@ public class Commandtime extends EssentialsCommand return; } - final User user = ess.getUser(sender); - if (user != null && !user.isAuthorized("essentials.time.set")) + if (Permissions.TIME_SET.isAuthorized(sender)) { - user.sendMessage(_("timeSetPermission")); + sender.sendMessage(_("timeSetPermission")); return; } @@ -111,14 +106,14 @@ public class Commandtime extends EssentialsCommand /** * Used to parse an argument of the type "world(s) selector" */ - private Set<World> getWorlds(final Server server, final CommandSender sender, final String selector) throws Exception + private Set<World> getWorlds(final CommandSender sender, final String selector) throws Exception { final Set<World> worlds = new TreeSet<World>(new WorldNameComparator()); // If there is no selector we want the world the user is currently in. Or all worlds if it isn't a user. if (selector == null) { - final User user = ess.getUser(sender); + final IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; if (user == null) { worlds.addAll(server.getWorlds()); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java index 3240b73a9..856a32153 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java @@ -1,36 +1,35 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.UserData.TimestampType; +import com.earth2me.essentials.utils.DateUtil; +import lombok.Cleanup; +import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; public class Commandtogglejail extends EssentialsCommand { - public Commandtogglejail() - { - super("togglejail"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - final User player = getPlayer(server, args, 0, true); + @Cleanup + final IUser player = getPlayer(args, 0, true); + player.acquireReadLock(); - if (args.length >= 2 && !player.isJailed()) + if (args.length >= 2 && !player.getData().isJailed()) { if (!player.isOnline()) { - if (sender instanceof Player - && !ess.getUser(sender).isAuthorized("essentials.togglejail.offline")) + if (Permissions.TOGGLEJAIL_OFFLINE.isAuthorized(sender)) { sender.sendMessage(_("mayNotJail")); return; @@ -38,7 +37,7 @@ public class Commandtogglejail extends EssentialsCommand } else { - if (player.isAuthorized("essentials.jail.exempt")) + if (Permissions.JAIL_EXEMPT.isAuthorized(player)) { sender.sendMessage(_("mayNotJail")); return; @@ -53,48 +52,50 @@ public class Commandtogglejail extends EssentialsCommand // Check if jail exists ess.getJails().getJail(args[1]); } - player.setJailed(true); + player.acquireWriteLock(); + player.getData().setJailed(true); player.sendMessage(_("userJailed")); - player.setJail(null); - player.setJail(args[1]); + player.getData().setJail(args[1]); long timeDiff = 0; if (args.length > 2) { final String time = getFinalArg(args, 2); - timeDiff = Util.parseDateDiff(time, true); - player.setJailTimeout(timeDiff); + timeDiff = DateUtil.parseDateDiff(time, true); + player.setTimestamp(TimestampType.JAIL, timeDiff); } sender.sendMessage((timeDiff > 0 - ? _("playerJailedFor", player.getName(), Util.formatDateDiff(timeDiff)) + ? _("playerJailedFor", player.getName(), DateUtil.formatDateDiff(timeDiff)) : _("playerJailed", player.getName()))); return; } - if (args.length >= 2 && player.isJailed() && !args[1].equalsIgnoreCase(player.getJail())) + if (args.length >= 2 && player.getData().isJailed() && !args[1].equalsIgnoreCase(player.getData().getJail())) { - sender.sendMessage(_("jailAlreadyIncarcerated", player.getJail())); + sender.sendMessage(_("jailAlreadyIncarcerated", player.getData().getJail())); return; } - if (args.length >= 2 && player.isJailed() && args[1].equalsIgnoreCase(player.getJail())) + if (args.length >= 2 && player.getData().isJailed() && args[1].equalsIgnoreCase(player.getData().getJail())) { final String time = getFinalArg(args, 2); - final long timeDiff = Util.parseDateDiff(time, true); - player.setJailTimeout(timeDiff); - sender.sendMessage(_("jailSentenceExtended", Util.formatDateDiff(timeDiff))); + final long timeDiff = DateUtil.parseDateDiff(time, true); + player.acquireWriteLock(); + player.setTimestamp(TimestampType.JAIL, timeDiff); + sender.sendMessage(_("jailSentenceExtended", DateUtil.formatDateDiff(timeDiff))); return; } - if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(player.getJail()))) + if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(player.getData().getJail()))) { - if (!player.isJailed()) + if (!player.getData().isJailed()) { throw new NotEnoughArgumentsException(); } - player.setJailed(false); - player.setJailTimeout(0); + player.acquireWriteLock(); + player.getData().setJailed(false); + player.setTimestamp(TimestampType.JAIL, 0); player.sendMessage(_("jailReleasedPlayerNotify")); - player.setJail(null); + player.getData().setJail(null); if (player.isOnline()) { player.getTeleport().back(); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java index e91d0984a..1e9926ecd 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java @@ -1,27 +1,21 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtop extends EssentialsCommand { - public Commandtop() - { - super("top"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { 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), TeleportCause.COMMAND); + user.getTeleport().teleport(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), new Trade(commandName, ess), TeleportCause.COMMAND); user.sendMessage(_("teleportTop")); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java index d6d6b76f9..f508c872c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java @@ -2,22 +2,18 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import lombok.Cleanup; import org.bukkit.command.CommandSender; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtp extends EssentialsCommand { - public Commandtp() - { - super("tp"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { switch (args.length) { @@ -25,8 +21,10 @@ public class Commandtp extends EssentialsCommand throw new NotEnoughArgumentsException(); case 1: - final User player = getPlayer(server, args, 0); - if (!player.isTeleportEnabled()) + @Cleanup + final IUser player = getPlayer(args, 0); + player.acquireReadLock(); + if (!player.getData().isTeleportEnabled()) { throw new Exception(_("teleportDisabled", player.getDisplayName())); } @@ -36,19 +34,19 @@ public class Commandtp extends EssentialsCommand throw new Exception(_("noPerm", "essentials.world." + player.getWorld().getName())); } user.sendMessage(_("teleporting")); - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); charge.isAffordableFor(user); user.getTeleport().teleport(player, charge, TeleportCause.COMMAND); throw new NoChargeException(); default: - if (!user.isAuthorized("essentials.tp.others")) + if (!Permissions.TPOHERE.isAuthorized(user)) { - throw new Exception(_("noPerm", "essentials.tp.others")); + throw new Exception(_("needTpohere")); } user.sendMessage(_("teleporting")); - final User target = getPlayer(server, args, 0); - final User toPlayer = getPlayer(server, args, 1); + final IUser target = getPlayer(args, 0); + final IUser toPlayer = getPlayer(args, 1); if (!target.isTeleportEnabled()) { throw new Exception(_("teleportDisabled", target.getDisplayName())); @@ -69,7 +67,7 @@ public class Commandtp extends EssentialsCommand } @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { @@ -77,8 +75,8 @@ public class Commandtp extends EssentialsCommand } sender.sendMessage(_("teleporting")); - final User target = getPlayer(server, args, 0); - final User toPlayer = getPlayer(server, args, 1); + final IUser target = getPlayer(args, 0); + final IUser toPlayer = getPlayer(args, 1); target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); target.sendMessage(_("teleportAtoB", Console.NAME, toPlayer.getDisplayName())); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java index 95cbc58cd..6ce71b3ba 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java @@ -1,27 +1,25 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import lombok.Cleanup; public class Commandtpa extends EssentialsCommand { - public Commandtpa() - { - super("tpa"); - } - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - User player = getPlayer(server, args, 0); - if (!player.isTeleportEnabled()) + @Cleanup + IUser player = getPlayer(args, 0); + player.acquireReadLock(); + if (!player.getData().isTeleportEnabled()) { throw new Exception(_("teleportDisabled", player.getDisplayName())); } @@ -36,9 +34,17 @@ public class Commandtpa extends EssentialsCommand player.sendMessage(_("teleportRequest", user.getDisplayName())); player.sendMessage(_("typeTpaccept")); player.sendMessage(_("typeTpdeny")); - if (ess.getSettings().getTpaAcceptCancellation() != 0) + int tpaAcceptCancellation = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } finally { + settings.unlock(); + } + if (tpaAcceptCancellation != 0) { - player.sendMessage(_("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); + player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); } } user.sendMessage(_("requestSent", player.getDisplayName())); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java index 7af445c51..7f7d36413 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java @@ -1,47 +1,45 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import lombok.Cleanup; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandtpaall extends EssentialsCommand { - public Commandtpaall() - { - super("tpaall"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { if (sender instanceof Player) { - teleportAAllPlayers(server, sender, ess.getUser(sender)); + teleportAAllPlayers(sender, ess.getUser((Player)sender)); return; } throw new NotEnoughArgumentsException(); } - final User player = getPlayer(server, args, 0); - teleportAAllPlayers(server, sender, player); + final IUser player = getPlayer(args, 0); + teleportAAllPlayers(sender, player); } - private void teleportAAllPlayers(final Server server, final CommandSender sender, final User user) + private void teleportAAllPlayers(final CommandSender sender, final IUser user) { sender.sendMessage(_("teleportAAll")); for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); + @Cleanup + final IUser player = ess.getUser(onlinePlayer); + player.acquireReadLock(); if (user == player) { continue; } - if (!player.isTeleportEnabled()) + if (!player.getData().isTeleportEnabled()) { continue; } @@ -55,14 +53,25 @@ public class Commandtpaall extends EssentialsCommand player.requestTeleport(user, true); player.sendMessage(_("teleportHereRequest", user.getDisplayName())); player.sendMessage(_("typeTpaccept")); - if (ess.getSettings().getTpaAcceptCancellation() != 0) + int tpaAcceptCancellation = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } + finally + { + settings.unlock(); + } + if (tpaAcceptCancellation != 0) { - player.sendMessage(_("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); + player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); } } catch (Exception ex) { - ess.showError(sender, ex, getName()); + ess.getCommandHandler().showCommandError(sender, commandName, ex); } } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java index 9203f9015..8b7cb7b1b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java @@ -1,26 +1,29 @@ 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 com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import org.bukkit.OfflinePlayer; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtpaccept extends EssentialsCommand { - public Commandtpaccept() - { - super("tpaccept"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { + if (user.getTeleportRequester() == null) + { + throw new Exception(_("noPendingRequest")); + } - final User target = user.getTeleportRequest(); - - if (target == null || !target.isOnline()) + final IUser target = user.getTeleportRequester(); + if (target == null + || !target.isOnline() + || (user.isTeleportRequestHere() && !Permissions.TPAHERE.isAuthorized(target)) + || (!user.isTeleportRequestHere() && !Permissions.TPA.isAuthorized(target) && !Permissions.TPAALL.isAuthorized(target))) { throw new Exception(_("noPendingRequest")); } @@ -44,14 +47,25 @@ public class Commandtpaccept extends EssentialsCommand throw new Exception(_("noPendingRequest")); } - long timeout = ess.getSettings().getTpaAcceptCancellation(); - if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) + int tpaAcceptCancellation = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } + finally + { + settings.unlock(); + } + + if (tpaAcceptCancellation != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > tpaAcceptCancellation) { user.requestTeleport(null, false); throw new Exception(_("requestTimedOut")); } - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); if (user.isTpRequestHere()) { charge.isAffordableFor(user); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java index 9d389ecac..c32a14470 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java @@ -1,27 +1,25 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import lombok.Cleanup; public class Commandtpahere extends EssentialsCommand { - public Commandtpahere() - { - super("tpahere"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - final User player = getPlayer(server, args, 0); - if (!player.isTeleportEnabled()) + @Cleanup + final IUser player = getPlayer(args, 0); + player.acquireReadLock(); + if (!player.getData().isTeleportEnabled()) { throw new Exception(_("teleportDisabled", player.getDisplayName())); } @@ -33,9 +31,20 @@ public class Commandtpahere extends EssentialsCommand player.requestTeleport(user, true); player.sendMessage(_("teleportHereRequest", user.getDisplayName())); player.sendMessage(_("typeTpaccept")); - if (ess.getSettings().getTpaAcceptCancellation() != 0) + int tpaAcceptCancellation = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } + finally + { + settings.unlock(); + } + if (tpaAcceptCancellation != 0) { - player.sendMessage(_("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); + player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); } user.sendMessage(_("requestSent", player.getDisplayName())); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java index 6335a4a54..fb7efcdcb 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java @@ -1,8 +1,7 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; @@ -10,34 +9,29 @@ import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtpall extends EssentialsCommand { - public Commandtpall() - { - super("tpall"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { if (sender instanceof Player) { - teleportAllPlayers(server, sender, ess.getUser(sender)); + teleportAllPlayers(sender, ess.getUser((Player)sender)); return; } throw new NotEnoughArgumentsException(); } - final User player = getPlayer(server, args, 0); - teleportAllPlayers(server, sender, player); + final IUser player = getPlayer(args, 0); + teleportAllPlayers(sender, player); } - private void teleportAllPlayers(Server server, CommandSender sender, User user) + private void teleportAllPlayers(CommandSender sender, IUser user) { sender.sendMessage(_("teleportAll")); for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); + final IUser player = ess.getUser(onlinePlayer); if (user == player) { continue; @@ -53,7 +47,7 @@ public class Commandtpall extends EssentialsCommand } catch (Exception ex) { - ess.showError(sender, ex, getName()); + ess.getCommandHandler().showCommandError(sender, commandName, ex); } } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java index 92bba1054..15d3f7728 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java @@ -1,21 +1,15 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; public class Commandtpdeny extends EssentialsCommand { - public Commandtpdeny() - { - super("tpdeny"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - final User player = user.getTeleportRequest(); + final IUser player = user.getTeleportRequester(); if (player == null) { throw new Exception(_("noPendingRequest")); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java index 92eb87226..a995e31f4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java @@ -1,24 +1,21 @@ 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 com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; +import lombok.Cleanup; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtphere extends EssentialsCommand { - public Commandtphere() - { - super("tphere"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - final User player = getPlayer(server, args, 0); - if (!player.isTeleportEnabled()) + @Cleanup + final IUser player = getPlayer(args, 0); + player.acquireReadLock(); + if (!player.getData().isTeleportEnabled()) { throw new Exception(_("teleportDisabled", player.getDisplayName())); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java index 4d7ced478..56041fc3e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java @@ -1,20 +1,15 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtpo extends EssentialsCommand { - public Commandtpo() - { - super("tpo"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { switch (args.length) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java index 880c4e362..e27613b20 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java @@ -1,20 +1,15 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtpohere extends EssentialsCommand { - public Commandtpohere() - { - super("tpohere"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -22,7 +17,7 @@ public class Commandtpohere extends EssentialsCommand } //Just basically the old tphere command - final User player = getPlayer(server, args, 0, true); + final IUser player = getPlayer(args, 0, true); // Check if user is offline if (!player.isOnline()) @@ -37,7 +32,7 @@ public class Commandtpohere extends EssentialsCommand } // Verify permission - if (!player.isHidden() || user.isAuthorized("essentials.teleport.hidden")) + if (!player.isHidden() || Permissions.TELEPORT_HIDDEN.isAuthorized(user)) { player.getTeleport().now(user, false, TeleportCause.COMMAND); user.sendMessage(_("teleporting")); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java index 75910cd85..ca50a068d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java @@ -1,23 +1,17 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtppos extends EssentialsCommand { - public Commandtppos() - { - super("tppos"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 3) { @@ -36,7 +30,7 @@ public class Commandtppos extends EssentialsCommand { location.setPitch(Float.parseFloat(args[4])); } - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); charge.isAffordableFor(user); user.sendMessage(_("teleporting")); user.getTeleport().teleport(location, charge, TeleportCause.COMMAND); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java index 1fc4c2aa4..2c39271ac 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java @@ -1,19 +1,13 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; public class Commandtptoggle extends EssentialsCommand { - public Commandtptoggle() - { - super("tptoggle"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { user.sendMessage(user.toggleTeleportEnabled() ? _("teleportationEnabled") diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java index 6c2c15983..79bbecd29 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java @@ -1,22 +1,16 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.utils.LocationUtil; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.TreeType; public class Commandtree extends EssentialsCommand { - public Commandtree() - { - super("tree"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { TreeType tree; if (args.length < 1) @@ -60,8 +54,8 @@ public class Commandtree extends EssentialsCommand throw new NotEnoughArgumentsException(); } - final Location loc = Util.getTarget(user); - final Location safeLocation = Util.getSafeDestination(loc); + final Location loc = LocationUtil.getTarget(user); + final Location safeLocation = LocationUtil.getSafeDestination(loc); final boolean success = user.getWorld().generateTree(safeLocation, tree); if (success) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java index dda1475d0..101e09691 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java @@ -1,20 +1,15 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import lombok.Cleanup; import org.bukkit.command.CommandSender; public class Commandunban extends EssentialsCommand { - public Commandunban() - { - super("unban"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -23,7 +18,10 @@ public class Commandunban extends EssentialsCommand try { - final User player = getPlayer(server, args, 0, true); + @Cleanup + final IUser player = getPlayer(args, 0, true); + player.acquireWriteLock(); + player.getData().setBan(null); player.setBanned(false); sender.sendMessage(_("unbannedPlayer")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java index c539a596c..14d2c8ae6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java @@ -1,20 +1,15 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import lombok.Cleanup; import org.bukkit.command.CommandSender; public class Commandunbanip extends EssentialsCommand { - public Commandunbanip() - { - super("unbanip"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -22,8 +17,10 @@ public class Commandunbanip extends EssentialsCommand } try { - final User user = getPlayer(server, args, 0, true); - ess.getServer().unbanIP(user.getLastLoginAddress()); + @Cleanup + final IUser user = getPlayer(args, 0, true); + user.acquireReadLock(); + ess.getServer().unbanIP(user.getData().getIpAddress()); } catch (Exception ex) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java index beff6a77b..a6f6ae477 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java @@ -1,35 +1,34 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import com.earth2me.essentials.User; -import java.util.List; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.permissions.UnlimitedItemPermissions; import java.util.Locale; +import java.util.Set; +import lombok.Cleanup; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.inventory.ItemStack; public class Commandunlimited extends EssentialsCommand { - public Commandunlimited() - { - super("unlimited"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - User target = user; + @Cleanup + IUser target = user; - if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) + if (args.length > 1 && Permissions.UNLIMITED_OTHERS.isAuthorized(user)) { - target = getPlayer(server, args, 1); + target = getPlayer(args, 1); + target.acquireReadLock(); } if (args[0].equalsIgnoreCase("list")) @@ -39,16 +38,12 @@ public class Commandunlimited extends EssentialsCommand } else if (args[0].equalsIgnoreCase("clear")) { - final List<Integer> itemList = target.getUnlimited(); - - int index = 0; - while (itemList.size() > index) + //TODO: Fix this, the clear should always work, even when the player does not have permission. + final Set<Material> itemList = target.getData().getUnlimited(); + for(Material mat : itemList) { - final Integer item = itemList.get(index); - if (toggleUnlimited(user, target, item.toString()) == false) - { - index++; - } + toggleUnlimited(user, target, mat.name()); + } } else @@ -57,49 +52,44 @@ public class Commandunlimited extends EssentialsCommand } } - private String getList(final User target) + private String getList(final IUser target) { final StringBuilder output = new StringBuilder(); output.append(_("unlimitedItems")).append(" "); boolean first = true; - final List<Integer> items = target.getUnlimited(); + final Set<Material> items = target.getData().getUnlimited(); if (items.isEmpty()) { output.append(_("none")); } - for (Integer integer : items) + for (Material mater : items) { if (!first) { output.append(", "); } first = false; - final String matname = Material.getMaterial(integer).toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + final String matname = mater.name().toLowerCase(Locale.ENGLISH).replace("_", ""); output.append(matname); } return output.toString(); } - private Boolean toggleUnlimited(final User user, final User target, final String item) throws Exception + private Boolean toggleUnlimited(final IUser user, final IUser target, final String item) throws Exception { final ItemStack stack = ess.getItemDb().get(item, 1); stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2)); final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (ess.getSettings().permissionBasedItemSpawn() - && (!user.isAuthorized("essentials.unlimited.item-all") - && !user.isAuthorized("essentials.unlimited.item-" + itemname) - && !user.isAuthorized("essentials.unlimited.item-" + stack.getTypeId()) - && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) - && user.isAuthorized("essentials.unlimited.item-bucket")))) + if (!UnlimitedItemPermissions.getPermission(stack.getType()).isAuthorized(user)) { throw new Exception(_("unlimitedItemPermission", itemname)); } String message = "disableUnlimited"; Boolean enableUnlimited = false; - if (!target.hasUnlimited(stack)) + if (!target.getData().hasUnlimited(stack.getType())) { message = "enableUnlimited"; enableUnlimited = true; @@ -114,7 +104,8 @@ public class Commandunlimited extends EssentialsCommand user.sendMessage(_(message, itemname, target.getDisplayName())); } target.sendMessage(_(message, itemname, target.getDisplayName())); - target.setUnlimited(stack, enableUnlimited); + target.acquireWriteLock(); + target.getData().setUnlimited(stack.getType(), enableUnlimited); return true; } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java index 84df12900..a809c3c8d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java @@ -1,15 +1,16 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import com.earth2me.essentials.Warps; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.api.IWarps; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.permissions.WarpPermissions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; @@ -18,17 +19,12 @@ public class Commandwarp extends EssentialsCommand { private final static int WARPS_PER_PAGE = 20; - public Commandwarp() - { - super("warp"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length == 0 || args[0].matches("[0-9]+")) { - if (!user.isAuthorized("essentials.warp.list")) + if (!Permissions.WARP_LIST.isAuthorized(user)) { throw new Exception(_("warpListPermission")); } @@ -37,31 +33,31 @@ public class Commandwarp extends EssentialsCommand } if (args.length > 0) { - User otherUser = null; - if (args.length == 2 && user.isAuthorized("essentials.warp.otherplayers")) + IUser otherUser = null; + if (args.length == 2 && Permissions.WARP_OTHERS.isAuthorized(user)) { otherUser = ess.getUser(server.getPlayer(args[1])); if (otherUser == null) { throw new Exception(_("playerNotFound")); } - warpUser(user, otherUser, args[0]); + warpUser(otherUser, args[0]); throw new NoChargeException(); } - warpUser(user, user, args[0]); + warpUser(user, args[0]); throw new NoChargeException(); } } @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2 || args[0].matches("[0-9]+")) { warpList(sender, args); throw new NoChargeException(); } - User otherUser = ess.getUser(server.getPlayer(args[1])); + IUser otherUser = ess.getUser(server.getPlayer(args[1])); if (otherUser == null) { throw new Exception(_("playerNotFound")); @@ -74,20 +70,20 @@ public class Commandwarp extends EssentialsCommand //TODO: Use one of the new text classes, like /help ? private void warpList(final CommandSender sender, final String[] args) throws Exception { - final Warps warps = ess.getWarps(); + final IWarps warps = ess.getWarps(); if (warps.isEmpty()) { throw new Exception(_("noWarpsDefined")); } - final List<String> warpNameList = new ArrayList<String>(warps.getWarpNames()); + final List<String> warpNameList = new ArrayList<String>(warps.getList()); - if (sender instanceof User) + if (sender instanceof IUser) { final Iterator<String> iterator = warpNameList.iterator(); while (iterator.hasNext()) { final String warpName = iterator.next(); - if (ess.getSettings().getPerWarpPermission() && !((User)sender).isAuthorized("essentials.warp." + warpName)) + if (!WarpPermissions.getPermission(warpName).isAuthorized(sender)) { iterator.remove(); } @@ -113,17 +109,18 @@ public class Commandwarp extends EssentialsCommand } } - private void warpUser(final User owner, final User user, final String name) throws Exception + private void warpUser(final IUser user, final String name) throws Exception { final Trade chargeWarp = new Trade("warp-" + name.toLowerCase(Locale.ENGLISH).replace('_', '-'), ess); final Trade chargeCmd = new Trade(this.getName(), ess); final double fullCharge = chargeWarp.getCommandCost(user) + chargeCmd.getCommandCost(user); final Trade charge = new Trade(fullCharge, ess); - charge.isAffordableFor(owner); - if (ess.getSettings().getPerWarpPermission() && !owner.isAuthorized("essentials.warp." + name)) + charge.isAffordableFor(user); + if (WarpPermissions.getPermission(name).isAuthorized(user)) { - throw new Exception(_("warpUsePermission")); + user.getTeleport().warp(name, charge, TeleportCause.COMMAND); + return; } - user.getTeleport().warp(name, charge, TeleportCause.COMMAND); + throw new Exception(_("warpUsePermission")); } }
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandweather.java b/Essentials/src/com/earth2me/essentials/commands/Commandweather.java index 1229c9ee4..2df5b1eac 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandweather.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandweather.java @@ -1,22 +1,16 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; import org.bukkit.World; import org.bukkit.command.CommandSender; public class Commandweather extends EssentialsCommand { - public Commandweather() - { - super("weather"); - } - //TODO: Remove duplication @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -45,11 +39,11 @@ public class Commandweather extends EssentialsCommand //TODO: Translate these @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) //running from console means inserting a world arg before other args { - throw new Exception("When running from console, usage is: /" + commandLabel + " <world> <storm/sun> [duration]"); + throw new Exception("When running from console, usage is: /" + commandName + " <world> <storm/sun> [duration]"); } final boolean isStorm = args[1].equalsIgnoreCase("storm"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java index 6c7919163..cc3a876ec 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java @@ -1,24 +1,23 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.user.UserData; +import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.craftbukkit.SetExpFix; import java.util.Locale; -import org.bukkit.Server; +import lombok.Cleanup; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandwhois extends EssentialsCommand { - public Commandwhois() - { - super("whois"); - } - @Override - public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { @@ -27,7 +26,7 @@ public class Commandwhois extends EssentialsCommand boolean showhidden = false; if (sender instanceof Player) { - if (ess.getUser(sender).isAuthorized("essentials.list.hidden")) + if (Permissions.LIST_HIDDEN.isAuthorized(sender)) { showhidden = true; } @@ -37,15 +36,21 @@ public class Commandwhois extends EssentialsCommand showhidden = true; } final String whois = args[0].toLowerCase(Locale.ENGLISH); - final int prefixLength = Util.stripFormat(ess.getSettings().getNicknamePrefix()).length(); + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final int prefixLength = Util.stripColor(settings.getData().getChat().getNicknamePrefix()).length(); for (Player onlinePlayer : server.getOnlinePlayers()) { - final User user = ess.getUser(onlinePlayer); + @Cleanup + final IUser user = ess.getUser(onlinePlayer); + if (user.isHidden() && !showhidden) { continue; } - final String nickName = Util.stripFormat(user.getNickname()); + user.acquireReadLock(); + final String nickName = Util.stripFormat(user.getData().getNickname()); if (!whois.equalsIgnoreCase(nickName) && !whois.substring(prefixLength).equalsIgnoreCase(nickName) && !whois.equalsIgnoreCase(user.getName())) @@ -61,22 +66,19 @@ public class Commandwhois extends EssentialsCommand sender.sendMessage(_("whoisGod", (user.isGodModeEnabled() ? _("true") : _("false")))); sender.sendMessage(_("whoisGamemode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)))); sender.sendMessage(_("whoisLocation", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); - if (!ess.getSettings().isEcoDisabled()) - { - sender.sendMessage(_("whoisMoney", Util.displayCurrency(user.getMoney(), ess))); - } - sender.sendMessage(_("whoisJail", (user.isJailed() - ? user.getJailTimeout() > 0 - ? Util.formatDateDiff(user.getJailTimeout()) + sender.sendMessage(_("whoisMoney", Util.displayCurrency(user.getMoney(), ess))); + sender.sendMessage(_("whoisJail", (user.getData().isJailed() + ? user.getTimestamp(UserData.TimestampType.JAIL) > 0 + ? DateUtil.formatDateDiff(user.getTimestamp(UserData.TimestampType.JAIL)) : _("true") : _("false")))); - sender.sendMessage(user.isAfk() + sender.sendMessage(user.getData().isAfk() ? _("whoisStatusAway") : _("whoisStatusAvailable")); sender.sendMessage(_("whoisIPAddress", user.getAddress().getAddress().toString())); - final String location = user.getGeoLocation(); + final String location = user.getData().getGeolocation(); if (location != null - && (sender instanceof Player ? ess.getUser(sender).isAuthorized("essentials.geoip.show") : true)) + && Permissions.GEOIP_SHOW.isAuthorized(sender)) { sender.sendMessage(_("whoisGeoLocation", location)); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java index 647115d66..9e2c1b08d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java @@ -1,24 +1,19 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.WorldPermissions; 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 { - public Commandworld() - { - super("world"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { World world; @@ -54,9 +49,11 @@ public class Commandworld extends EssentialsCommand } } - if (ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.world." + world.getName())) + + if (!WorldPermissions.getPermission(world.getName()).isAuthorized(user)) { - throw new Exception(_("noPerm", "essentials.world." + world.getName())); + user.sendMessage(_("invalidWorld")); //TODO: Make a "world teleport denied" translation + throw new NoChargeException(); } double factor; @@ -76,7 +73,7 @@ public class Commandworld extends EssentialsCommand final Location loc = user.getLocation(); final Location target = new Location(world, loc.getBlockX() * factor + .5, loc.getBlockY(), loc.getBlockZ() * factor + .5); - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); charge.isAffordableFor(user); user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); throw new NoChargeException(); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java index c8573ba25..0e1ec1dc1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java @@ -1,24 +1,18 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IUser; import java.util.Locale; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.inventory.ItemStack; public class Commandworth extends EssentialsCommand { - public Commandworth() - { - super("worth"); - } - //TODO: Remove duplication @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { ItemStack iStack = user.getInventory().getItemInHand(); int amount = iStack.getAmount(); @@ -62,7 +56,7 @@ public class Commandworth extends EssentialsCommand } @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java index 6bc0649e9..e3b25177a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java @@ -1,34 +1,37 @@ 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.Trade; -import com.earth2me.essentials.User; +import com.earth2me.essentials.economy.Trade; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IEssentialsModule; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.AbstractSuperpermsPermission; import java.util.List; import java.util.logging.Logger; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; -public abstract class EssentialsCommand implements IEssentialsCommand +public abstract class EssentialsCommand extends AbstractSuperpermsPermission implements IEssentialsCommand { - private final transient String name; + protected transient String commandName; protected transient IEssentials ess; protected transient IEssentialsModule module; - protected final static Logger logger = Logger.getLogger("Minecraft"); + protected transient Server server; + protected transient Logger logger; + private transient String permission; + private transient Permission bukkitPerm; - protected EssentialsCommand(final String name) - { - this.name = name; - } - - @Override - public void setEssentials(final IEssentials ess) + public void init(final IEssentials ess, final String commandName) { this.ess = ess; + this.logger = ess.getLogger(); + this.server = ess.getServer(); + this.commandName = commandName; + this.permission = "essentials." + commandName; } @Override @@ -37,18 +40,12 @@ public abstract class EssentialsCommand implements IEssentialsCommand this.module = module; } - @Override - public String getName() - { - return name; - } - - protected User getPlayer(final Server server, final String[] args, final int pos) throws NoSuchFieldException, NotEnoughArgumentsException + protected IUser getPlayer(final String[] args, final int pos) throws NoSuchFieldException, NotEnoughArgumentsException { - return getPlayer(server, args, pos, false); + return getPlayer(args, pos, false); } - protected User getPlayer(final Server server, final String[] args, final int pos, final boolean getOffline) throws NoSuchFieldException, NotEnoughArgumentsException + protected IUser getPlayer(final String[] args, final int pos, final boolean getOffline) throws NoSuchFieldException, NotEnoughArgumentsException { if (args.length <= pos) { @@ -58,7 +55,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { throw new NoSuchFieldException(_("playerNotFound")); } - final User user = ess.getUser(args[pos]); + final IUser user = ess.getUser(args[pos]); if (user != null) { if (!getOffline && (!user.isOnline() || user.isHidden())) @@ -73,13 +70,13 @@ public abstract class EssentialsCommand implements IEssentialsCommand { for (Player player : matches) { - final User userMatch = ess.getUser(player); + final IUser userMatch = ess.getUser(player); if (userMatch.getDisplayName().startsWith(args[pos]) && (getOffline || !userMatch.isHidden())) { return userMatch; } } - final User userMatch = ess.getUser(matches.get(0)); + final IUser userMatch = ess.getUser(matches.get(0)); if (getOffline || !userMatch.isHidden()) { return userMatch; @@ -89,28 +86,28 @@ public abstract class EssentialsCommand implements IEssentialsCommand } @Override - public final void run(final Server server, final User user, final String commandLabel, final Command cmd, final String[] args) throws Exception + public final void run(final IUser user, final Command cmd, final String commandLabel, final String[] args) throws Exception { - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); charge.isAffordableFor(user); - run(server, user, commandLabel, args); + run(user, commandLabel, args); charge.charge(user); } - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - run(server, (CommandSender)user.getBase(), commandLabel, args); + run((CommandSender)user.getBase(), commandLabel, args); } @Override - public final void run(final Server server, final CommandSender sender, final String commandLabel, final Command cmd, final String[] args) throws Exception + public final void run(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) throws Exception { - run(server, sender, commandLabel, args); + run(sender, commandLabel, args); } - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { - throw new Exception(_("onlyPlayers", commandLabel)); + throw new Exception(_("onlyPlayers", commandName)); } public static String getFinalArg(final String[] args, final int start) @@ -126,4 +123,10 @@ public abstract class EssentialsCommand implements IEssentialsCommand } return bldr.toString(); } + + @Override + public String getPermission() + { + return permission; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommandHandler.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommandHandler.java new file mode 100644 index 000000000..f45a55a3f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommandHandler.java @@ -0,0 +1,316 @@ +package com.earth2me.essentials.commands; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.*; +import com.earth2me.essentials.commands.EssentialsCommand; +import com.earth2me.essentials.commands.IEssentialsCommand; +import com.earth2me.essentials.commands.NoChargeException; +import com.earth2me.essentials.commands.NotEnoughArgumentsException; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.command.PluginCommandYamlParser; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class EssentialsCommandHandler implements ICommandHandler +{ + private final transient ClassLoader classLoader; + private final transient String commandPath; + private final transient String permissionPrefix; + private final transient IEssentialsModule module; + private static final transient Logger LOGGER = Bukkit.getLogger(); + private final transient Map<String, List<PluginCommand>> altcommands = new HashMap<String, List<PluginCommand>>(); + private final transient Map<String, String> disabledList = new HashMap<String, String>(); + private final transient Map<String, IEssentialsCommand> commands = new HashMap<String, IEssentialsCommand>(); + private final transient IEssentials ess; + + public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentials ess) + { + this(classLoader, commandPath, permissionPrefix, null, ess); + } + + public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module, IEssentials ess) + { + this.classLoader = classLoader; + this.commandPath = commandPath; + this.permissionPrefix = permissionPrefix; + this.module = module; + this.ess = ess; + for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) + { + if (plugin.isEnabled()) + { + addPlugin(plugin); + } + } + } + + @Override + public boolean handleCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) + { + boolean disabled = false; + boolean overridden = false; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + disabled = settings.getData().getCommands().isDisabled(command.getName()); + overridden = !disabled || settings.getData().getCommands().isOverridden(command.getName()); + } + finally + { + settings.unlock(); + } + // Allow plugins to override the command via onCommand + if (!overridden && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) + { + final PluginCommand pc = getAlternative(commandLabel); + if (pc != null) + { + + executed(commandLabel, pc.getLabel()); + try + { + return pc.execute(sender, commandLabel, args); + } + catch (final Exception ex) + { + final ArrayList<StackTraceElement> elements = new ArrayList<StackTraceElement>(Arrays.asList(ex.getStackTrace())); + elements.remove(0); + final ArrayList<StackTraceElement> toRemove = new ArrayList<StackTraceElement>(); + for (final StackTraceElement e : elements) + { + if (e.getClassName().equals("com.earth2me.essentials.Essentials")) + { + toRemove.add(e); + } + } + elements.removeAll(toRemove); + final StackTraceElement[] trace = elements.toArray(new StackTraceElement[elements.size()]); + ex.setStackTrace(trace); + ex.printStackTrace(); + sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command"); + return true; + } + } + } + + try + { + IUser user = null; + if (sender instanceof Player) + { + user = ess.getUser((Player)sender); + LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0))); + } + + // Check for disabled commands + if (disabled) + { + return true; + } + + final String commandName = command.getName().toLowerCase(Locale.ENGLISH); + IEssentialsCommand cmd = commands.get(commandName); + if (cmd == null) + { + try + { + cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + commandName).newInstance(); + cmd.init(ess, commandName); + cmd.setEssentialsModule(module); + commands.put(commandName, cmd); + } + catch (Exception ex) + { + sender.sendMessage(_("commandNotLoaded", commandName)); + LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandName), ex); + return true; + } + } + + // Check authorization + if (sender != null && !cmd.isAuthorized(sender)) + { + LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName())); + user.sendMessage(_("noAccessCommand")); + return true; + } + + // Run the command + try + { + if (user == null) + { + cmd.run(sender, command, commandLabel, args); + } + else + { + user.acquireReadLock(); + try + { + cmd.run(user, command, commandLabel, args); + } + finally + { + user.unlock(); + } + } + return true; + } + catch (NoChargeException ex) + { + return true; + } + catch (NotEnoughArgumentsException ex) + { + sender.sendMessage(command.getDescription()); + sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); + if (!ex.getMessage().isEmpty()) + { + sender.sendMessage(ex.getMessage()); + } + return true; + } + catch (Throwable ex) + { + showCommandError(sender, commandLabel, ex); + return true; + } + } + catch (Throwable ex) + { + LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex); + return true; + } + } + + @Override + public void showCommandError(final CommandSender sender, final String commandLabel, final Throwable exception) + { + sender.sendMessage(_("errorWithMessage", exception.getMessage())); + if (ess.getSettings().isDebug()) + { + LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception); + } + } + + @Override + public void onReload() + { + } + + public final void addPlugin(final Plugin plugin) + { + if (plugin.getDescription().getMain().contains("com.earth2me.essentials")) + { + return; + } + final List<Command> commands = PluginCommandYamlParser.parse(plugin); + final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH); + + for (Command command : commands) + { + final PluginCommand pc = (PluginCommand)command; + final List<String> labels = new ArrayList<String>(pc.getAliases()); + labels.add(pc.getName()); + + PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH)); + if (reg == null) + { + reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH)); + } + if (reg == null || !reg.getPlugin().equals(plugin)) + { + continue; + } + for (String label : labels) + { + List<PluginCommand> plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH)); + if (plugincommands == null) + { + plugincommands = new ArrayList<PluginCommand>(); + altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands); + } + boolean found = false; + for (PluginCommand pc2 : plugincommands) + { + if (pc2.getPlugin().equals(plugin)) + { + found = true; + } + } + if (!found) + { + plugincommands.add(reg); + } + } + } + } + + public void removePlugin(final Plugin plugin) + { + final Iterator<Map.Entry<String, List<PluginCommand>>> iterator = altcommands.entrySet().iterator(); + while (iterator.hasNext()) + { + final Map.Entry<String, List<PluginCommand>> entry = iterator.next(); + final Iterator<PluginCommand> pcIterator = entry.getValue().iterator(); + while (pcIterator.hasNext()) + { + final PluginCommand pc = pcIterator.next(); + if (pc.getPlugin() == null || pc.getPlugin().equals(plugin)) + { + pcIterator.remove(); + } + } + if (entry.getValue().isEmpty()) + { + iterator.remove(); + } + } + } + + public PluginCommand getAlternative(final String label) + { + final List<PluginCommand> commands = altcommands.get(label); + if (commands == null || commands.isEmpty()) + { + return null; + } + if (commands.size() == 1) + { + return commands.get(0); + } + // return the first command that is not an alias + for (PluginCommand command : commands) + { + if (command.getName().equalsIgnoreCase(label)) + { + return command; + } + } + // return the first alias + return commands.get(0); + } + + public void executed(final String label, final String 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 disabledList; + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java index 439c14d70..b4c1b40f8 100644 --- a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java @@ -1,24 +1,22 @@ 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 com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IEssentialsModule; +import com.earth2me.essentials.api.IPermission; +import com.earth2me.essentials.api.IUser; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -public interface IEssentialsCommand +public interface IEssentialsCommand extends IPermission { - String getName(); - - void run(Server server, User user, String commandLabel, Command cmd, String[] args) + void run(IUser user, Command cmd, String commandLabel, String[] args) throws Exception; - void run(Server server, CommandSender sender, String commandLabel, Command cmd, String[] args) + void run(CommandSender sender, Command cmd, String commandLabel, String[] args) throws Exception; - void setEssentials(IEssentials ess); + void init(IEssentials ess, String commandLabel); void setEssentialsModule(IEssentialsModule module); } diff --git a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java b/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java index bfba73818..c5b592c2a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java +++ b/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n._; public class WarpNotFoundException extends Exception { @@ -14,3 +13,5 @@ public class WarpNotFoundException extends Exception super(message); } } + + diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java b/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java deleted file mode 100644 index ce617fcd5..000000000 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java +++ /dev/null @@ -1,672 +0,0 @@ -package com.earth2me.essentials.craftbukkit; - -import java.io.File; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import org.bukkit.*; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; -import org.bukkit.entity.*; -import org.bukkit.generator.BlockPopulator; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.inventory.ItemStack; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.plugin.Plugin; -import org.bukkit.util.Vector; - - -public class FakeWorld implements World -{ - private final String name; - private final Environment env; - - public FakeWorld(String string, Environment environment) - { - this.name = string; - this.env = environment; - } - - @Override - public Block getBlockAt(int i, int i1, int i2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Block getBlockAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getBlockTypeIdAt(int i, int i1, int i2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getBlockTypeIdAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getHighestBlockYAt(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getHighestBlockYAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Chunk getChunkAt(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Chunk getChunkAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Chunk getChunkAt(Block block) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isChunkLoaded(Chunk chunk) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Chunk[] getLoadedChunks() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void loadChunk(Chunk chunk) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isChunkLoaded(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void loadChunk(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean loadChunk(int i, int i1, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunk(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunk(int i, int i1, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunk(int i, int i1, boolean bln, boolean bln1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunkRequest(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunkRequest(int i, int i1, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean regenerateChunk(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean refreshChunk(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Item dropItem(Location lctn, ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Item dropItemNaturally(Location lctn, ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Arrow spawnArrow(Location lctn, Vector vector, float f, float f1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean generateTree(Location lctn, TreeType tt) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean generateTree(Location lctn, TreeType tt, BlockChangeDelegate bcd) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public LivingEntity spawnCreature(Location lctn, CreatureType ct) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public LightningStrike strikeLightning(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public LightningStrike strikeLightningEffect(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List<Entity> getEntities() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List<LivingEntity> getLivingEntities() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List<Player> getPlayers() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getName() - { - return name; - } - - @Override - public Location getSpawnLocation() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean setSpawnLocation(int i, int i1, int i2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getTime() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTime(long l) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getFullTime() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setFullTime(long l) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasStorm() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setStorm(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getWeatherDuration() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setWeatherDuration(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isThundering() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setThundering(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getThunderDuration() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setThunderDuration(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Environment getEnvironment() - { - return env; - } - - @Override - public long getSeed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getPVP() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setPVP(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void save() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(double d, double d1, double d2, float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(Location lctn, float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ChunkGenerator getGenerator() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List<BlockPopulator> getPopulators() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playEffect(Location lctn, Effect effect, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playEffect(Location lctn, Effect effect, int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(double d, double d1, double d2, float f, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(Location lctn, float f, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public <T extends Entity> T spawn(Location lctn, Class<T> type) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ChunkSnapshot getEmptyChunkSnapshot(int i, int i1, boolean bln, boolean bln1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setSpawnFlags(boolean bln, boolean bln1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getAllowAnimals() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getAllowMonsters() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public UUID getUID() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Block getHighestBlockAt(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Block getHighestBlockAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Biome getBiome(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public double getTemperature(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public double getHumidity(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunk(Chunk chunk) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getMaxHeight() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getKeepSpawnInMemory() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setKeepSpawnInMemory(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isAutoSave() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setAutoSave(boolean bln) - { - 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() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public File getWorldFolder() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public <T extends Entity> Collection<T> getEntitiesByClass(Class<T>... types) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public WorldType getWorldType() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set<String> getListeningPluginChannels() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean canGenerateStructures() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getTicksPerAnimalSpawns() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTicksPerAnimalSpawns(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getTicksPerMonsterSpawns() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTicksPerMonsterSpawns(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public <T extends Entity> Collection<T> getEntitiesByClass(Class<T> type) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Collection<Entity> getEntitiesByClasses(Class<?>... types) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public LivingEntity spawnCreature(Location arg0, EntityType arg1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public <T> void playEffect(Location lctn, Effect effect, T t) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public <T> void playEffect(Location lctn, Effect effect, T t, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setMetadata(String string, MetadataValue mv) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List<MetadataValue> getMetadata(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasMetadata(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removeMetadata(String string, Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setBiome(int arg0, int arg1, Biome arg2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getMonsterSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setMonsterSpawnLimit(int arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getAnimalSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setAnimalSpawnLimit(int arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getWaterAnimalSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setWaterAnimalSpawnLimit(int arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/Economy.java b/Essentials/src/com/earth2me/essentials/economy/Economy.java new file mode 100644 index 000000000..12bc9414c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/economy/Economy.java @@ -0,0 +1,207 @@ +package com.earth2me.essentials.economy; + +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.*; +import com.earth2me.essentials.permissions.Permissions; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class Economy implements IEconomy +{ + private final IEssentials ess; + private final MoneyHolder npcs; + + public Economy(IEssentials ess) + { + this.ess = ess; + this.npcs = new MoneyHolder(ess); + } + + private double getNPCBalance(String name) throws UserDoesNotExistException + { + npcs.acquireReadLock(); + try + { + Map<String, Double> balances = npcs.getData().getBalances(); + if (balances == null) + { + throw new UserDoesNotExistException(name); + } + Double balance = npcs.getData().getBalances().get(name.toLowerCase(Locale.ENGLISH)); + if (balance == null) + { + throw new UserDoesNotExistException(name); + } + return balance; + } + finally + { + npcs.unlock(); + } + } + + private void setNPCBalance(String name, double balance, boolean checkExistance) throws UserDoesNotExistException + { + npcs.acquireWriteLock(); + try + { + Map<String, Double> balances = npcs.getData().getBalances(); + if (balances == null) + { + balances = new HashMap<String, Double>(); + npcs.getData().setBalances(balances); + } + if (checkExistance && !balances.containsKey(name.toLowerCase(Locale.ENGLISH))) + { + throw new UserDoesNotExistException(name); + } + balances.put(name.toLowerCase(Locale.ENGLISH), balance); + } + finally + { + npcs.unlock(); + } + } + + private double getStartingBalance() + { + double startingBalance = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + startingBalance = settings.getData().getEconomy().getStartingBalance(); + } + finally + { + settings.unlock(); + } + return startingBalance; + } + + @Override + public void onReload() + { + this.npcs.onReload(false); + } + + @Override + public double getMoney(String name) throws UserDoesNotExistException + { + IUser user = ess.getUser(name); + if (user == null) + { + return getNPCBalance(name); + } + return user.getMoney(); + } + + @Override + public void setMoney(String name, double balance) throws NoLoanPermittedException, UserDoesNotExistException + { + IUser user = ess.getUser(name); + if (user == null) + { + setNPCBalance(name, balance, true); + return; + } + if (balance < 0.0 && !Permissions.ECO_LOAN.isAuthorized(user)) + { + throw new NoLoanPermittedException(); + } + user.setMoney(balance); + } + + @Override + public void resetBalance(String name) throws NoLoanPermittedException, UserDoesNotExistException + { + setMoney(name, getStartingBalance()); + } + + @Override + public String format(double amount) + { + return Util.displayCurrency(amount, ess); + } + + @Override + public boolean playerExists(String name) + { + try + { + getMoney(name); + return true; + } + catch (UserDoesNotExistException ex) + { + return false; + } + } + + @Override + public boolean isNPC(String name) throws UserDoesNotExistException + { + boolean result = ess.getUser(name) == null; + if (result) + { + getNPCBalance(name); + } + return result; + } + + @Override + public boolean createNPC(String name) + { + try + { + if (isNPC(name)) + { + + setNPCBalance(name, getStartingBalance(), false); + return true; + } + } + catch (UserDoesNotExistException ex) + { + try + { + setNPCBalance(name, getStartingBalance(), false); + return true; + } + catch (UserDoesNotExistException ex1) + { + //This should never happen! + } + } + return false; + } + + @Override + public void removeNPC(String name) throws UserDoesNotExistException + { + npcs.acquireWriteLock(); + try + { + Map<String, Double> balances = npcs.getData().getBalances(); + if (balances == null) + { + balances = new HashMap<String, Double>(); + npcs.getData().setBalances(balances); + } + if (balances.containsKey(name.toLowerCase(Locale.ENGLISH))) + { + balances.remove(name.toLowerCase(Locale.ENGLISH)); + } + else + { + throw new UserDoesNotExistException(name); + } + } + finally + { + npcs.unlock(); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/economy/Money.java b/Essentials/src/com/earth2me/essentials/economy/Money.java new file mode 100644 index 000000000..ff081e609 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/economy/Money.java @@ -0,0 +1,17 @@ +package com.earth2me.essentials.economy; + +import com.earth2me.essentials.storage.MapValueType; +import com.earth2me.essentials.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Money implements StorageObject +{ + @MapValueType(Double.class) + private Map<String, Double> balances = new HashMap<String, Double>(); +} diff --git a/Essentials/src/com/earth2me/essentials/economy/MoneyHolder.java b/Essentials/src/com/earth2me/essentials/economy/MoneyHolder.java new file mode 100644 index 000000000..179e09210 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/economy/MoneyHolder.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.economy; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; + + +public class MoneyHolder extends AsyncStorageObjectHolder<Money> +{ + public MoneyHolder(IEssentials ess) + { + super(ess, Money.class); + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.getDataFolder(), "economy_npcs.yml"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/Trade.java b/Essentials/src/com/earth2me/essentials/economy/Trade.java index 3d3f36d8c..f9812a2f9 100644 --- a/Essentials/src/com/earth2me/essentials/Trade.java +++ b/Essentials/src/com/earth2me/essentials/economy/Trade.java @@ -1,8 +1,14 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.economy; +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.ChargeException; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; import com.earth2me.essentials.craftbukkit.SetExpFix; -import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.permissions.NoCommandCostPermissions; +import com.earth2me.essentials.permissions.Permissions; import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -12,6 +18,7 @@ import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; +import lombok.Cleanup; import org.bukkit.Location; import org.bukkit.entity.Item; import org.bukkit.inventory.ItemStack; @@ -65,6 +72,7 @@ public class Trade { if (getMoney() != null && getMoney() > 0 + && !Permissions.ECO_LOAN.isAuthorized(user)) && !user.canAfford(getMoney())) { throw new ChargeException(_("notEnoughMoney")); @@ -76,10 +84,15 @@ public class Trade throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); } - double money; + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (command != null && !command.isEmpty() - && 0 < (money = getCommandCost(user)) - && !user.canAfford(money)) + && !NoCommandCostPermissions.getPermission(command).isAuthorized(user) + && mon < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) + && 0 < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) + && !Permissions.ECO_LOAN.isAuthorized(user)) { throw new ChargeException(_("notEnoughMoney")); } @@ -109,21 +122,21 @@ public class Trade { final Map<Integer, ItemStack> leftOver = InventoryWorkaround.addItem(user.getInventory(), true, getItemStack()); final Location loc = user.getLocation(); - for (ItemStack itemStack : leftOver.values()) + for (ItemStack dropStack : leftOver.values()) { - final int maxStackSize = itemStack.getType().getMaxStackSize(); - final int stacks = itemStack.getAmount() / maxStackSize; - final int leftover = itemStack.getAmount() % maxStackSize; + final int maxStackSize = dropStack.getType().getMaxStackSize(); + final int stacks = dropStack.getAmount() / maxStackSize; + final int leftover = dropStack.getAmount() % maxStackSize; final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)]; for (int i = 0; i < stacks; i++) { - final ItemStack stack = itemStack.clone(); + final ItemStack stack = dropStack.clone(); stack.setAmount(maxStackSize); itemStacks[i] = loc.getWorld().dropItem(loc, stack); } if (leftover > 0) { - final ItemStack stack = itemStack.clone(); + final ItemStack stack = dropStack.clone(); stack.setAmount(leftover); itemStacks[stacks] = loc.getWorld().dropItem(loc, stack); } @@ -161,9 +174,13 @@ public class Trade InventoryWorkaround.removeItem(user.getInventory(), true, true, getItemStack()); user.updateInventory(); } - if (command != null) + if (command != null && !command.isEmpty() + && !NoCommandCostPermissions.getPermission(command).isAuthorized(user)) { - final double cost = getCommandCost(user); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final double cost = settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); if (!user.canAfford(cost) && cost > 0) { throw new ChargeException(_("notEnoughMoney")); @@ -215,8 +232,10 @@ public class Trade public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess) { - if ((loc == null && !ess.getSettings().isEcoLogUpdateEnabled()) - || (loc != null && !ess.getSettings().isEcoLogEnabled())) + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getEconomy().isLogEnabled()) { return; } @@ -256,7 +275,7 @@ public class Trade { sb.append(charge.getMoney()).append(","); sb.append("money").append(","); - sb.append(ess.getSettings().getCurrencySymbol()); + sb.append(settings.getData().getEconomy().getCurrencySymbol()); } if (charge.getExperience() != null) { @@ -287,7 +306,7 @@ public class Trade { sb.append(pay.getMoney()).append(","); sb.append("money").append(","); - sb.append(ess.getSettings().getCurrencySymbol()); + sb.append(settings.getData().getEconomy().getCurrencySymbol()); } if (pay.getExperience() != null) { diff --git a/Essentials/src/com/earth2me/essentials/settings/Worth.java b/Essentials/src/com/earth2me/essentials/economy/Worth.java index 707f907cf..c8f6a39ae 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Worth.java +++ b/Essentials/src/com/earth2me/essentials/economy/Worth.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.settings; +package com.earth2me.essentials.economy; import com.earth2me.essentials.storage.EnchantmentLevel; import com.earth2me.essentials.storage.MapKeyType; @@ -9,7 +9,6 @@ import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; import org.bukkit.material.MaterialData; diff --git a/Essentials/src/com/earth2me/essentials/economy/WorthHolder.java b/Essentials/src/com/earth2me/essentials/economy/WorthHolder.java new file mode 100644 index 000000000..598c22c4c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/economy/WorthHolder.java @@ -0,0 +1,86 @@ +package com.earth2me.essentials.economy; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IWorth; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import com.earth2me.essentials.storage.EnchantmentLevel; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.MaterialData; + + +public class WorthHolder extends AsyncStorageObjectHolder<com.earth2me.essentials.economy.Worth> implements IWorth +{ + public WorthHolder(final IEssentials ess) + { + super(ess, com.earth2me.essentials.economy.Worth.class); + onReload(false); + } + + @Override + public double getPrice(final ItemStack itemStack) + { + this.acquireReadLock(); + try + { + final Map<MaterialData, Double> prices = this.getData().getSell(); + if (prices == null || itemStack == null) + { + return Double.NaN; + } + final Double basePrice = prices.get(itemStack.getData()); + if (basePrice == null || Double.isNaN(basePrice)) + { + return Double.NaN; + } + double multiplier = 1.0; + if (itemStack.getType().getMaxDurability() > 0) { + multiplier *= (double)itemStack.getDurability() / (double)itemStack.getType().getMaxDurability(); + } + if (itemStack.getEnchantments() != null && !itemStack.getEnchantments().isEmpty()) + { + final Map<EnchantmentLevel, Double> enchantmentMultipliers = this.getData().getEnchantmentMultiplier(); + if (enchantmentMultipliers != null) + { + for (Map.Entry<Enchantment, Integer> entry : itemStack.getEnchantments().entrySet()) + { + final Double enchMult = enchantmentMultipliers.get(new EnchantmentLevel(entry.getKey(), entry.getValue())); + if (enchMult != null) + { + multiplier *= enchMult; + } + } + } + } + return basePrice * multiplier; + } + finally + { + this.unlock(); + } + } + + @Override + public void setPrice(final ItemStack itemStack, final double price) + { + acquireWriteLock(); + try { + if (getData().getSell() == null) { + getData().setSell(new HashMap<MaterialData, Double>()); + } + getData().getSell().put(itemStack.getData(), price); + } finally { + unlock(); + } + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.getDataFolder(), "worth.yml"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/register/payment/Method.java b/Essentials/src/com/earth2me/essentials/economy/register/Method.java index c4c9d401a..5866066eb 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/Method.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/Method.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.register.payment; +package com.earth2me.essentials.economy.register; import org.bukkit.plugin.Plugin; diff --git a/Essentials/src/com/earth2me/essentials/register/payment/Methods.java b/Essentials/src/com/earth2me/essentials/economy/register/Methods.java index f8729923e..eb3138473 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/Methods.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/Methods.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.register.payment; +package com.earth2me.essentials.economy.register; import java.util.HashSet; import java.util.Set; @@ -45,14 +45,14 @@ public class Methods */ private static void _init() { - addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo6()); - addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo5()); - addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo4()); - addMethod("BOSEconomy", new com.earth2me.essentials.register.payment.methods.BOSE6()); - addMethod("BOSEconomy", new com.earth2me.essentials.register.payment.methods.BOSE7()); - addMethod("Currency", new com.earth2me.essentials.register.payment.methods.MCUR()); + addMethod("iConomy", new com.earth2me.essentials.economy.register.methods.iCo6()); + addMethod("iConomy", new com.earth2me.essentials.economy.register.methods.iCo5()); + addMethod("iConomy", new com.earth2me.essentials.economy.register.methods.iCo4()); + addMethod("BOSEconomy", new com.earth2me.essentials.economy.register.methods.BOSE6()); + addMethod("BOSEconomy", new com.earth2me.essentials.economy.register.methods.BOSE7()); + addMethod("Currency", new com.earth2me.essentials.economy.register.methods.MCUR()); Dependencies.add("MultiCurrency"); - addMethod("Vault", new com.earth2me.essentials.register.payment.methods.VaultEco()); + addMethod("Vault", new com.earth2me.essentials.economy.register.methods.VaultEco()); } /** diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/BOSE6.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE6.java index a77a1d3b0..688e68332 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/methods/BOSE6.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE6.java @@ -1,6 +1,6 @@ -package com.earth2me.essentials.register.payment.methods; +package com.earth2me.essentials.economy.register.methods; -import com.earth2me.essentials.register.payment.Method; +import com.earth2me.essentials.economy.register.Method; import cosine.boseconomy.BOSEconomy; import org.bukkit.plugin.Plugin; diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/BOSE7.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE7.java index 7aab8c459..53dd43d87 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/methods/BOSE7.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE7.java @@ -1,6 +1,6 @@ -package com.earth2me.essentials.register.payment.methods; +package com.earth2me.essentials.economy.register.methods; -import com.earth2me.essentials.register.payment.Method; +import com.earth2me.essentials.economy.register.Method; import cosine.boseconomy.BOSEconomy; import org.bukkit.plugin.Plugin; diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/MCUR.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/MCUR.java index 92c4f4f19..d2cb57a8d 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/methods/MCUR.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/methods/MCUR.java @@ -1,6 +1,6 @@ -package com.earth2me.essentials.register.payment.methods; +package com.earth2me.essentials.economy.register.methods; -import com.earth2me.essentials.register.payment.Method; +import com.earth2me.essentials.economy.register.Method; import me.ashtheking.currency.Currency; import me.ashtheking.currency.CurrencyList; import org.bukkit.plugin.Plugin; diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/VaultEco.java index f0a8171f3..43beb84f4 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/methods/VaultEco.java @@ -1,13 +1,11 @@ -package com.earth2me.essentials.register.payment.methods; +package com.earth2me.essentials.economy.register.methods; +import com.earth2me.essentials.economy.register.Method; import net.milkbowl.vault.Vault; import net.milkbowl.vault.economy.Economy; - import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; -import com.earth2me.essentials.register.payment.Method; - public class VaultEco implements Method { diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo4.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo4.java index 4542f6743..b033ba9cc 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo4.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo4.java @@ -1,6 +1,6 @@ -package com.earth2me.essentials.register.payment.methods; +package com.earth2me.essentials.economy.register.methods; -import com.earth2me.essentials.register.payment.Method; +import com.earth2me.essentials.economy.register.Method; import com.nijiko.coelho.iConomy.iConomy; import com.nijiko.coelho.iConomy.system.Account; import org.bukkit.plugin.Plugin; diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo5.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo5.java index 87144fa34..137772ebc 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo5.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo5.java @@ -1,6 +1,6 @@ -package com.earth2me.essentials.register.payment.methods; +package com.earth2me.essentials.economy.register.methods; -import com.earth2me.essentials.register.payment.Method; +import com.earth2me.essentials.economy.register.Method; import com.iConomy.iConomy; import com.iConomy.system.Account; import com.iConomy.system.BankAccount; diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo6.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo6.java index ecd1d6aae..ead4ebeb3 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo6.java +++ b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo6.java @@ -1,6 +1,6 @@ -package com.earth2me.essentials.register.payment.methods; +package com.earth2me.essentials.economy.register.methods; -import com.earth2me.essentials.register.payment.Method; +import com.earth2me.essentials.economy.register.Method; import com.iCo6.iConomy; import com.iCo6.system.Account; import com.iCo6.system.Accounts; diff --git a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsBlockListener.java index 3423da9d0..3f2f78477 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java +++ b/Essentials/src/com/earth2me/essentials/listener/EssentialsBlockListener.java @@ -1,5 +1,8 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.listener; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import org.bukkit.GameMode; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -14,6 +17,7 @@ public class EssentialsBlockListener implements Listener public EssentialsBlockListener(final IEssentials ess) { + super(); this.ess = ess; } @@ -22,13 +26,13 @@ public class EssentialsBlockListener implements Listener { // Do not rely on getItemInHand(); // http://leaky.bukkit.org/issues/663 - final ItemStack is = Util.convertBlockToItem(event.getBlockPlaced()); - if (is == null) + final ItemStack itemstack = Util.convertBlockToItem(event.getBlockPlaced()); + if (itemstack == null) { return; } - final User user = ess.getUser(event.getPlayer()); - final boolean unlimitedForUser = user.hasUnlimited(is); + final IUser user = ess.getUser(event.getPlayer()); + final boolean unlimitedForUser = user.getData().hasUnlimited(itemstack.getType()); if (unlimitedForUser && user.getGameMode() == GameMode.SURVIVAL) { ess.scheduleSyncDelayedTask( @@ -37,7 +41,7 @@ public class EssentialsBlockListener implements Listener @Override public void run() { - user.getInventory().addItem(is); + user.getInventory().addItem(itemstack); user.updateInventory(); } }); diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java index 9b11f0a24..036da57d2 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java +++ b/Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java @@ -1,24 +1,29 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.listener; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; import java.util.List; +import lombok.Cleanup; import org.bukkit.Material; -import org.bukkit.entity.Ageable; +import org.bukkit.entity.Animals; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.*; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; +import org.bukkit.event.entity.*; import org.bukkit.inventory.ItemStack; public class EssentialsEntityListener implements Listener { - private final IEssentials ess; + private final transient IEssentials ess; - public EssentialsEntityListener(IEssentials ess) + public EssentialsEntityListener(final IEssentials ess) { this.ess = ess; } @@ -30,51 +35,32 @@ public class EssentialsEntityListener implements Listener final Entity eDefend = event.getEntity(); if (eDefend instanceof Player && eAttack instanceof Player) { - final User defender = ess.getUser(eDefend); - final User attacker = ess.getUser(eAttack); - - if (ess.getSettings().getLoginAttackDelay() > 0 && !attacker.isAuthorized("essentials.pvpdelay.exempt") - && (System.currentTimeMillis() < (attacker.getLastLogin() + ess.getSettings().getLoginAttackDelay()))) - { - event.setCancelled(true); - } - - if (attacker.hasInvulnerabilityAfterTeleport() || defender.hasInvulnerabilityAfterTeleport()) - { - event.setCancelled(true); - } - + @Cleanup + final IUser attacker = ess.getUser((Player)eAttack); + attacker.acquireReadLock(); attacker.updateActivity(true); - final List<String> commandList = attacker.getPowertool(attacker.getItemInHand()); + final ItemStack itemstack = attacker.getItemInHand(); + final List<String> commandList = attacker.getData().getPowertool(itemstack.getType()); if (commandList != null && !commandList.isEmpty()) { - for (final String command : commandList) + for (String command : commandList) { if (command != null && !command.isEmpty()) { - ess.scheduleSyncDelayedTask( - new Runnable() - { - @Override - public void run() - { - attacker.getServer().dispatchCommand(attacker.getBase(), command.replaceAll("\\{player\\}", defender.getName())); - } - }); - + attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", ((Player)eDefend).getName())); event.setCancelled(true); return; } } } } - else if (eDefend instanceof Ageable && eAttack instanceof Player) + else if (eDefend instanceof Animals && eAttack instanceof Player) { final Player player = (Player)eAttack; final ItemStack hand = player.getItemInHand(); if (hand != null && hand.getType() == Material.MILK_BUCKET) { - ((Ageable)eDefend).setBaby(); + ((Animals)eDefend).setBaby(); hand.setType(Material.BUCKET); player.setItemInHand(hand); player.updateInventory(); @@ -86,7 +72,7 @@ public class EssentialsEntityListener implements Listener @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityDamage(final EntityDamageEvent event) { - if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled()) + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) { final Player player = (Player)event.getEntity(); player.setFireTicks(0); @@ -98,7 +84,7 @@ public class EssentialsEntityListener implements Listener @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityCombust(final EntityCombustEvent event) { - if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled()) + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) { event.setCancelled(true); } @@ -107,13 +93,16 @@ public class EssentialsEntityListener implements Listener @EventHandler(priority = EventPriority.LOWEST) public void onPlayerDeathEvent(final PlayerDeathEvent event) { - final User user = ess.getUser(event.getEntity()); - if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back")) + final IUser user = ess.getUser((Player)event.getEntity()); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (Permissions.BACK_ONDEATH.isAuthorized(user) && !settings.getData().getCommands().isDisabled("back")) { user.setLastLocation(); user.sendMessage(_("backAfterDeath")); } - if (!ess.getSettings().areDeathMessagesEnabled()) + if (!settings.getData().getGeneral().isDeathMessages()) { event.setDeathMessage(""); } @@ -122,7 +111,7 @@ public class EssentialsEntityListener implements Listener @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onFoodLevelChange(final FoodLevelChangeEvent event) { - if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled()) + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) { event.setCancelled(true); } @@ -131,10 +120,19 @@ public class EssentialsEntityListener implements Listener @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityRegainHealth(final EntityRegainHealthEvent event) { - if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player - && ess.getUser(event.getEntity()).isAfk() && ess.getSettings().getFreezeAfkPlayers()) + + if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player) { - event.setCancelled(true); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + @Cleanup + final IUser user = ess.getUser((Player)event.getEntity()); + user.acquireReadLock(); + if (user.getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()) + { + event.setCancelled(true); + } } } } diff --git a/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java new file mode 100644 index 000000000..978794b75 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java @@ -0,0 +1,438 @@ +package com.earth2me.essentials.listener; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.utils.textreader.IText; +import com.earth2me.essentials.utils.textreader.KeywordReplacer; +import com.earth2me.essentials.utils.textreader.TextInput; +import com.earth2me.essentials.utils.textreader.TextPager; +import com.earth2me.essentials.user.UserData.TimestampType; +import com.earth2me.essentials.utils.LocationUtil; +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.logging.Level; +import java.util.logging.Logger; +import lombok.Cleanup; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerLoginEvent.Result; +import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsPlayerListener implements Listener +{ + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private final transient Server server; + private final transient IEssentials ess; + + public EssentialsPlayerListener(final IEssentials parent) + { + super(); + this.ess = parent; + this.server = parent.getServer(); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerRespawn(final PlayerRespawnEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + user.updateCompass(); + user.updateDisplayName(); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerChat(final PlayerChatEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isMuted()) + { + event.setCancelled(true); + user.sendMessage(_("playerMuted")); + LOGGER.info(_("mutedUserSpeaks", user.getName())); + } + final Iterator<Player> it = event.getRecipients().iterator(); + while (it.hasNext()) + { + final IUser player = ess.getUser(it.next()); + if (player.isIgnoringPlayer(user.getName())) + { + it.remove(); + } + } + user.updateActivity(true); + user.updateDisplayName(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(final PlayerMoveEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + if (user.getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()) + { + final Location from = event.getFrom(); + final Location to = event.getTo().clone(); + to.setX(from.getX()); + to.setY(from.getY()); + to.setZ(from.getZ()); + try + { + event.setTo(LocationUtil.getSafeDestination(to)); + } + catch (Exception ex) + { + event.setTo(to); + } + return; + } + + final Location afk = user.getAfkPosition(); + if (afk == null || !event.getTo().getWorld().equals(afk.getWorld()) || afk.distanceSquared(event.getTo()) > 9) + { + user.updateActivity(true); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerQuit(final PlayerQuitEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (settings.getData().getCommands().getGod().isRemoveOnDisconnect() && user.isGodModeEnabled()) + { + user.toggleGodModeEnabled(); + } + if (user.getData().getInventory() != null) + { + user.getInventory().setContents(user.getData().getInventory().getBukkitInventory()); + user.getData().setInventory(null); + } + user.updateActivity(false); + user.dispose(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(final PlayerJoinEvent event) + { + ess.getBackup().startTask(); + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireWriteLock(); + + user.updateDisplayName(); + user.getData().setIpAddress(user.getAddress().getAddress().getHostAddress()); + user.updateActivity(false); + if (Permissions.SLEEPINGIGNORED.isAuthorized(user)) + { + user.setSleepingIgnored(true); + } + + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + if (!settings.getData().getCommands().isDisabled("motd") && Permissions.MOTD.isAuthorized(user)) + { + try + { + final IText input = new TextInput(user, "motd", true, ess); + final IText output = new KeywordReplacer(input, user, ess); + final TextPager pager = new TextPager(output, true); + pager.showPage("1", null, "motd", user); + } + catch (IOException ex) + { + if (settings.getData().getGeneral().isDebug()) + { + LOGGER.log(Level.WARNING, ex.getMessage(), ex); + } + else + { + LOGGER.log(Level.WARNING, ex.getMessage()); + } + } + } + + if (!settings.getData().getCommands().isDisabled("mail") && Permissions.MAIL.isAuthorized(user)) + { + final List<String> mail = user.getData().getMails(); + if (mail == null || mail.isEmpty()) + { + user.sendMessage(_("noNewMail")); + } + else + { + user.sendMessage(_("youHaveNewMail", mail.size())); + } + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerLogin(final PlayerLoginEvent event) + { + switch (event.getResult()) + { + case ALLOWED: + case KICK_FULL: + case KICK_BANNED: + break; + default: + return; + } + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireWriteLock(); + user.getData().setNpc(false); + + final long currentTime = System.currentTimeMillis(); + final boolean banExpired = user.checkBanTimeout(currentTime); + user.checkMuteTimeout(currentTime); + user.checkJailTimeout(currentTime); + + if (!banExpired && (user.isBanned() || event.getResult() == Result.KICK_BANNED)) + { + final String banReason = user.getData().getBan() == null ? "" : user.getData().getBan().getReason(); + event.disallow(Result.KICK_BANNED, banReason == null || banReason.isEmpty() || banReason.equalsIgnoreCase("ban") ? _("defaultBanReason") : banReason); + return; + } + + if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !Permissions.JOINFULLSERVER.isAuthorized(user)) + { + event.disallow(Result.KICK_FULL, _("serverFull")); + return; + } + event.allow(); + + user.setTimestamp(TimestampType.LOGIN, System.currentTimeMillis()); + user.updateCompass(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerTeleport(final PlayerTeleportEvent event) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + //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) && settings.getData().getCommands().getBack().isRegisterBackInListener()) + { + final IUser user = ess.getUser(event.getPlayer()); + user.setLastLocation(); + } + + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerEggThrow(final PlayerEggThrowEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + final ItemStack hand = new ItemStack(Material.EGG, 1); + if (user.getData().hasUnlimited(hand.getType())) + { + user.getInventory().addItem(hand); + user.updateInventory(); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().hasUnlimited(event.getBucket())) + { + event.getItemStack().setType(event.getBucket()); + ess.scheduleSyncDelayedTask(new Runnable() + { + @Override + public void run() + { + user.updateInventory(); + } + }); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); + final List<String> commands = Arrays.asList("msg", "r", "mail", "m", "t", "emsg", "tell", "er", "reply", "ereply", "email"); + if (commands.contains(cmd)) + { + for (Player player : ess.getServer().getOnlinePlayers()) + { + @Cleanup + IUser spyer = ess.getUser(player); + spyer.acquireReadLock(); + if (spyer.getData().isSocialspy() && !user.equals(spyer)) + { + player.sendMessage(user.getDisplayName() + " : " + event.getMessage()); + } + } + } + if (!cmd.equalsIgnoreCase("afk")) + { + user.updateActivity(true); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (settings.getData().getChat().getChangeDisplayname()) + { + user.updateDisplayName(); + } + if (!settings.getData().getWorldOptions(event.getPlayer().getLocation().getWorld().getName()).isGodmode() && !Permissions.NOGOD_OVERRIDE.isAuthorized(user)) + { + if (user.getData().isGodmode()) + { + user.sendMessage(_("noGodWorldWarning")); + } + } + if (settings.getData().getCommands().getTpa().isCancelTpRequestsOnWorldChange()) + { + if (user.getTeleportRequester() != null) + { + user.requestTeleport(null, false); + user.sendMessage(_("teleportRequestsCancelledWorldChange")); + } + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerInteract(final PlayerInteractEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + user.updateActivity(true); + switch (event.getAction()) + { + case RIGHT_CLICK_BLOCK: + if (event.isCancelled()) + { + return; + } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (settings.getData().getCommands().getHome().isUpdateBedAtDaytime() && event.getClickedBlock().getType() == Material.BED_BLOCK) + { + event.getPlayer().setBedSpawnLocation(event.getClickedBlock().getLocation()); + } + break; + case LEFT_CLICK_AIR: + case LEFT_CLICK_BLOCK: + if (user.getData().hasPowerTools() && user.getData().isPowerToolsEnabled()) + { + if (usePowertools(user)) + { + event.setCancelled(true); + } + } + break; + default: + break; + } + } + + private boolean usePowertools(final IUser user) + { + final ItemStack is = user.getItemInHand(); + int id; + if (is == null || (id = is.getTypeId()) == 0) + { + return false; + } + + final List<String> commandList = user.getData().getPowertool(is.getType()); + if (commandList == null || commandList.isEmpty()) + { + return false; + } + boolean used = false; + // We need to loop through each command and execute + for (final String command : commandList) + { + if (command.matches(".*\\{player\\}.*")) + { + //user.sendMessage("Click a player to use this command"); + continue; + } + else if (command.startsWith("c:")) + { + used = true; + user.chat(command.substring(2)); + } + else + { + used = true; + ess.scheduleSyncDelayedTask( + new Runnable() + { + @Override + public void run() + { + user.getServer().dispatchCommand(user.getBase(), command); + } + }); + } + } + return used; + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerPickupItem(final PlayerPickupItemEvent event) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getCommands().getAfk().isDisableItemPickupWhileAfk()) + { + return; + } + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isAfk()) + { + event.setCancelled(true); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java new file mode 100644 index 000000000..edb839aa2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java @@ -0,0 +1,110 @@ +package com.earth2me.essentials.listener; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IReload; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.ranks.GMGroups; +import com.earth2me.essentials.ranks.VaultGroups; +import com.earth2me.essentials.economy.register.Methods; +import com.earth2me.essentials.settings.General; +import com.earth2me.essentials.ranks.RanksStorage; +import java.util.logging.Level; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.plugin.Plugin; + + +public class EssentialsPluginListener implements Listener, IReload +{ + private final transient IEssentials ess; + + public EssentialsPluginListener(final IEssentials ess) + { + super(); + this.ess = ess; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPluginEnable(final PluginEnableEvent event) + { + checkGroups(); + //ess.getPermissionsHandler().checkPermissions(); + ess.getCommandHandler().addPlugin(event.getPlugin()); + if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) + { + ess.getLogger().log(Level.INFO, "Payment method found ({0} version: {1})", new Object[] + { + Methods.getMethod().getName(), Methods.getMethod().getVersion() + }); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPluginDisable(final PluginDisableEvent event) + { + checkGroups(); + //ess.getPermissionsHandler().checkPermissions(); + ess.getCommandHandler().removePlugin(event.getPlugin()); + // Check to see if the plugin thats being disabled is the one we are using + if (Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) + { + Methods.reset(); + ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments."); + } + } + + @Override + public void onReload() + { + //ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); + } + + private void checkGroups() + { + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + General.GroupStorage storage = General.GroupStorage.FILE; + try + { + storage = settings.getData().getGeneral().getGroupStorage(); + } + finally + { + settings.unlock(); + } + if (storage == General.GroupStorage.GROUPMANAGER) + { + Plugin groupManager = ess.getServer().getPluginManager().getPlugin("GroupManager"); + if (groupManager != null && groupManager.isEnabled() && !(ess.getRanks() instanceof GMGroups)) + { + if (ess.getRanks() instanceof RanksStorage) + { + ess.removeReloadListener((RanksStorage)ess.getRanks()); + } + ess.setRanks(new GMGroups(ess, groupManager)); + return; + } + } + if (storage == General.GroupStorage.VAULT) + { + Plugin vault = ess.getServer().getPluginManager().getPlugin("Vault"); + if (vault != null && vault.isEnabled() && !(ess.getRanks() instanceof VaultGroups)) + { + if (ess.getRanks() instanceof RanksStorage) + { + ess.removeReloadListener((RanksStorage)ess.getRanks()); + } + ess.setRanks(new VaultGroups(ess)); + return; + } + } + if (!(ess.getRanks() instanceof RanksStorage)) + { + ess.setRanks(new RanksStorage(ess)); + ess.addReloadListener((RanksStorage)ess.getRanks()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java b/Essentials/src/com/earth2me/essentials/listener/TntExplodeListener.java index 4187f835d..4710187f1 100644 --- a/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java +++ b/Essentials/src/com/earth2me/essentials/listener/TntExplodeListener.java @@ -1,5 +1,8 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.listener; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.craftbukkit.FakeExplosion; +import java.util.concurrent.atomic.AtomicBoolean; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -7,13 +10,13 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityExplodeEvent; -public class TNTExplodeListener implements Listener, Runnable +public class TntExplodeListener implements Listener, Runnable { private final transient IEssentials ess; - private transient boolean enabled = false; + private transient AtomicBoolean enabled = new AtomicBoolean(false); private transient int timer = -1; - public TNTExplodeListener(final IEssentials ess) + public TntExplodeListener(final IEssentials ess) { super(); this.ess = ess; @@ -21,15 +24,14 @@ public class TNTExplodeListener implements Listener, Runnable public void enable() { - if (!enabled) + if (enabled.compareAndSet(false, true)) { - enabled = true; timer = ess.scheduleSyncDelayedTask(this, 1000); return; } if (timer != -1) { - ess.getScheduler().cancelTask(timer); + ess.getServer().getScheduler().cancelTask(timer); timer = ess.scheduleSyncDelayedTask(this, 1000); } } @@ -37,7 +39,7 @@ public class TNTExplodeListener implements Listener, Runnable @EventHandler(priority = EventPriority.LOW) public void onEntityExplode(final EntityExplodeEvent event) { - if (!enabled) + if (!enabled.get()) { return; } @@ -56,6 +58,6 @@ public class TNTExplodeListener implements Listener, Runnable @Override public void run() { - enabled = false; + enabled.set(false); } } diff --git a/Essentials/src/com/earth2me/essentials/perm/BPermissions2Handler.java b/Essentials/src/com/earth2me/essentials/perm/BPermissions2Handler.java deleted file mode 100644 index f4122bf53..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/BPermissions2Handler.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.earth2me.essentials.perm; - -import de.bananaco.bpermissions.api.ApiLayer; -import de.bananaco.bpermissions.api.World; -import de.bananaco.bpermissions.api.WorldManager; -import de.bananaco.bpermissions.api.util.Calculable; -import de.bananaco.bpermissions.api.util.CalculableType; -import java.util.Arrays; -import java.util.List; -import org.bukkit.entity.Player; - - -public class BPermissions2Handler extends SuperpermsHandler -{ - public BPermissions2Handler() - { - - } - - @Override - public String getGroup(final Player base) - { - final List<String> groups = getGroups(base); - if (groups == null || groups.isEmpty()) - { - return null; - } - return groups.get(0); - } - - @Override - public List<String> getGroups(final Player base) - { - final String[] groups = ApiLayer.getGroups(base.getWorld().getName(), CalculableType.USER, base.getName()); - return Arrays.asList(groups); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - return ApiLayer.hasGroup(base.getWorld().getName(), CalculableType.USER, base.getName(), group); - } - - @Override - public boolean canBuild(final Player base, final String group) - { - return hasPermission(base, "essentials.build") || hasPermission(base, "bPermissions.build"); - } - - @Override - public String getPrefix(final Player base) - { - return ApiLayer.getValue(base.getWorld().getName(), CalculableType.USER, base.getName(), "prefix"); - } - - @Override - public String getSuffix(final Player base) - { - return ApiLayer.getValue(base.getWorld().getName(), CalculableType.USER, base.getName(), "suffix"); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/perm/BPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/BPermissionsHandler.java deleted file mode 100644 index fea268f90..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/BPermissionsHandler.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.earth2me.essentials.perm; - -import de.bananaco.permissions.Permissions; -import de.bananaco.permissions.info.InfoReader; -import de.bananaco.permissions.interfaces.PermissionSet; -import de.bananaco.permissions.worlds.WorldPermissionsManager; -import java.util.List; -import org.bukkit.entity.Player; - - -public class BPermissionsHandler extends SuperpermsHandler -{ - private final transient WorldPermissionsManager wpm; - private final transient InfoReader info; - - public BPermissionsHandler() - { - wpm = Permissions.getWorldPermissionsManager(); - info = new InfoReader(); - info.instantiate(); - } - - @Override - public String getGroup(final Player base) - { - final List<String> groups = getGroups(base); - if (groups == null || groups.isEmpty()) - { - return null; - } - return groups.get(0); - } - - @Override - public List<String> getGroups(final Player base) - { - final PermissionSet pset = wpm.getPermissionSet(base.getWorld()); - if (pset == null) - { - return null; - } - return pset.getGroups(base); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - final List<String> groups = getGroups(base); - if (groups == null || groups.isEmpty()) - { - return false; - } - return groups.contains(group); - } - - @Override - public boolean canBuild(final Player base, final String group) - { - return hasPermission(base, "essentials.build") || hasPermission(base, "bPermissions.build"); - } - - @Override - public String getPrefix(final Player base) - { - return info.getPrefix(base); - } - - @Override - public String getSuffix(final Player base) - { - return info.getSuffix(base); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java deleted file mode 100644 index fad479444..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.earth2me.essentials.perm; - -import com.earth2me.essentials.IEssentials; -import java.util.List; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class ConfigPermissionsHandler implements IPermissionsHandler -{ - private final transient IEssentials ess; - - public ConfigPermissionsHandler(final Plugin ess) - { - this.ess = (IEssentials)ess; - } - - @Override - public String getGroup(final Player base) - { - return null; - } - - @Override - public List<String> getGroups(final Player base) - { - return null; - } - - @Override - public boolean canBuild(final Player base, final String group) - { - return true; - } - - @Override - public boolean inGroup(final Player base, final String group) - { - return false; - } - - @Override - public boolean hasPermission(final Player base, final String node) - { - final String[] cmds = node.split("\\.", 2); - return !ess.getSettings().isCommandRestricted(cmds[cmds.length - 1]) - && ess.getSettings().isPlayerCommand(cmds[cmds.length - 1]); - } - - @Override - public String getPrefix(final Player base) - { - return null; - } - - @Override - public String getSuffix(final Player base) - { - return null; - } -} diff --git a/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java b/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java deleted file mode 100644 index 23fe142b2..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.earth2me.essentials.perm; - -import java.util.Arrays; -import java.util.List; -import org.anjocaido.groupmanager.GroupManager; -import org.anjocaido.groupmanager.dataholder.worlds.WorldsHolder; -import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class GroupManagerHandler implements IPermissionsHandler -{ - private final transient GroupManager groupManager; - - public GroupManagerHandler(final Plugin permissionsPlugin) - { - groupManager = ((GroupManager)permissionsPlugin); - } - - @Override - public String getGroup(final Player base) - { - final AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return null; - } - return handler.getGroup(base.getName()); - } - - @Override - public List<String> getGroups(final Player base) - { - final AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return null; - } - return Arrays.asList(handler.getGroups(base.getName())); - } - - @Override - public boolean canBuild(final Player base, final String group) - { - final AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return false; - } - return handler.canUserBuild(base.getName()); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return false; - } - return handler.inGroup(base.getName(), group); - } - - @Override - public boolean hasPermission(final Player base, final String node) - { - AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return false; - } - return handler.has(base, node); - } - - @Override - public String getPrefix(final Player base) - { - AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return null; - } - return handler.getUserPrefix(base.getName()); - } - - @Override - public String getSuffix(final Player base) - { - AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return null; - } - return handler.getUserSuffix(base.getName()); - } - - private AnjoPermissionsHandler getHandler(final Player base) - { - final WorldsHolder holder = groupManager.getWorldsHolder(); - if (holder == null) - { - return null; - } - return holder.getWorldPermissions(base); - } -} diff --git a/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java deleted file mode 100644 index 27af48e8c..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.perm; - -import java.util.List; -import org.bukkit.entity.Player; - - -public interface IPermissionsHandler -{ - String getGroup(Player base); - - List<String> getGroups(Player base); - - boolean canBuild(Player base, String group); - - boolean inGroup(Player base, String group); - - boolean hasPermission(Player base, String node); - - String getPrefix(Player base); - - String getSuffix(Player base); -} diff --git a/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java deleted file mode 100644 index b51aeb055..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.earth2me.essentials.perm; - -import java.util.Collections; -import java.util.List; -import org.bukkit.entity.Player; - - -public class NullPermissionsHandler implements IPermissionsHandler -{ - @Override - public String getGroup(final Player base) - { - return null; - } - - @Override - public List<String> getGroups(final Player base) - { - return Collections.emptyList(); - } - - @Override - public boolean canBuild(final Player base, final String group) - { - return false; - } - - @Override - public boolean inGroup(final Player base, final String group) - { - return false; - } - - @Override - public boolean hasPermission(final Player base, final String node) - { - return false; - } - - @Override - public String getPrefix(final Player base) - { - return null; - } - - @Override - public String getSuffix(final Player base) - { - return null; - } -} diff --git a/Essentials/src/com/earth2me/essentials/perm/Permissions2Handler.java b/Essentials/src/com/earth2me/essentials/perm/Permissions2Handler.java deleted file mode 100644 index 6b5ff5b73..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/Permissions2Handler.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.earth2me.essentials.perm; - -import com.nijiko.permissions.PermissionHandler; -import com.nijikokun.bukkit.Permissions.Permissions; -import java.util.Arrays; -import java.util.List; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class Permissions2Handler implements IPermissionsHandler -{ - private final transient PermissionHandler permissionHandler; - - public Permissions2Handler(final Plugin permissionsPlugin) - { - permissionHandler = ((Permissions)permissionsPlugin).getHandler(); - } - - @Override - public String getGroup(final Player base) - { - return permissionHandler.getGroup(base.getWorld().getName(), base.getName()); - } - - @Override - public List<String> getGroups(final Player base) - { - return Arrays.asList(permissionHandler.getGroups(base.getWorld().getName(), base.getName())); - } - - @Override - public boolean canBuild(final Player base, final String group) - { - return permissionHandler.canGroupBuild(base.getWorld().getName(), getGroup(base)); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - return permissionHandler.inGroup(base.getWorld().getName(), base.getName(), group); - } - - @Override - public boolean hasPermission(final Player base, final String node) - { - return permissionHandler.permission(base, node); - } - - @Override - public String getPrefix(final Player base) - { - return permissionHandler.getGroupPrefix(base.getWorld().getName(), getGroup(base)); - } - - @Override - public String getSuffix(final Player base) - { - return permissionHandler.getGroupSuffix(base.getWorld().getName(), getGroup(base)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/perm/Permissions3Handler.java b/Essentials/src/com/earth2me/essentials/perm/Permissions3Handler.java deleted file mode 100644 index 190d5b8c5..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/Permissions3Handler.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.earth2me.essentials.perm; - -import com.nijiko.permissions.PermissionHandler; -import com.nijikokun.bukkit.Permissions.Permissions; -import java.util.Arrays; -import java.util.List; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class Permissions3Handler implements IPermissionsHandler -{ - private final transient PermissionHandler permissionHandler; - - public Permissions3Handler(final Plugin permissionsPlugin) - { - permissionHandler = ((Permissions)permissionsPlugin).getHandler(); - } - - @Override - public String getGroup(final Player base) - { - return permissionHandler.getPrimaryGroup(base.getWorld().getName(), base.getName()); - } - - @Override - public List<String> getGroups(final Player base) - { - return Arrays.asList(permissionHandler.getGroups(base.getWorld().getName(), base.getName())); - } - - @Override - public boolean canBuild(final Player base, final String group) - { - return permissionHandler.canUserBuild(base.getWorld().getName(), base.getName()); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - return permissionHandler.inGroup(base.getWorld().getName(), base.getName(), group); - } - - @Override - public boolean hasPermission(final Player base, final String node) - { - return permissionHandler.has(base, node); - } - - @Override - public String getPrefix(final Player base) - { - return permissionHandler.getUserPrefix(base.getWorld().getName(), base.getName()); - } - - @Override - public String getSuffix(final Player base) - { - return permissionHandler.getUserSuffix(base.getWorld().getName(), base.getName()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsBukkitHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsBukkitHandler.java deleted file mode 100644 index aef6401d9..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsBukkitHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.earth2me.essentials.perm; - -import com.platymuus.bukkit.permissions.Group; -import com.platymuus.bukkit.permissions.PermissionInfo; -import com.platymuus.bukkit.permissions.PermissionsPlugin; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class PermissionsBukkitHandler extends SuperpermsHandler -{ - private final transient PermissionsPlugin plugin; - - public PermissionsBukkitHandler(final Plugin plugin) - { - this.plugin = (PermissionsPlugin)plugin; - } - - @Override - public String getGroup(final Player base) - { - final List<Group> groups = getPBGroups(base); - if (groups == null || groups.isEmpty()) - { - return null; - } - return groups.get(0).getName(); - } - - @Override - public List<String> getGroups(final Player base) - { - final List<Group> groups = getPBGroups(base); - if (groups.size() == 1) - { - return Collections.singletonList(groups.get(0).getName()); - } - final List<String> groupNames = new ArrayList<String>(groups.size()); - for (Group group : groups) - { - groupNames.add(group.getName()); - } - return groupNames; - } - - private List<Group> getPBGroups(final Player base) - { - final PermissionInfo info = plugin.getPlayerInfo(base.getName()); - if (info == null) - { - return Collections.emptyList(); - } - final List<Group> groups = info.getGroups(); - if (groups == null || groups.isEmpty()) - { - return Collections.emptyList(); - } - return groups; - } - - @Override - public boolean inGroup(final Player base, final String group) - { - final List<Group> groups = getPBGroups(base); - for (Group group1 : groups) - { - if (group1.getName().equalsIgnoreCase(group)) - { - return true; - } - } - return false; - } - - @Override - public boolean canBuild(Player base, String group) - { - return hasPermission(base, "essentials.build") || hasPermission(base, "permissions.build"); - } -} diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java deleted file mode 100644 index 5d8e62232..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.earth2me.essentials.perm; - -import java.util.Arrays; -import java.util.List; -import org.bukkit.entity.Player; -import ru.tehkode.permissions.PermissionManager; -import ru.tehkode.permissions.PermissionUser; -import ru.tehkode.permissions.bukkit.PermissionsEx; - - -public class PermissionsExHandler implements IPermissionsHandler -{ - private final transient PermissionManager manager; - - public PermissionsExHandler() - { - manager = PermissionsEx.getPermissionManager(); - } - - @Override - public String getGroup(final Player base) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return null; - } - return user.getGroupsNames()[0]; - } - - @Override - public List<String> getGroups(final Player base) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return null; - } - return Arrays.asList(user.getGroupsNames()); - } - - @Override - public boolean canBuild(final Player base, final String group) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return true; - } - - return user.getOptionBoolean("build", base.getWorld().getName(), true); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return false; - } - - return user.inGroup(group); - } - - @Override - public boolean hasPermission(final Player base, final String node) - { - return manager.has(base.getName(), node, base.getWorld().getName()); - } - - @Override - public String getPrefix(final Player base) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return null; - } - return user.getPrefix(base.getWorld().getName()); - } - - @Override - public String getSuffix(final Player base) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return null; - } - - return user.getSuffix(base.getWorld().getName()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java deleted file mode 100644 index e1bf13d10..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java +++ /dev/null @@ -1,218 +0,0 @@ -package com.earth2me.essentials.perm; - -import com.earth2me.essentials.Util; -import java.util.Collections; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; - - -public class PermissionsHandler implements IPermissionsHandler -{ - private transient IPermissionsHandler handler = new NullPermissionsHandler(); - private transient String defaultGroup = "default"; - private final transient Plugin plugin; - private final static Logger LOGGER = Logger.getLogger("Minecraft"); - private transient boolean useSuperperms = false; - - public PermissionsHandler(final Plugin plugin) - { - this.plugin = plugin; - } - - public PermissionsHandler(final Plugin plugin, final boolean useSuperperms) - { - this.plugin = plugin; - this.useSuperperms = useSuperperms; - } - - public PermissionsHandler(final Plugin plugin, final String defaultGroup) - { - this.plugin = plugin; - this.defaultGroup = defaultGroup; - } - - @Override - public String getGroup(final Player base) - { - String group = handler.getGroup(base); - if (group == null) - { - group = defaultGroup; - } - return group; - } - - @Override - public List<String> getGroups(final Player base) - { - List<String> groups = handler.getGroups(base); - if (groups == null || groups.isEmpty()) - { - groups = Collections.singletonList(defaultGroup); - } - return Collections.unmodifiableList(groups); - } - - @Override - public boolean canBuild(final Player base, final String group) - { - return handler.canBuild(base, group); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - return handler.inGroup(base, group); - } - - @Override - public boolean hasPermission(final Player base, final String node) - { - return handler.hasPermission(base, node); - } - - @Override - public String getPrefix(final Player base) - { - String prefix = handler.getPrefix(base); - if (prefix == null) - { - prefix = ""; - } - return prefix; - } - - @Override - public String getSuffix(final Player base) - { - String suffix = handler.getSuffix(base); - if (suffix == null) - { - suffix = ""; - } - return suffix; - } - - public void checkPermissions() - { - final PluginManager pluginManager = plugin.getServer().getPluginManager(); - - final Plugin permExPlugin = pluginManager.getPlugin("PermissionsEx"); - if (permExPlugin != null && permExPlugin.isEnabled()) - { - if (!(handler instanceof PermissionsExHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using PermissionsEx based permissions."); - handler = new PermissionsExHandler(); - } - return; - } - - final Plugin GMplugin = pluginManager.getPlugin("GroupManager"); - if (GMplugin != null && GMplugin.isEnabled()) - { - if (!(handler instanceof GroupManagerHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using GroupManager based permissions."); - handler = new GroupManagerHandler(GMplugin); - } - return; - } - - final Plugin permBukkitPlugin = pluginManager.getPlugin("PermissionsBukkit"); - if (permBukkitPlugin != null && permBukkitPlugin.isEnabled()) - { - if (!(handler instanceof PermissionsBukkitHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using PermissionsBukkit based permissions."); - handler = new PermissionsBukkitHandler(permBukkitPlugin); - } - return; - } - - final Plugin privPlugin = pluginManager.getPlugin("Privileges"); - if (privPlugin != null && privPlugin.isEnabled()) - { - if (!(handler instanceof PrivilegesHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using Privileges based permissions."); - handler = new PrivilegesHandler(privPlugin); - } - return; - } - - final Plugin bPermPlugin = pluginManager.getPlugin("bPermissions"); - if (bPermPlugin != null && bPermPlugin.isEnabled()) - { - final String bVer = bPermPlugin.getDescription().getVersion().replace(".", ""); - if (Util.isInt(bVer) && Integer.parseInt(bVer) < 284) - { - if (!(handler instanceof BPermissionsHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using bPermissions based permissions."); - handler = new BPermissionsHandler(); - } - return; - } - if (!(handler instanceof BPermissions2Handler)) - { - LOGGER.log(Level.INFO, "Essentials: Using bPermissions2 based permissions."); - handler = new BPermissions2Handler(); - } - return; - - } - final Plugin permPlugin = pluginManager.getPlugin("Permissions"); - if (permPlugin != null && permPlugin.isEnabled()) - { - if (permPlugin.getDescription().getVersion().charAt(0) == '3') - { - if (!(handler instanceof Permissions3Handler)) - { - LOGGER.log(Level.INFO, "Essentials: Using Permissions 3 based permissions."); - handler = new Permissions3Handler(permPlugin); - } - } - else - { - if (!(handler instanceof Permissions2Handler)) - { - LOGGER.log(Level.INFO, "Essentials: Using Permissions 2 based permissions."); - handler = new Permissions2Handler(permPlugin); - } - } - return; - } - - if (useSuperperms) - { - if (!(handler instanceof SuperpermsHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using superperms based permissions."); - handler = new SuperpermsHandler(); - } - } - else - { - if (!(handler instanceof ConfigPermissionsHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using config based permissions. Enable superperms in config."); - handler = new ConfigPermissionsHandler(plugin); - } - } - } - - public void setUseSuperperms(final boolean useSuperperms) - { - this.useSuperperms = useSuperperms; - } - - public String getName() - { - return handler.getClass().getSimpleName().replace("Handler", ""); - } -} diff --git a/Essentials/src/com/earth2me/essentials/perm/PrivilegesHandler.java b/Essentials/src/com/earth2me/essentials/perm/PrivilegesHandler.java deleted file mode 100644 index 6cc97f30e..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/PrivilegesHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.earth2me.essentials.perm; - -import java.util.ArrayList; -import java.util.List; -import net.krinsoft.privileges.Privileges; -import net.krinsoft.privileges.groups.Group; -import net.krinsoft.privileges.groups.GroupManager; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -public class PrivilegesHandler extends SuperpermsHandler -{ - private final transient Privileges plugin; - private final GroupManager manager; - - public PrivilegesHandler(final Plugin plugin) - { - this.plugin = (Privileges) plugin; - this.manager = this.plugin.getGroupManager(); - } - - @Override - public String getGroup(final Player base) - { - Group group = manager.getGroup(base); - if (group == null) - { - return null; - } - return group.getName(); - } - - @Override - public List<String> getGroups(final Player base) - { - Group group = manager.getGroup(base); - if (group == null) - { - return new ArrayList<String>(); - } - return group.getGroupTree(); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - Group pGroup = manager.getGroup(base); - if (pGroup == null) - { - return false; - } - return pGroup.isMemberOf(group); - } - - @Override - public boolean canBuild(Player base, String group) - { - return hasPermission(base, "essentials.build") || hasPermission(base, "privileges.build"); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java b/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java deleted file mode 100644 index 2e767cb72..000000000 --- a/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.earth2me.essentials.perm; - -import java.util.List; -import org.bukkit.entity.Player; - - -public class SuperpermsHandler implements IPermissionsHandler -{ - @Override - public String getGroup(final Player base) - { - return null; - } - - @Override - public List<String> getGroups(final Player base) - { - return null; - } - - @Override - public boolean canBuild(final Player base, final String group) - { - return hasPermission(base, "essentials.build"); - } - - @Override - public boolean inGroup(final Player base, final String group) - { - return hasPermission(base, "group." + group); - } - - @Override - public boolean hasPermission(final Player base, final String node) - { - if (base.hasPermission("-" + node)) - { - return false; - } - final String[] parts = node.split("\\."); - final StringBuilder builder = new StringBuilder(node.length()); - for (String part : parts) - { - builder.append('*'); - if (base.hasPermission(builder.toString())) - { - return true; - } - builder.deleteCharAt(builder.length() - 1); - builder.append(part).append('.'); - } - return base.hasPermission(node); - } - - @Override - public String getPrefix(final Player base) - { - return null; - } - - @Override - public String getSuffix(final Player base) - { - return null; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/AbstractSuperpermsPermission.java b/Essentials/src/com/earth2me/essentials/permissions/AbstractSuperpermsPermission.java new file mode 100644 index 000000000..4819f5ced --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/AbstractSuperpermsPermission.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IPermission; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public abstract class AbstractSuperpermsPermission implements IPermission +{ + protected Permission bukkitPerm; + + @Override + public Permission getBukkitPermission() + { + if (bukkitPerm != null) + { + return bukkitPerm; + } + else + { + return Util.registerPermission(getPermission(), getPermissionDefault()); + } + } + + /** + * PermissionDefault is OP, if the method is not overwritten. + * @return + */ + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.OP; + } + + @Override + public boolean isAuthorized(final CommandSender sender) + { + return sender.hasPermission(getBukkitPermission()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/BasePermission.java b/Essentials/src/com/earth2me/essentials/permissions/BasePermission.java new file mode 100644 index 000000000..3c033913f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/BasePermission.java @@ -0,0 +1,16 @@ +package com.earth2me.essentials.permissions; + +public class BasePermission extends AbstractSuperpermsPermission { + protected String permission; + + public BasePermission(String base, String permission) + { + super(); + this.permission = base + permission; + } + + public String getPermission() + { + return permission; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/EnchantPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/EnchantPermissions.java new file mode 100644 index 000000000..c31aa6f62 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/EnchantPermissions.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class EnchantPermissions +{ + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String enchantName) + { + IPermission perm = permissions.get(enchantName); + if (perm == null) + { + perm = new BasePermission("essentials.enchant.",enchantName.toLowerCase(Locale.ENGLISH)); + permissions.put(enchantName, perm); + } + return perm; + } +}
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/permissions/GivePermissions.java b/Essentials/src/com/earth2me/essentials/permissions/GivePermissions.java new file mode 100644 index 000000000..162ec46c0 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/GivePermissions.java @@ -0,0 +1,30 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + +public class GivePermissions { + private static Map<Material, IPermission> permissions = new EnumMap<Material, IPermission>(Material.class); + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new BasePermission("essentials.give.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")) + { + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } + }; + permissions.put(mat, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/GroupsPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/GroupsPermissions.java new file mode 100644 index 000000000..ed3ca92ff --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/GroupsPermissions.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class GroupsPermissions +{ + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String groupName) + { + IPermission perm = permissions.get(groupName); + if (perm == null) + { + perm = new BasePermission("essentials.groups.",groupName.toLowerCase(Locale.ENGLISH)); + permissions.put(groupName, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/HelpPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/HelpPermissions.java new file mode 100644 index 000000000..aae5e0ce7 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/HelpPermissions.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class HelpPermissions +{ + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String pluginName) + { + IPermission perm = permissions.get(pluginName); + if (perm == null) + { + perm = new BasePermission("essentials.help.", pluginName.toLowerCase(Locale.ENGLISH)); + permissions.put(pluginName, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/ItemPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/ItemPermissions.java new file mode 100644 index 000000000..980af104f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/ItemPermissions.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + + +public class ItemPermissions +{ + private static Map<Material, IPermission> permissions = new EnumMap<Material, IPermission>(Material.class); + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new BasePermission("essentials.itemspawn.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")) + { + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } + }; + permissions.put(mat, perm); + } + return perm; + } +}
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/permissions/KitPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/KitPermissions.java new file mode 100644 index 000000000..b21e0712d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/KitPermissions.java @@ -0,0 +1,31 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.permissions.PermissionDefault; + + +public class KitPermissions +{ + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String kitName) + { + IPermission perm = permissions.get(kitName); + if (perm == null) + { + perm = new BasePermission("essentials.kit.", kitName.toLowerCase(Locale.ENGLISH)) + { + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } + }; + permissions.put(kitName, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/NoCommandCostPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/NoCommandCostPermissions.java new file mode 100644 index 000000000..77511e198 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/NoCommandCostPermissions.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class NoCommandCostPermissions +{ + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String command) + { + IPermission perm = permissions.get(command); + if (perm == null) + { + perm = new BasePermission("essentials.nocommandcost.", command.toLowerCase(Locale.ENGLISH)); + permissions.put(command, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/Permissions.java b/Essentials/src/com/earth2me/essentials/permissions/Permissions.java new file mode 100644 index 000000000..151ed77c9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/Permissions.java @@ -0,0 +1,124 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IPermission; +import java.util.Locale; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public enum Permissions implements IPermission +{ + AFK, + AFK_KICKEXEMPT, + AFK_OTHERS, + BACK_ONDEATH, + BALANCE_OTHERS, + BAN_EXEMPT, + BAN_NOTIFY, + BAN_OFFLINE, + BREAK_BEDROCK, + CHAT_COLOR, + CHAT_SPY, + CLEARINVENTORY_OTHERS, + DELHOME_OTHERS, + ECO_LOAN(PermissionDefault.FALSE), + FEED_OTHERS, + GAMEMODE_OTHERS, + GEOIP_HIDE(PermissionDefault.FALSE), + GEOIP_SHOW(PermissionDefault.TRUE), + GETPOS_OTHERS, + GOD_OTHERS, + HEAL_COOLDOWN_BYPASS, + HEAL_OTHERS, + HELPOP_RECEIVE, + HOME_OTHERS, + JAIL_EXEMPT, + JOINFULLSERVER, + KICK_EXEMPT, + KICK_NOTIFY, + LIST_HIDDEN, + LIGHTNING_OTHERS, + MAIL, + MAIL_SEND, + MAIL_SENDALL, + MOTD, + MSG_COLOR, + MUTE_EXEMPT, + NEAR_OTHERS, + NICK_COLOR, + NICK_OTHERS, + NOGOD_OVERRIDE, + OVERSIZEDSTACKS(PermissionDefault.FALSE), + POWERTOOL_APPEND, + PTIME_OTHERS, + REPAIR_ARMOR, + REPAIR_ENCHANTED, + SEEN_BANREASON, + SETHOME_MULTIPLE, + SETHOME_OTHERS, + SLEEPINGIGNORED, + SPAWN_OTHERS, + SUDO_EXEMPT, + TELEPORT_COOLDOWN_BYPASS, + TELEPORT_HIDDEN, + TELEPORT_TIMER_BYPASS, + TEMPBAN_EXEMPT, + TEMPBAN_OFFLINE, + TIME_SET, + TOGGLEJAIL_OFFLINE, + TPA, + TPAALL, + TPAHERE, + TPOHERE, + UNLIMITED_OTHERS, + WARP_LIST(PermissionDefault.TRUE), + WARP_OTHERS; + private static final String base = "essentials."; + private final String permission; + private final PermissionDefault defaultPerm; + private transient Permission bukkitPerm = null; + + private Permissions() + { + this(PermissionDefault.OP); + } + + private Permissions(final PermissionDefault defaultPerm) + { + permission = base + toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); + this.defaultPerm = defaultPerm; + } + + @Override + public String getPermission() + { + return permission; + } + + @Override + public Permission getBukkitPermission() + { + if (bukkitPerm != null) + { + return bukkitPerm; + } + else + { + return Util.registerPermission(getPermission(), getPermissionDefault()); + } + } + + @Override + public PermissionDefault getPermissionDefault() + { + return this.defaultPerm; + } + + @Override + public boolean isAuthorized(CommandSender sender) + { + return sender.hasPermission(getBukkitPermission()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/SpawnerPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/SpawnerPermissions.java new file mode 100644 index 000000000..17f8243cf --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/SpawnerPermissions.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class SpawnerPermissions +{ + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String mobName) + { + IPermission perm = permissions.get(mobName); + if (perm == null) + { + perm = new BasePermission("essentials.spawner.", mobName.toLowerCase(Locale.ENGLISH).replace("_", "")); + permissions.put(mobName, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/SpawnmobPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/SpawnmobPermissions.java new file mode 100644 index 000000000..fa1e26fa0 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/SpawnmobPermissions.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class SpawnmobPermissions { + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String mobName) + { + IPermission perm = permissions.get(mobName); + if (perm == null) + { + perm = new BasePermission("essentials.spawnmob.", mobName.toLowerCase(Locale.ENGLISH).replace("_", "")); + permissions.put(mobName, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/UnlimitedItemPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/UnlimitedItemPermissions.java new file mode 100644 index 000000000..dbe7df95b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/UnlimitedItemPermissions.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; + +public class UnlimitedItemPermissions +{ + private static Map<Material, IPermission> permissions = new EnumMap<Material, IPermission>(Material.class); + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new BasePermission("essentials.unlimited.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")); + permissions.put(mat, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/permissions/WarpPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/WarpPermissions.java new file mode 100644 index 000000000..7f08ad3a2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/WarpPermissions.java @@ -0,0 +1,31 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.permissions.PermissionDefault; + + +public class WarpPermissions +{ + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String warpName) + { + IPermission perm = permissions.get(warpName); + if (perm == null) + { + perm = new BasePermission("essentials.warp.", warpName.toLowerCase(Locale.ENGLISH)) + { + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } + }; + permissions.put(warpName, perm); + } + return perm; + } +}
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/permissions/WorldPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/WorldPermissions.java new file mode 100644 index 000000000..303a7214d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/permissions/WorldPermissions.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.permissions; + +import com.earth2me.essentials.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class WorldPermissions +{ + private static Map<String, IPermission> permissions = new HashMap<String, IPermission>(); + + public static IPermission getPermission(final String worldName) + { + IPermission perm = permissions.get(worldName); + if (perm == null) + { + perm = new BasePermission("essentials.world.", worldName.toLowerCase(Locale.ENGLISH)); + permissions.put(worldName, perm); + } + return perm; + } +} diff --git a/Essentials/src/com/earth2me/essentials/ranks/GMGroups.java b/Essentials/src/com/earth2me/essentials/ranks/GMGroups.java new file mode 100644 index 000000000..244ff8410 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/ranks/GMGroups.java @@ -0,0 +1,143 @@ +package com.earth2me.essentials.ranks; + +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IRanks; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import java.text.MessageFormat; +import lombok.Cleanup; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.bukkit.plugin.Plugin; + +public class GMGroups implements IRanks { + private final transient IEssentials ess; + private final transient GroupManager groupManager; + + public GMGroups(final IEssentials ess, final Plugin groupManager) + { + this.ess = ess; + this.groupManager = (GroupManager)groupManager; + } + + @Override + public double getHealCooldown(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return 0; + } + return handler.getPermissionDouble(player.getName(), "healcooldown"); + } + + @Override + public double getTeleportCooldown(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return 0; + } + return handler.getPermissionDouble(player.getName(), "teleportcooldown"); + } + + @Override + public double getTeleportDelay(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return 0; + } + return handler.getPermissionDouble(player.getName(), "teleportdelay"); + } + + @Override + public String getPrefix(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return null; + } + return handler.getUserPrefix(player.getName()); + } + + @Override + public String getSuffix(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return null; + } + return handler.getUserSuffix(player.getName()); + } + + @Override + public int getHomeLimit(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return 0; + } + return handler.getPermissionInteger(player.getName(), "homes"); + } + + @Override + public MessageFormat getChatFormat(final IUser player) + { + String format = getRawChatFormat(player); + format = Util.replaceColor(format); + format = format.replace("{DISPLAYNAME}", "%1$s"); + format = format.replace("{GROUP}", "{0}"); + format = format.replace("{MESSAGE}", "%2$s"); + format = format.replace("{WORLDNAME}", "{1}"); + format = format.replace("{SHORTWORLDNAME}", "{2}"); + format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); + MessageFormat mFormat = new MessageFormat(format); + return mFormat; + } + + private String getRawChatFormat(final IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler != null) + { + String chatformat = handler.getPermissionString(player.getName(), "chatformat"); + if (chatformat != null && !chatformat.isEmpty()) { + return chatformat; + } + } + + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getChat().getDefaultFormat(); + } + + @Override + public String getMainGroup(IUser player) + { + final AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return null; + } + return handler.getGroup(player.getName()); + } + + @Override + public boolean inGroup(IUser player, String groupname) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return false; + } + return handler.inGroup(player.getName(), groupname); + } +} diff --git a/Essentials/src/com/earth2me/essentials/settings/GroupOptions.java b/Essentials/src/com/earth2me/essentials/ranks/RankOptions.java index 7b16a471b..5fa011f9c 100644 --- a/Essentials/src/com/earth2me/essentials/settings/GroupOptions.java +++ b/Essentials/src/com/earth2me/essentials/ranks/RankOptions.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.settings; +package com.earth2me.essentials.ranks; import com.earth2me.essentials.storage.Comment; import com.earth2me.essentials.storage.StorageObject; @@ -8,7 +8,7 @@ import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) -public class GroupOptions implements StorageObject +public class RankOptions implements StorageObject { @Comment("Message format of chat messages") private String messageFormat; diff --git a/Essentials/src/com/earth2me/essentials/ranks/Ranks.java b/Essentials/src/com/earth2me/essentials/ranks/Ranks.java new file mode 100644 index 000000000..cc11aff2a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/ranks/Ranks.java @@ -0,0 +1,28 @@ +package com.earth2me.essentials.ranks; + +import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.MapValueType; +import com.earth2me.essentials.storage.StorageObject; +import java.util.LinkedHashMap; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Ranks implements StorageObject +{ + public Ranks() + { + final RankOptions defaultOptions = new RankOptions(); + ranks.put("default", defaultOptions); + } + @Comment( + { + "The order of the ranks matters, the ranks are checked from top to bottom.", + "All rank names have to be lower case.", + "The ranks can be connected to users using the permission essentials.ranks.rankname" + }) + @MapValueType(RankOptions.class) + private LinkedHashMap<String, RankOptions> ranks = new LinkedHashMap<String, RankOptions>(); +} diff --git a/Essentials/src/com/earth2me/essentials/ranks/RanksStorage.java b/Essentials/src/com/earth2me/essentials/ranks/RanksStorage.java new file mode 100644 index 000000000..7f6e5dd84 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/ranks/RanksStorage.java @@ -0,0 +1,195 @@ +package com.earth2me.essentials.ranks; + +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IRanks; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.GroupsPermissions; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import lombok.Cleanup; + + +public class RanksStorage extends AsyncStorageObjectHolder<Ranks> implements IRanks +{ + public RanksStorage(final IEssentials ess) + { + super(ess, Ranks.class); + onReload(); + } + + @Override + public File getStorageFile() + { + return new File(ess.getDataFolder(), "ranks.yml"); + } + + public Collection<Entry<String, RankOptions>> getGroups(final IUser player) + { + acquireReadLock(); + try + { + final Map<String, RankOptions> groups = getData().getRanks(); + if (groups == null || groups.isEmpty()) + { + return Collections.emptyList(); + } + final ArrayList<Entry<String, RankOptions>> list = new ArrayList(); + for (Entry<String, RankOptions> entry : groups.entrySet()) + { + if (GroupsPermissions.getPermission(entry.getKey()).isAuthorized(player)) + { + if(entry.getValue() != null) + { + list.add(entry); + } + } + } + return list; + } + finally + { + unlock(); + } + } + + @Override + public double getHealCooldown(final IUser player) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getHealCooldown() != null) + { + return groupOptions.getValue().getHealCooldown(); + } + } + return 0; + } + + @Override + public double getTeleportCooldown(final IUser player) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getTeleportCooldown() != null) + { + return groupOptions.getValue().getTeleportCooldown(); + } + } + return 0; + } + + @Override + public double getTeleportDelay(final IUser player) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getTeleportDelay() != null) + { + return groupOptions.getValue().getTeleportDelay(); + } + } + return 0; + } + + @Override + public String getPrefix(final IUser player) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getPrefix() != null) + { + return groupOptions.getValue().getPrefix(); + } + } + return ""; + } + + @Override + public String getSuffix(final IUser player) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getSuffix() != null) + { + return groupOptions.getValue().getSuffix(); + } + } + return ""; + } + + @Override + public int getHomeLimit(final IUser player) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getHomes() != null) + { + return groupOptions.getValue().getHomes(); + } + } + return 0; + } + + //TODO: Reimplement caching + @Override + public MessageFormat getChatFormat(final IUser player) + { + String format = getRawChatFormat(player); + format = Util.replaceColor(format); + format = format.replace("{DISPLAYNAME}", "%1$s"); + format = format.replace("{GROUP}", "{0}"); + format = format.replace("{MESSAGE}", "%2$s"); + format = format.replace("{WORLDNAME}", "{1}"); + format = format.replace("{SHORTWORLDNAME}", "{2}"); + format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); + MessageFormat mFormat = new MessageFormat(format); + return mFormat; + } + + private String getRawChatFormat(final IUser player) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getMessageFormat() != null) + { + return groupOptions.getValue().getMessageFormat(); + } + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getChat().getDefaultFormat(); + } + + @Override + public boolean inGroup(IUser player, String groupname) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + if (groupOptions.getKey().equalsIgnoreCase(groupname)) + { + return true; + } + } + return false; + } + + @Override + public String getMainGroup(IUser player) + { + for (Entry<String, RankOptions> groupOptions : getGroups(player)) + { + return groupOptions.getKey(); + } + return "default"; + } + +} diff --git a/Essentials/src/com/earth2me/essentials/ranks/VaultGroups.java b/Essentials/src/com/earth2me/essentials/ranks/VaultGroups.java new file mode 100644 index 000000000..1d94b6089 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/ranks/VaultGroups.java @@ -0,0 +1,124 @@ +package com.earth2me.essentials.ranks; + +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IRanks; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import java.text.MessageFormat; +import lombok.Cleanup; +import net.milkbowl.vault.chat.Chat; +import org.bukkit.plugin.RegisteredServiceProvider; + + +public class VaultGroups implements IRanks +{ + private final IEssentials ess; + + public VaultGroups(final IEssentials ess) + { + this.ess = ess; + } + + @Override + public double getHealCooldown(IUser player) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerInfoDouble(player.getBase(), "healcooldown", 0); + } + + @Override + public double getTeleportCooldown(IUser player) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerInfoDouble(player.getBase(), "teleportcooldown", 0); + } + + @Override + public double getTeleportDelay(IUser player) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerInfoDouble(player.getBase(), "teleportdelay", 0); + } + + @Override + public String getPrefix(IUser player) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerPrefix(player.getBase()); + } + + @Override + public String getSuffix(IUser player) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerSuffix(player.getBase()); + } + + @Override + public int getHomeLimit(IUser player) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerInfoInteger(player.getBase(), "homes", 0); + } + + @Override + public MessageFormat getChatFormat(final IUser player) + { + String format = getRawChatFormat(player); + format = Util.replaceColor(format); + format = format.replace("{DISPLAYNAME}", "%1$s"); + format = format.replace("{GROUP}", "{0}"); + format = format.replace("{MESSAGE}", "%2$s"); + format = format.replace("{WORLDNAME}", "{1}"); + format = format.replace("{SHORTWORLDNAME}", "{2}"); + format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); + MessageFormat mFormat = new MessageFormat(format); + return mFormat; + } + + private String getRawChatFormat(final IUser player) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + String chatformat = chat.getPlayerInfoString(player.getBase(), "chatformat", ""); + if (chatformat != null && !chatformat.isEmpty()) + { + return chatformat; + } + + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getChat().getDefaultFormat(); + } + + @Override + public String getMainGroup(IUser player) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPrimaryGroup(player.getBase()); + } + + @Override + public boolean inGroup(IUser player, String groupname) + { + RegisteredServiceProvider<Chat> rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + for (String group : chat.getPlayerGroups(player.getBase())) + { + if (group.equalsIgnoreCase(groupname)) + { + return true; + } + } + return false; + } +} diff --git a/Essentials/src/com/earth2me/essentials/settings/Chat.java b/Essentials/src/com/earth2me/essentials/settings/Chat.java index 623228c4e..bbd02ce8e 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Chat.java +++ b/Essentials/src/com/earth2me/essentials/settings/Chat.java @@ -12,8 +12,12 @@ public class Chat implements StorageObject { @Comment("The character(s) to prefix all nicknames, so that you know they are not true usernames.") private String nicknamePrefix = "~"; - @Comment("Disable this if you have any other plugin, that modifies the displayname of a user.") - private boolean changeDisplayname = true; + @Comment( + { + "Disable this if you have any other plugin, that modifies the displayname of a user.", + "If it is not set, it will be enabled if EssentialsChat is installed, otherwise not." + }) + private Boolean changeDisplayname = true; private String displaynameFormat = "{PREFIX}{NICKNAMEPREFIX}{NAME}{SUFFIX}"; @Comment( { diff --git a/Essentials/src/com/earth2me/essentials/settings/Commands.java b/Essentials/src/com/earth2me/essentials/settings/Commands.java index 08efc881c..1b738d4c9 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Commands.java +++ b/Essentials/src/com/earth2me/essentials/settings/Commands.java @@ -15,12 +15,14 @@ import lombok.EqualsAndHashCode; public class Commands implements StorageObject { private Afk afk = new Afk(); + private Back back = new Back(); private God god = new God(); private Help help = new Help(); private Home home = new Home(); - private Kit kit = new Kit(); private Lightning lightning = new Lightning(); + private com.earth2me.essentials.settings.commands.List list = new com.earth2me.essentials.settings.commands.List(); private Spawnmob spawnmob = new Spawnmob(); + private Tpa tpa = new Tpa(); @ListType @Comment( { @@ -33,8 +35,40 @@ public class Commands implements StorageObject "We should try to take priority over /god. If this doesn't work, use /essentials:god or /egod.", "If god is set using WorldGuard, use /ungod to remove then use whichever you see fit." }) - private List<String> overwritten = new ArrayList<String>(); + private List<String> overridden = new ArrayList<String>(); @ListType @Comment("Disabled commands will be completelly unavailable on the server.") private List<String> disabled = new ArrayList<String>(); + + public boolean isDisabled(final String commandName) + { + if (disabled == null) + { + return false; + } + for (String disabledCommand : disabled) + { + if (commandName.equalsIgnoreCase(disabledCommand)) + { + return true; + } + } + return false; + } + + public boolean isOverridden(final String commandName) + { + if (overridden == null) + { + return false; + } + for (String overriddenCommand : overridden) + { + if (commandName.equalsIgnoreCase(overriddenCommand)) + { + return true; + } + } + return false; + } } diff --git a/Essentials/src/com/earth2me/essentials/settings/Economy.java b/Essentials/src/com/earth2me/essentials/settings/Economy.java index 5872dada9..ea106f13f 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Economy.java +++ b/Essentials/src/com/earth2me/essentials/settings/Economy.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.settings; +import com.earth2me.essentials.economy.Worth; import com.earth2me.essentials.storage.Comment; import com.earth2me.essentials.storage.MapValueType; import com.earth2me.essentials.storage.StorageObject; @@ -37,7 +38,30 @@ public class Economy implements StorageObject { return Math.abs(maxMoney) > MAXMONEY ? MAXMONEY : Math.abs(maxMoney); } + + @Comment( + { + "Set the minimum amount of money a player can have (must be above the negative of max-money).", + "Setting this to 0, will disable overdrafts/loans completely. Users need 'essentials.eco.loan' perm to go below 0." + }) + private double minMoney = -MAXMONEY; + public double getMinMoney() + { + return Math.abs(minMoney) > MAXMONEY ? -MAXMONEY : minMoney; + } + @Comment("Enable this to log all interactions with trade/buy/sell signs and sell command") private boolean logEnabled = false; private Worth worth = new Worth(); + private boolean tradeInStacks = false; + + public double getCommandCost(String command) + { + if (commandCosts == null) + { + return 0; + } + Double price = commandCosts.get(command); + return price == null || Double.isNaN(price) || Double.isInfinite(price) ? 0 : price; + } } diff --git a/Essentials/src/com/earth2me/essentials/settings/General.java b/Essentials/src/com/earth2me/essentials/settings/General.java index a7cf537bb..85238977f 100644 --- a/Essentials/src/com/earth2me/essentials/settings/General.java +++ b/Essentials/src/com/earth2me/essentials/settings/General.java @@ -25,9 +25,30 @@ public class General implements StorageObject private String locale; @Comment( { - "Should we announce to the server when someone logs in for the first time?", - "If so, use this format, replacing {DISPLAYNAME} with the player name.", - "If not, set to ''" + "The number of items given, if the quantity parameter is left out in /item or /give.", + "If this number is below 1, the maximum stack size size is given. If oversized stacks", + "is not enabled, any number higher then the maximum stack size results in more than one stack." }) - private String newPlayerAnnouncement = "&dWelcome {DISPLAYNAME} to the server!"; + private int defaultStacksize = -1; + @Comment( + { + "Oversized stacks are stacks that ignore the normal max stacksize.", + "They can be obtained using /give and /item, if the player has essentials.oversizedstacks permission.", + "How many items should be in a oversized stack?" + }) + private int oversizedStacksize = 64; + + + public enum GroupStorage + { + FILE, GROUPMANAGER, VAULT + } + @Comment( + { + "Sets the place where group options should be stored:", + " FILE: Options are stored inside groups.yml in the Essentials folder", + " GROUPMANAGER: Options are stored using the GroupManager groups", + " VAULT: Options are stored using a permissions plugin supported by Vault" + }) + private GroupStorage groupStorage = GroupStorage.FILE; } diff --git a/Essentials/src/com/earth2me/essentials/settings/Groups.java b/Essentials/src/com/earth2me/essentials/settings/Groups.java deleted file mode 100644 index 5e67db890..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Groups.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.LinkedHashMap; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Groups implements StorageObject -{ - public Groups() - { - GroupOptions defaultOptions = new GroupOptions(); - groups.put("default", defaultOptions); - } - @Comment( - { - "The order of the groups matters, the groups are checked from top to bottom.", - "All group names have to be lower case.", - "The groups can be connected to users using the permission essentials.groups.groupname" - }) - @MapValueType(GroupOptions.class) - private LinkedHashMap<String, GroupOptions> groups = new LinkedHashMap<String, GroupOptions>(); -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Jails.java b/Essentials/src/com/earth2me/essentials/settings/Jails.java index 4f9b79197..3adb4ec1e 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Jails.java +++ b/Essentials/src/com/earth2me/essentials/settings/Jails.java @@ -1,12 +1,12 @@ package com.earth2me.essentials.settings; +import com.earth2me.essentials.storage.Location; import com.earth2me.essentials.storage.MapValueType; import com.earth2me.essentials.storage.StorageObject; import java.util.HashMap; import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; -import org.bukkit.Location; @Data diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/KitObject.java b/Essentials/src/com/earth2me/essentials/settings/Kit.java index fe0353be9..19267e6f3 100644 --- a/Essentials/src/com/earth2me/essentials/settings/commands/KitObject.java +++ b/Essentials/src/com/earth2me/essentials/settings/Kit.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.settings.commands; +package com.earth2me.essentials.settings; import com.earth2me.essentials.storage.ListType; import com.earth2me.essentials.storage.StorageObject; @@ -11,7 +11,7 @@ import org.bukkit.inventory.ItemStack; @Data @EqualsAndHashCode(callSuper = false) -public class KitObject implements StorageObject +public class Kit implements StorageObject { @ListType(ItemStack.class) private List<ItemStack> items = new ArrayList<ItemStack>(); diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Kit.java b/Essentials/src/com/earth2me/essentials/settings/Kits.java index 87aa42d3c..f943c2bb9 100644 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Kit.java +++ b/Essentials/src/com/earth2me/essentials/settings/Kits.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.settings.commands; +package com.earth2me.essentials.settings; import com.earth2me.essentials.storage.MapValueType; import com.earth2me.essentials.storage.StorageObject; @@ -12,17 +12,17 @@ import org.bukkit.inventory.ItemStack; @Data @EqualsAndHashCode(callSuper = false) -public class Kit implements StorageObject +public class Kits implements StorageObject { - public Kit() + public Kits() { - final KitObject kit = new KitObject(); + final Kit kit = new Kit(); kit.setDelay(10.0); kit.getItems().add(new ItemStack(Material.DIAMOND_SPADE, 1)); kit.getItems().add(new ItemStack(Material.DIAMOND_PICKAXE, 1)); kit.getItems().add(new ItemStack(Material.DIAMOND_AXE, 1)); kits.put("tools", kit); } - @MapValueType(KitObject.class) - private Map<String, KitObject> kits = new HashMap<String, KitObject>(); + @MapValueType(Kit.class) + private Map<String, Kit> kits = new HashMap<String, Kit>(); } diff --git a/Essentials/src/com/earth2me/essentials/settings/Locations.java b/Essentials/src/com/earth2me/essentials/settings/Locations.java deleted file mode 100644 index 7e7f1a63d..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Locations.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.Location; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Locations implements StorageObject -{ - @MapValueType(Location.class) - Map<String, Location> jails = new HashMap<String, Location>(); - @MapValueType(Location.class) - Map<String, Location> warps = new HashMap<String, Location>(); - @MapValueType(Location.class) - Map<String, Location> spawns = new HashMap<String, Location>(); -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Settings.java b/Essentials/src/com/earth2me/essentials/settings/Settings.java index 4c2ff2dd9..6e5ec9793 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Settings.java +++ b/Essentials/src/com/earth2me/essentials/settings/Settings.java @@ -1,7 +1,10 @@ package com.earth2me.essentials.settings; import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.MapValueType; import com.earth2me.essentials.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; @@ -50,9 +53,20 @@ public class Settings implements StorageObject { "##########################################################", "+------------------------------------------------------+ #", - "| Group Settings | #", + "| Worlds Settings | #", "+------------------------------------------------------+ #", "##########################################################" }) - private Groups groups = new Groups(); + @MapValueType(WorldOptions.class) + private Map<String, WorldOptions> worlds = new HashMap<String, WorldOptions>(); + + public WorldOptions getWorldOptions(final String name) + { + if (worlds == null) + { + worlds = new HashMap<String, WorldOptions>(); + } + final WorldOptions options = worlds.get(name); + return (options == null) ? new WorldOptions() : options; + } } diff --git a/Essentials/src/com/earth2me/essentials/settings/SettingsHolder.java b/Essentials/src/com/earth2me/essentials/settings/SettingsHolder.java new file mode 100644 index 000000000..434d9b922 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/SettingsHolder.java @@ -0,0 +1,64 @@ +package com.earth2me.essentials.settings; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.util.concurrent.atomic.AtomicBoolean; + + +public class SettingsHolder extends AsyncStorageObjectHolder<Settings> implements ISettings +{ + private final transient AtomicBoolean debug = new AtomicBoolean(false); + public SettingsHolder(final IEssentials ess) + { + super(ess, Settings.class); + onReload(); + } + + @Override + public final void onReload() + { + super.onReload(); + acquireReadLock(); + try { + debug.set(getData().getGeneral().isDebug()); + } finally { + unlock(); + } + } + + @Override + public File getStorageFile() + { + return new File(ess.getDataFolder(), "settings.yml"); + } + + @Override + public String getLocale() + { + acquireReadLock(); + try { + return getData().getGeneral().getLocale(); + } finally { + unlock(); + } + } + + @Override + public boolean isDebug() + { + return debug.get(); + } + + public void setDebug(final boolean set) + { + debug.set(set); + acquireWriteLock(); + try { + getData().getGeneral().setDebug(set); + } finally { + unlock(); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/settings/Spawns.java b/Essentials/src/com/earth2me/essentials/settings/Spawns.java index a0afa450c..451ef49b1 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Spawns.java +++ b/Essentials/src/com/earth2me/essentials/settings/Spawns.java @@ -1,18 +1,40 @@ package com.earth2me.essentials.settings; +import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.Location; import com.earth2me.essentials.storage.MapValueType; import com.earth2me.essentials.storage.StorageObject; import java.util.HashMap; import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; -import org.bukkit.Location; @Data @EqualsAndHashCode(callSuper = false) public class Spawns implements StorageObject { + @Comment( + { + "Should we announce to the server when someone logs in for the first time?", + "If so, use this format, replacing {DISPLAYNAME} with the player name.", + "If not, set to ''" + }) + private String newPlayerAnnouncement = "&dWelcome {DISPLAYNAME} to the server!"; + @Comment( + { + "Priority of the respawn event listener", + "Set this to lowest, if you want e.g. Multiverse to handle the respawning", + "Set this to normal, if you want EssentialsSpawn to handle the respawning", + "Set this to highest, if you want to force EssentialsSpawn to handle the respawning" + }) + private String respawnPriority = "normal"; + @Comment({ + "When we spawn for the first time, which spawnpoint do we use?", + "Set to none if you want to use the spawn point of the world." + }) + private String newbieSpawn = "none"; + @Comment("List of all spawnpoints") @MapValueType(Location.class) private Map<String, Location> spawns = new HashMap<String, Location>(); } diff --git a/Essentials/src/com/earth2me/essentials/settings/SpawnsHolder.java b/Essentials/src/com/earth2me/essentials/settings/SpawnsHolder.java new file mode 100644 index 000000000..19c9198da --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/SpawnsHolder.java @@ -0,0 +1,307 @@ +package com.earth2me.essentials.settings; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IEssentialsModule; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import com.earth2me.essentials.storage.Location.WorldNotLoadedException; +import com.earth2me.essentials.utils.textreader.IText; +import com.earth2me.essentials.utils.textreader.KeywordReplacer; +import com.earth2me.essentials.utils.textreader.SimpleTextInput; +import com.earth2me.essentials.utils.textreader.SimpleTextPager; +import java.io.File; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.logging.Level; +import org.bukkit.*; +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.plugin.EventExecutor; + + +public class SpawnsHolder extends AsyncStorageObjectHolder<Spawns> implements IEssentialsModule +{ + public SpawnsHolder(final IEssentials ess) + { + super(ess, Spawns.class); + onReload(); + registerListeners(); + } + + @Override + public File getStorageFile() + { + return new File(ess.getDataFolder(), "spawn.yml"); + } + + public void setSpawn(final Location loc, final String group) + { + acquireWriteLock(); + try + { + if (getData().getSpawns() == null) + { + getData().setSpawns(new HashMap<String, com.earth2me.essentials.storage.Location>()); + } + getData().getSpawns().put(group.toLowerCase(Locale.ENGLISH), new com.earth2me.essentials.storage.Location(loc)); + } + finally + { + unlock(); + } + + if ("default".equalsIgnoreCase(group)) + { + loc.getWorld().setSpawnLocation(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + } + } + + public Location getSpawn(final String group) + { + acquireReadLock(); + try + { + if (getData().getSpawns() == null || group == null) + { + return getWorldSpawn(); + } + final Map<String, com.earth2me.essentials.storage.Location> spawnMap = getData().getSpawns(); + String groupName = group.toLowerCase(Locale.ENGLISH); + if (!spawnMap.containsKey(groupName)) + { + groupName = "default"; + } + if (!spawnMap.containsKey(groupName)) + { + return getWorldSpawn(); + } + try + { + return spawnMap.get(groupName).getBukkitLocation(); + } + catch (WorldNotLoadedException ex) + { + return getWorldSpawn(); + } + } + finally + { + unlock(); + } + } + + private Location getWorldSpawn() + { + for (World world : ess.getServer().getWorlds()) + { + if (world.getEnvironment() != World.Environment.NORMAL) + { + continue; + } + return world.getSpawnLocation(); + } + return ess.getServer().getWorlds().get(0).getSpawnLocation(); + } + + public EventPriority getRespawnPriority() + { + acquireReadLock(); + try + { + for (EventPriority priority : EventPriority.values()) + { + if (priority.toString().equalsIgnoreCase(getData().getRespawnPriority())) + { + return priority; + } + } + return EventPriority.NORMAL; + } + finally + { + unlock(); + } + } + + public Location getNewbieSpawn() + { + acquireReadLock(); + try + { + if (getData().getNewbieSpawn() == null || getData().getNewbieSpawn().isEmpty() + || getData().getNewbieSpawn().equalsIgnoreCase("none")) + { + return null; + } + return getSpawn(getData().getNewbieSpawn()); + } + finally + { + unlock(); + } + } + + public boolean getAnnounceNewPlayers() + { + acquireReadLock(); + try + { + return getData().getNewPlayerAnnouncement() != null && !getData().getNewPlayerAnnouncement().isEmpty(); + } + finally + { + unlock(); + } + } + + public String getAnnounceNewPlayerFormat(IUser user) + { + acquireReadLock(); + try + { + return getData().getNewPlayerAnnouncement().replace('&', '�').replace("��", "&").replace("{PLAYER}", user.getDisplayName()).replace("{DISPLAYNAME}", user.getDisplayName()).replace("{GROUP}", ess.getRanks().getMainGroup(user)).replace("{USERNAME}", user.getName()).replace("{ADDRESS}", user.getAddress().toString()); + } + finally + { + unlock(); + } + } + + private void registerListeners() + { + final SpawnPlayerListener playerListener = new SpawnPlayerListener(ess, this); + ess.getServer().getPluginManager().registerEvent(PlayerRespawnEvent.class, playerListener, getRespawnPriority(), new EventExecutor() + { + @Override + public void execute(final Listener ll, final Event event) throws EventException + { + ((SpawnPlayerListener)ll).onPlayerRespawn((PlayerRespawnEvent)event); + } + }, ess); + ess.getServer().getPluginManager().registerEvent(PlayerJoinEvent.class, playerListener, getRespawnPriority(), new EventExecutor() + { + @Override + public void execute(final Listener ll, final Event event) throws EventException + { + ((SpawnPlayerListener)ll).onPlayerJoin((PlayerJoinEvent)event); + } + }, ess); + } + + + private class SpawnPlayerListener implements Listener + { + private final transient IEssentials ess; + private final transient SpawnsHolder spawns; + + public SpawnPlayerListener(final IEssentials ess, final SpawnsHolder spawns) + { + super(); + this.ess = ess; + this.spawns = spawns; + } + + public void onPlayerRespawn(final PlayerRespawnEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + + boolean respawnAtHome = false; + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + respawnAtHome = ess.getSettings().getData().getCommands().getHome().isRespawnAtHome(); + } + finally + { + settings.unlock(); + } + if (respawnAtHome) + { + Location home; + final Location bed = user.getBedSpawnLocation(); + if (bed != null && bed.getBlock().getType() == Material.BED_BLOCK) + { + home = bed; + } + else + { + home = user.getHome(user.getLocation()); + } + if (home != null) + { + event.setRespawnLocation(home); + return; + } + } + final Location spawn = spawns.getSpawn(ess.getRanks().getMainGroup(user)); + if (spawn != null) + { + event.setRespawnLocation(spawn); + } + } + + public void onPlayerJoin(final PlayerJoinEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + + if (user.hasPlayedBefore()) + { + return; + } + + if (spawns.getNewbieSpawn() != null) + { + ess.scheduleSyncDelayedTask(new NewPlayerTeleport(user), 1L); + } + + if (spawns.getAnnounceNewPlayers()) + { + final IText output = new KeywordReplacer(new SimpleTextInput(spawns.getAnnounceNewPlayerFormat(user)), user, ess); + final SimpleTextPager pager = new SimpleTextPager(output); + ess.broadcastMessage(user, pager.getString(0)); + } + } + + + private class NewPlayerTeleport implements Runnable + { + private final transient IUser user; + + public NewPlayerTeleport(final IUser user) + { + this.user = user; + } + + @Override + public void run() + { + if (user.getBase() instanceof OfflinePlayer) + { + return; + } + + try + { + final Location spawn = spawns.getNewbieSpawn(); + if (spawn != null) + { + user.getTeleport().now(spawn, false, PlayerTeleportEvent.TeleportCause.PLUGIN); + } + } + catch (Exception ex) + { + Bukkit.getLogger().log(Level.WARNING, _("teleportNewPlayerError"), ex); + } + } + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/settings/Warp.java b/Essentials/src/com/earth2me/essentials/settings/Warp.java new file mode 100644 index 000000000..f9c506b58 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/Warp.java @@ -0,0 +1,14 @@ +package com.earth2me.essentials.settings; + +import com.earth2me.essentials.storage.Location; +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = false) +public class Warp implements StorageObject +{ + private String name; + private Location location; +} diff --git a/Essentials/src/com/earth2me/essentials/settings/WarpHolder.java b/Essentials/src/com/earth2me/essentials/settings/WarpHolder.java new file mode 100644 index 000000000..b6a9f2879 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/WarpHolder.java @@ -0,0 +1,35 @@ +package com.earth2me.essentials.settings; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IWarp; +import com.earth2me.essentials.api.InvalidNameException; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; + + +public class WarpHolder extends AsyncStorageObjectHolder<Warp> implements IWarp +{ + private final String name; + + public WarpHolder(String name, IEssentials ess) + { + super(ess, Warp.class); + this.name = name; + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + try + { + return ess.getWarps().getWarpFile(name); + } + catch (InvalidNameException ex) + { + throw new IOException(ex.getMessage(), ex); + } + } + +} diff --git a/Essentials/src/com/earth2me/essentials/settings/WorldOptions.java b/Essentials/src/com/earth2me/essentials/settings/WorldOptions.java new file mode 100644 index 000000000..33271b460 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/WorldOptions.java @@ -0,0 +1,14 @@ +package com.earth2me.essentials.settings; + +import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = false) +public class WorldOptions implements StorageObject +{ + @Comment("Disables godmode for all players if they teleport to this world.") + private boolean godmode = true; +} diff --git a/Essentials/src/com/earth2me/essentials/settings/Worlds.java b/Essentials/src/com/earth2me/essentials/settings/Worlds.java new file mode 100644 index 000000000..ed865d94b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/Worlds.java @@ -0,0 +1,12 @@ +package com.earth2me.essentials.settings; + +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = false) +public class Worlds implements StorageObject +{ + +}
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Afk.java b/Essentials/src/com/earth2me/essentials/settings/commands/Afk.java index 80cae7e8a..f46e52d52 100644 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Afk.java +++ b/Essentials/src/com/earth2me/essentials/settings/commands/Afk.java @@ -15,14 +15,14 @@ public class Afk implements StorageObject "After this timeout in seconds, the user will be set as afk.", "Set to -1 for no timeout." }) - private int autoAFK = 300; + private long autoAFK = 300; @Comment( { "Auto-AFK Kick", "After this timeout in seconds, the user will be kicked from the server.", "Set to -1 for no timeout." }) - private int autoAFKKick = -1; + private long autoAFKKick = -1; @Comment( { "Set this to true, if you want to freeze the player, if he is afk.", @@ -33,4 +33,6 @@ public class Afk implements StorageObject "since the player will not get a message, if he tries to move." }) private boolean freezeAFKPlayers = false; + + private boolean disableItemPickupWhileAfk = true; } diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Back.java b/Essentials/src/com/earth2me/essentials/settings/commands/Back.java new file mode 100644 index 000000000..bd2afdd62 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/commands/Back.java @@ -0,0 +1,19 @@ +package com.earth2me.essentials.settings.commands; + +import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Back implements StorageObject +{ + @Comment( + { + "Do you want essentials to keep track of previous location for /back in the teleport listener?", + "If you set this to true any plugin that uses teleport will have the previous location registered." + }) + private boolean registerBackInListener = false; +} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Home.java b/Essentials/src/com/earth2me/essentials/settings/commands/Home.java index 8b3a0ca82..b856c881b 100644 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Home.java +++ b/Essentials/src/com/earth2me/essentials/settings/commands/Home.java @@ -21,4 +21,6 @@ public class Home implements StorageObject private boolean bedSetsHome = false; @Comment("If no home is set, should the player be send to spawn, when /home is used.") private boolean spawnIfNoHome = false; + @Comment("Allows people to set their bed at daytime") + private boolean updateBedAtDaytime = true; } diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/List.java b/Essentials/src/com/earth2me/essentials/settings/commands/List.java new file mode 100644 index 000000000..ca2c61d2d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/commands/List.java @@ -0,0 +1,16 @@ +package com.earth2me.essentials.settings.commands; + + +import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class List implements StorageObject +{ + @Comment("Sort output of /list command by groups") + private boolean sortByGroups = true; +} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Tpa.java b/Essentials/src/com/earth2me/essentials/settings/commands/Tpa.java new file mode 100644 index 000000000..88cbc9a6b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/commands/Tpa.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.settings.commands; + +import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Tpa implements StorageObject +{ + @Comment( + { + "Set timeout in seconds for players to accept tpa before request is cancelled.", + "Set to 0 for no timeout." + }) + private int timeout = 0; + @Comment({"Cancels a request made by tpa / tphere on world change to prevent cross world tp"}) + private boolean cancelTpRequestsOnWorldChange = false; +} diff --git a/Essentials/src/com/earth2me/essentials/settings/geoip/Database.java b/Essentials/src/com/earth2me/essentials/settings/geoip/Database.java new file mode 100644 index 000000000..0e883d0bd --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/geoip/Database.java @@ -0,0 +1,16 @@ +package com.earth2me.essentials.settings.geoip; + +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Database implements StorageObject +{ + boolean showCities = false; + boolean downloadIfMissing = true; + String downloadUrlCity = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz"; + String downloadUrl = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz"; +} diff --git a/Essentials/src/com/earth2me/essentials/settings/geoip/GeoIP.java b/Essentials/src/com/earth2me/essentials/settings/geoip/GeoIP.java new file mode 100644 index 000000000..65a909ed4 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/geoip/GeoIP.java @@ -0,0 +1,15 @@ +package com.earth2me.essentials.settings.geoip; + +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class GeoIP implements StorageObject +{ + private Database database = new Database(); + boolean showOnWhois = true; + boolean showOnLogin = true; +} diff --git a/Essentials/src/com/earth2me/essentials/settings/protect/Prevent.java b/Essentials/src/com/earth2me/essentials/settings/protect/Prevent.java new file mode 100644 index 000000000..192e93ac1 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/protect/Prevent.java @@ -0,0 +1,45 @@ +package com.earth2me.essentials.settings.protect; + +import com.earth2me.essentials.storage.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Material; +import org.bukkit.entity.CreatureType; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Prevent implements StorageObject +{ + @Comment("Which blocks should a piston not be able to push?") + @ListType(Material.class) + private Set<Material> pistonPush = new HashSet<Material>(); + private boolean lavaFlow = false; + private boolean waterFlow = false; + // private boolean waterbucketFlow = false; TODO: Test if this still works + private boolean firespread = true; + private boolean lavaFirespread = true; + private boolean lightningFirespread = true; + private boolean portalCreation = false; + private boolean tntExplosion = false; + private boolean fireballExplosion = false; + private boolean fireballFire = false; + private boolean creeperExplosion = false; + private boolean creeperBlockdamage = false; + private boolean enderdragonBlockdamage = false; + private boolean endermanPickup = false; + private boolean villagerDeath = false; + @Comment( + { + "Monsters won't follow players", + "permission essentials.protect.entitytarget.bypass disables this" + }) + private boolean entitytarget = false; + @MapKeyType(CreatureType.class) + @MapValueType(Boolean.class) + private Map<CreatureType, Boolean> spawn = new HashMap<CreatureType, Boolean>(); +}
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/settings/protect/Protect.java b/Essentials/src/com/earth2me/essentials/settings/protect/Protect.java new file mode 100644 index 000000000..bb745ad8f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/protect/Protect.java @@ -0,0 +1,45 @@ +package com.earth2me.essentials.settings.protect; + +import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.ListType; +import com.earth2me.essentials.storage.StorageObject; +import java.util.HashSet; +import java.util.Set; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Material; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Protect implements StorageObject +{ + @Comment("Either mysql or sqlite") + private String dbtype = "sqlite"; + @Comment("If you specified MySQL above, you MUST enter the appropriate details here.") + private String dbuser = "root"; + private String dbpassword = ""; + private String dburl = "jdbc:mysql://localhost:3306/minecraft"; + @Comment("For which block types would you like to be alerted?") + @ListType(Material.class) + private Set<Material> alertOnPlacement = new HashSet<Material>(); + @ListType(Material.class) + private Set<Material> alertOnUse = new HashSet<Material>(); + @ListType(Material.class) + private Set<Material> alertOnBreak = new HashSet<Material>(); + @Comment("General physics/behavior modifications") + private Prevent prevent = new Prevent(); + @Comment( + { + "Maximum height the creeper should explode. -1 allows them to explode everywhere.", + "Set prevent.creeper-explosion to true, if you want to disable creeper explosions." + }) + private int creeperMaxHeight = -1; + @Comment("Should we tell people they are not allowed to build") + private boolean warnOnBuildDisallow = true; + @Comment("Disable weather options") + private boolean disableStorm = false; + private boolean disableThunder = false; + private boolean disableLighting = false; + private SignsAndRails signsAndRails = new SignsAndRails(); +} diff --git a/Essentials/src/com/earth2me/essentials/settings/protect/SignsAndRails.java b/Essentials/src/com/earth2me/essentials/settings/protect/SignsAndRails.java new file mode 100644 index 000000000..dae3897c2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/protect/SignsAndRails.java @@ -0,0 +1,26 @@ +package com.earth2me.essentials.settings.protect; + +import com.earth2me.essentials.storage.Comment; +import com.earth2me.essentials.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class SignsAndRails implements StorageObject +{ + @Comment("Protect all signs") + private boolean protectSigns = true; + @Comment("Prevent users from destroying rails") + private boolean protectRails = true; + @Comment( + { + "Blocks below rails/signs are also protected if the respective rail/sign is protected.", + "This makes it more difficult to circumvent protection, and should be enabled.", + "This only has an effect if rails or signs is also enabled." + }) + private boolean blockBelow = true; + @Comment("Prevent placing blocks above protected rails, this is to stop a potential griefing") + private boolean preventBlockAboveRails = false; +} diff --git a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java b/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java deleted file mode 100644 index 21e70516e..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java +++ /dev/null @@ -1,515 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.*; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsSign -{ - private static final Set<Material> EMPTY_SET = new HashSet<Material>(); - protected transient final String signName; - - public EssentialsSign(final String signName) - { - this.signName = signName; - } - - public final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess) - { - final ISign sign = new EventSign(event); - final User user = ess.getUser(event.getPlayer()); - if (!(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".create") - || user.isAuthorized("essentials.signs.create." + signName.toLowerCase(Locale.ENGLISH)))) - { - // Return true, so other plugins can use the same sign title, just hope - // they won't change it to §1[Signname] - return true; - } - sign.setLine(0, _("signFormatFail", this.signName)); - try - { - final boolean ret = onSignCreate(sign, user, getUsername(user), ess); - if (ret) - { - sign.setLine(0, getSuccessName()); - } - return ret; - } - catch (ChargeException ex) - { - ess.showError(user, ex, signName); - } - catch (SignException ex) - { - ess.showError(user, ex, signName); - } - // Return true, so the player sees the wrong sign. - return true; - } - - public String getSuccessName() - { - return _("signFormatSuccess", this.signName); - } - - public String getTemplateName() - { - return _("signFormatTemplate", this.signName); - } - - private String getUsername(final User user) - { - return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length()); - } - - public final boolean onSignInteract(final Block block, final Player player, final IEssentials ess) - { - final ISign sign = new BlockSign(block); - final User user = ess.getUser(player); - try - { - return (user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".use") - || user.isAuthorized("essentials.signs.use." + signName.toLowerCase(Locale.ENGLISH))) - && onSignInteract(sign, user, getUsername(user), ess); - } - catch (ChargeException ex) - { - ess.showError(user, ex, signName); - return false; - } - catch (SignException ex) - { - ess.showError(user, ex, signName); - return false; - } - } - - public final boolean onSignBreak(final Block block, final Player player, final IEssentials ess) - { - final ISign sign = new BlockSign(block); - final User user = ess.getUser(player); - try - { - return (user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".break") - || user.isAuthorized("essentials.signs.break." + signName.toLowerCase(Locale.ENGLISH))) - && onSignBreak(sign, user, getUsername(user), ess); - } - catch (SignException ex) - { - ess.showError(user, ex, signName); - return false; - } - } - - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - return true; - } - - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - return true; - } - - protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - return true; - } - - public final boolean onBlockPlace(final Block block, final Player player, final IEssentials ess) - { - User user = ess.getUser(player); - try - { - return onBlockPlace(block, user, getUsername(user), ess); - } - catch (ChargeException ex) - { - ess.showError(user, ex, signName); - } - catch (SignException ex) - { - ess.showError(user, ex, signName); - } - return false; - } - - public final boolean onBlockInteract(final Block block, final Player player, final IEssentials ess) - { - User user = ess.getUser(player); - try - { - return onBlockInteract(block, user, getUsername(user), ess); - } - catch (ChargeException ex) - { - ess.showError(user, ex, signName); - } - catch (SignException ex) - { - ess.showError(user, ex, signName); - } - return false; - } - - public final boolean onBlockBreak(final Block block, final Player player, final IEssentials ess) - { - User user = ess.getUser(player); - try - { - return onBlockBreak(block, user, getUsername(user), ess); - } - catch (SignException ex) - { - ess.showError(user, ex, signName); - } - return false; - } - - public boolean onBlockBreak(final Block block, final IEssentials ess) - { - return true; - } - - public boolean onBlockExplode(final Block block, final IEssentials ess) - { - return true; - } - - public boolean onBlockBurn(final Block block, final IEssentials ess) - { - return true; - } - - public boolean onBlockIgnite(final Block block, final IEssentials ess) - { - return true; - } - - public boolean onBlockPush(final Block block, final IEssentials ess) - { - return true; - } - - public static boolean checkIfBlockBreaksSigns(final Block block) - { - final Block sign = block.getRelative(BlockFace.UP); - if (sign.getType() == Material.SIGN_POST && isValidSign(new BlockSign(sign))) - { - return true; - } - final BlockFace[] directions = new BlockFace[] - { - BlockFace.NORTH, - BlockFace.EAST, - BlockFace.SOUTH, - BlockFace.WEST - }; - for (BlockFace blockFace : directions) - { - final Block signblock = block.getRelative(blockFace); - if (signblock.getType() == Material.WALL_SIGN) - { - final org.bukkit.material.Sign signMat = (org.bukkit.material.Sign)signblock.getState().getData(); - if (signMat != null && signMat.getFacing() == blockFace && isValidSign(new BlockSign(signblock))) - { - return true; - } - } - } - return false; - } - - public static boolean isValidSign(final ISign sign) - { - return sign.getLine(0).matches("§1\\[.*\\]"); - } - - protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - return true; - } - - protected boolean onBlockInteract(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - return true; - } - - protected boolean onBlockBreak(final Block block, final User player, final String username, final IEssentials ess) throws SignException - { - return true; - } - - public Set<Material> getBlocks() - { - return EMPTY_SET; - } - - protected final void validateTrade(final ISign sign, final int index, final IEssentials ess) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - return; - } - final Trade trade = getTrade(sign, index, 0, ess); - final Double money = trade.getMoney(); - if (money != null) - { - sign.setLine(index, Util.shortCurrency(money, ess)); - } - } - - protected final void validateTrade(final ISign sign, final int amountIndex, final int itemIndex, - final User player, final IEssentials ess) throws SignException - { - if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) - { - int amount = getIntegerPositive(sign.getLine(amountIndex)); - sign.setLine(amountIndex, Integer.toString(amount)); - sign.setLine(itemIndex, "exp"); - return; - } - final Trade trade = getTrade(sign, amountIndex, itemIndex, player, ess); - final ItemStack item = trade.getItemStack(); - sign.setLine(amountIndex, Integer.toString(item.getAmount())); - sign.setLine(itemIndex, sign.getLine(itemIndex).trim()); - } - - protected final Trade getTrade(final ISign sign, final int amountIndex, final int itemIndex, - final User player, final IEssentials ess) throws SignException - { - if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) - { - final int amount = getIntegerPositive(sign.getLine(amountIndex)); - return new Trade(amount, ess); - } - final ItemStack item = getItemStack(sign.getLine(itemIndex), 1, ess); - final int amount = Math.min(getIntegerPositive(sign.getLine(amountIndex)), item.getType().getMaxStackSize() * player.getInventory().getSize()); - if (item.getTypeId() == 0 || amount < 1) - { - throw new SignException(_("moreThanZero")); - } - item.setAmount(amount); - return new Trade(item, ess); - } - - protected final void validateInteger(final ISign sign, final int index) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - throw new SignException("Empty line " + index); - } - final int quantity = getIntegerPositive(line); - sign.setLine(index, Integer.toString(quantity)); - } - - protected final int getIntegerPositive(final String line) throws SignException - { - final int quantity = getInteger(line); - if (quantity < 1) - { - throw new SignException(_("moreThanZero")); - } - return quantity; - } - - protected final int getInteger(final String line) throws SignException - { - try - { - final int quantity = Integer.parseInt(line); - - return quantity; - } - catch (NumberFormatException ex) - { - throw new SignException("Invalid sign", ex); - } - } - - protected final ItemStack getItemStack(final String itemName, final int quantity, final IEssentials ess) throws SignException - { - try - { - final ItemStack item = ess.getItemDb().get(itemName); - item.setAmount(quantity); - return item; - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - } - - protected final Double getMoney(final String line) throws SignException - { - final boolean isMoney = line.matches("^[^0-9-\\.][\\.0-9]+$"); - return isMoney ? getDoublePositive(line.substring(1)) : null; - } - - protected final Double getDoublePositive(final String line) throws SignException - { - final double quantity = getDouble(line); - if (Math.round(quantity * 100.0) < 1.0) - { - throw new SignException(_("moreThanZero")); - } - return quantity; - } - - protected final Double getDouble(final String line) throws SignException - { - try - { - return Double.parseDouble(line); - } - catch (NumberFormatException ex) - { - throw new SignException(ex.getMessage(), ex); - } - } - - protected final Trade getTrade(final ISign sign, final int index, final IEssentials ess) throws SignException - { - return getTrade(sign, index, 1, ess); - } - - protected final Trade getTrade(final ISign sign, final int index, final int decrement, final IEssentials ess) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); - } - - final Double money = getMoney(line); - if (money == null) - { - final String[] split = line.split("[ :]+", 2); - if (split.length != 2) - { - throw new SignException(_("invalidCharge")); - } - final int quantity = getIntegerPositive(split[0]); - - final String item = split[1].toLowerCase(Locale.ENGLISH); - if (item.equalsIgnoreCase("times")) - { - sign.setLine(index, (quantity - decrement) + " times"); - return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); - } - else if (item.equalsIgnoreCase("exp") || item.equalsIgnoreCase("xp")) - { - sign.setLine(index, quantity + " exp"); - return new Trade(quantity, ess); - } - else - { - final ItemStack stack = getItemStack(item, quantity, ess); - sign.setLine(index, quantity + " " + item); - return new Trade(stack, ess); - } - } - else - { - return new Trade(money, ess); - } - } - - - static class EventSign implements ISign - { - private final transient SignChangeEvent event; - private final transient Block block; - - public EventSign(final SignChangeEvent event) - { - this.event = event; - this.block = event.getBlock(); - } - - @Override - public final String getLine(final int index) - { - return event.getLine(index); - } - - @Override - public final void setLine(final int index, final String text) - { - event.setLine(index, text); - } - - @Override - public Block getBlock() - { - return block; - } - - @Override - public void updateSign() - { - } - } - - - static class BlockSign implements ISign - { - private final transient Sign sign; - private final transient Block block; - - public BlockSign(final Block block) - { - this.block = block; - this.sign = (Sign)block.getState(); - } - - @Override - public final String getLine(final int index) - { - return sign.getLine(index); - } - - @Override - public final void setLine(final int index, final String text) - { - sign.setLine(index, text); - } - - @Override - public final Block getBlock() - { - return block; - } - - @Override - public final void updateSign() - { - sign.update(); - } - } - - - public interface ISign - { - String getLine(final int index); - - void setLine(final int index, final String text); - - public Block getBlock(); - - void updateSign(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBalance.java b/Essentials/src/com/earth2me/essentials/signs/SignBalance.java deleted file mode 100644 index 4949cb645..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignBalance.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; - - -public class SignBalance extends EssentialsSign -{ - public SignBalance() - { - super("Balance"); - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - player.sendMessage(_("balance", Util.displayCurrency(player.getMoney(), ess))); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java b/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java deleted file mode 100644 index ccd40b214..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.*; - - -public class SignBlockListener implements Listener -{ - private final transient IEssentials ess; - private final static Logger LOGGER = Logger.getLogger("Minecraft"); - private final static int WALL_SIGN = Material.WALL_SIGN.getId(); - private final static int SIGN_POST = Material.SIGN_POST.getId(); - - public SignBlockListener(IEssentials ess) - { - this.ess = ess; - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBreak(final BlockBreakEvent event) - { - if (ess.getSettings().areSignsDisabled()) - { - return; - } - - if (protectSignsAndBlocks(event.getBlock(), event.getPlayer())) - { - event.setCancelled(true); - } - } - - public boolean protectSignsAndBlocks(final Block block, final Player player) - { - final int mat = block.getTypeId(); - if (mat == SIGN_POST || mat == WALL_SIGN) - { - final Sign csign = (Sign)block.getState(); - - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName()) - && !sign.onSignBreak(block, player, ess)) - { - return true; - } - } - } - // prevent any signs be broken by destroying the block they are attached to - if (EssentialsSign.checkIfBlockBreaksSigns(block)) - { - LOGGER.log(Level.INFO, "Prevented that a block was broken next to a sign."); - return true; - } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockBreak(block, player, ess)) - { - LOGGER.log(Level.INFO, "A block was protected by a sign."); - return true; - } - } - return false; - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onSignChange(final SignChangeEvent event) - { - if (ess.getSettings().areSignsDisabled()) - { - return; - } - User user = ess.getUser(event.getPlayer()); - - for (int i = 0; i < 4; i++) - { - event.setLine(i, Util.formatString(user, "essentials.signs", event.getLine(i))); - } - - for (Signs signs : Signs.values()) - { - final EssentialsSign sign = signs.getSign(); - if (event.getLine(0).equalsIgnoreCase(sign.getSuccessName())) - { - event.setCancelled(true); - return; - } - if (event.getLine(0).equalsIgnoreCase(sign.getTemplateName()) - && !sign.onSignCreate(event, ess)) - { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockPlace(final BlockPlaceEvent event) - { - if (ess.getSettings().areSignsDisabled()) - { - return; - } - - final Block against = event.getBlockAgainst(); - if ((against.getTypeId() == WALL_SIGN - || against.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(against))) - { - event.setCancelled(true); - return; - } - final Block block = event.getBlock(); - if (block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - { - return; - } - for (Signs signs : Signs.values()) - { - final EssentialsSign sign = signs.getSign(); - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockPlace(block, event.getPlayer(), ess)) - { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockBurn(final BlockBurnEvent event) - { - if (ess.getSettings().areSignsDisabled()) - { - return; - } - - final Block block = event.getBlock(); - if (((block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockBurn(block, ess)) - { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockIgnite(final BlockIgniteEvent event) - { - if (ess.getSettings().areSignsDisabled()) - { - return; - } - - final Block block = event.getBlock(); - if (((block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockIgnite(block, ess)) - { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockPistonExtend(final BlockPistonExtendEvent event) - { - for (Block block : event.getBlocks()) - { - if (((block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockPush(block, ess)) - { - event.setCancelled(true); - return; - } - } - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockPistonRetract(final BlockPistonRetractEvent event) - { - if (event.isSticky()) - { - final Block block = event.getBlock(); - if (((block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockPush(block, ess)) - { - event.setCancelled(true); - return; - } - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBuy.java b/Essentials/src/com/earth2me/essentials/signs/SignBuy.java deleted file mode 100644 index aa4e41426..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignBuy.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; - - -public class SignBuy extends EssentialsSign -{ - public SignBuy() - { - super("Buy"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 1, 2, player, ess); - validateTrade(sign, 3, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade items = getTrade(sign, 1, 2, player, ess); - final Trade charge = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - if (!items.pay(player, false)) - { - throw new ChargeException("Inventory full"); - } - charge.charge(player); - Trade.log("Sign", "Buy", "Interact", username, charge, username, items, sign.getBlock().getLocation(), ess); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java b/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java deleted file mode 100644 index f44c6177a..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; - - -public class SignDisposal extends EssentialsSign -{ - public SignDisposal() - { - super("Disposal"); - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) - { - player.getBase().openInventory(ess.getServer().createInventory(player, 36)); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java b/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java deleted file mode 100644 index a50ce967a..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import com.earth2me.essentials.Enchantments; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import java.util.Locale; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; - - -public class SignEnchant extends EssentialsSign -{ - public SignEnchant() - { - super("Enchant"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final ItemStack stack = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess); - final String[] enchantLevel = sign.getLine(2).split(":"); - if (enchantLevel.length != 2) - { - throw new SignException(_("invalidSignLine", 3)); - } - final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]); - if (enchantment == null) - { - throw new SignException(_("enchantmentNotFound")); - } - int level; - try - { - level = Integer.parseInt(enchantLevel[1]); - } - catch (NumberFormatException ex) - { - throw new SignException(ex.getMessage(), ex); - } - if (level < 1 || level > enchantment.getMaxLevel()) - { - level = enchantment.getMaxLevel(); - sign.setLine(2, enchantLevel[0] + ":" + level); - } - try - { - if (stack != null) - { - stack.addEnchantment(enchantment, level); - } - } - catch (Throwable ex) - { - throw new SignException(ex.getMessage(), ex); - } - getTrade(sign, 3, ess); - return true; - } - - @Override - protected boolean onSignInteract(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException - { - final ItemStack search = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess); - int slot = -1; - final Trade charge = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - final String[] enchantLevel = sign.getLine(2).split(":"); - if (enchantLevel.length != 2) - { - throw new SignException(_("invalidSignLine", 3)); - } - final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]); - if (enchantment == null) - { - throw new SignException(_("enchantmentNotFound")); - } - int level; - try - { - level = Integer.parseInt(enchantLevel[1]); - } - catch (NumberFormatException ex) - { - level = enchantment.getMaxLevel(); - } - - final ItemStack playerHand = player.getItemInHand(); - if (playerHand == null - || playerHand.getAmount() != 1 - || (playerHand.containsEnchantment(enchantment) - && playerHand.getEnchantmentLevel(enchantment) == level)) - { - throw new SignException(_("missingItems", 1, sign.getLine(1))); - } - if (search != null && playerHand.getType() != search.getType()) - { - throw new SignException(_("missingItems", 1, search.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '))); - } - - final ItemStack toEnchant = playerHand; - try - { - toEnchant.addEnchantment(enchantment, level); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - - charge.charge(player); - Trade.log("Sign", "Enchant", "Interact", username, charge, username, charge, sign.getBlock().getLocation(), ess); - player.updateInventory(); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java b/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java deleted file mode 100644 index 5a6ee177d..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.IEssentials; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityExplodeEvent; - - -public class SignEntityListener implements Listener -{ - private final transient IEssentials ess; - - public SignEntityListener(final IEssentials ess) - { - this.ess = ess; - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityExplode(final EntityExplodeEvent event) - { - for (Block block : event.blockList()) - { - if (((block.getTypeId() == Material.WALL_SIGN.getId() - || block.getTypeId() == Material.SIGN_POST.getId()) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (sign.getBlocks().contains(block.getType())) - { - event.setCancelled(!sign.onBlockExplode(block, ess)); - return; - } - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onEntityChangeBlock(final EntityChangeBlockEvent event) - { - if (ess.getSettings().areSignsDisabled()) - { - return; - } - - final Block block = event.getBlock(); - if (((block.getTypeId() == Material.WALL_SIGN.getId() - || block.getTypeId() == Material.SIGN_POST.getId()) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockBreak(block, ess)) - { - event.setCancelled(true); - return; - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignException.java b/Essentials/src/com/earth2me/essentials/signs/SignException.java deleted file mode 100644 index 9c9ab44a2..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.earth2me.essentials.signs; - - -public class SignException extends Exception -{ - public SignException(final String message) - { - super(message); - } - - public SignException(final String message, final Throwable throwable) - { - super(message, throwable); - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignFree.java b/Essentials/src/com/earth2me/essentials/signs/SignFree.java deleted file mode 100644 index 24ce481ff..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignFree.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import org.bukkit.Material; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - - -public class SignFree extends EssentialsSign -{ - public SignFree() - { - super("Free"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - getItemStack(sign.getLine(1), 1, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - final ItemStack item = getItemStack(sign.getLine(1), 1, ess); - if (item.getType() == Material.AIR) - { - throw new SignException(_("cantSpawnItem", "Air")); - } - - item.setAmount(item.getType().getMaxStackSize()); - Inventory invent = ess.getServer().createInventory(player, 36); - for (int i = 0; i < 36; i++) { - invent.addItem(item); - } - player.openInventory(invent); - Trade.log("Sign", "Free", "Interact", username, null, username, new Trade(item, ess), sign.getBlock().getLocation(), ess); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java b/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java deleted file mode 100644 index 37a9fb1b8..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import java.util.Locale; -import org.bukkit.GameMode; - - -public class SignGameMode extends EssentialsSign -{ - public SignGameMode() - { - super("GameMode"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 1, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 1, ess); - charge.isAffordableFor(player); - - player.setGameMode(player.getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : GameMode.SURVIVAL); - player.sendMessage(_("gameMode", _(player.getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName())); - charge.charge(player); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignHeal.java b/Essentials/src/com/earth2me/essentials/signs/SignHeal.java deleted file mode 100644 index be8b7ba1d..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignHeal.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; - - -public class SignHeal extends EssentialsSign -{ - public SignHeal() - { - super("Heal"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 1, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 1, ess); - charge.isAffordableFor(player); - player.setHealth(20); - player.setFoodLevel(20); - player.setFireTicks(0); - player.sendMessage(_("youAreHealed")); - charge.charge(player); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignKit.java b/Essentials/src/com/earth2me/essentials/signs/SignKit.java deleted file mode 100644 index c1a4cd0fd..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignKit.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.*; -import java.util.List; -import java.util.Locale; -import java.util.Map; - - -public class SignKit extends EssentialsSign -{ - public SignKit() - { - super("Kit"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 3, ess); - - final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH); - - if (kitName.isEmpty()) - { - sign.setLine(1, "§dKit name!"); - return false; - } - else - { - try - { - ess.getSettings().getKit(kitName); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - final String group = sign.getLine(2); - if ("Everyone".equalsIgnoreCase(group) || "Everybody".equalsIgnoreCase(group)) - { - sign.setLine(2, "§2Everyone"); - } - return true; - } - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH); - final String group = sign.getLine(2); - if ((!group.isEmpty() && ("§2Everyone".equals(group) || player.inGroup(group))) - || (group.isEmpty() && (player.isAuthorized("essentials.kit." + kitName)))) - { - final Trade charge = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - try - { - final Map<String, Object> kit = ess.getSettings().getKit(kitName); - Kit.checkTime(player, kitName, kit); - final List<String> items = Kit.getItems(player, kit); - Kit.expandItems(ess, player, items); - charge.charge(player); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - return true; - } - return false; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignMail.java b/Essentials/src/com/earth2me/essentials/signs/SignMail.java deleted file mode 100644 index b220fb2f5..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignMail.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; -import java.util.List; - - -public class SignMail extends EssentialsSign -{ - public SignMail() - { - super("Mail"); - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - final List<String> mail = player.getMails(); - if (mail.isEmpty()) - { - player.sendMessage(_("noNewMail")); - return false; - } - for (String s : mail) - { - player.sendMessage(s); - } - player.sendMessage(_("markMailAsRead")); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java b/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java deleted file mode 100644 index d415ef6a8..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.IEssentials; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; - - -public class SignPlayerListener implements Listener -{ - private final transient IEssentials ess; - - public SignPlayerListener(final IEssentials ess) - { - this.ess = ess; - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerInteract(final PlayerInteractEvent event) - { - if (ess.getSettings().areSignsDisabled() || event.getAction() != Action.RIGHT_CLICK_BLOCK) - { - return; - } - final Block block = event.getClickedBlock(); - if (block == null) - { - return; - } - - final int mat = block.getTypeId(); - if (mat == Material.SIGN_POST.getId() || mat == Material.WALL_SIGN.getId()) - { - final Sign csign = (Sign)block.getState(); - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName())) - { - sign.onSignInteract(block, event.getPlayer(), ess); - event.setCancelled(true); - return; - } - } - } - else - { - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockInteract(block, event.getPlayer(), ess)) - { - event.setCancelled(true); - return; - } - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignProtection.java b/Essentials/src/com/earth2me/essentials/signs/SignProtection.java deleted file mode 100644 index 2f2d25c46..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignProtection.java +++ /dev/null @@ -1,350 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import java.util.*; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.Sign; -import org.bukkit.inventory.ItemStack; - - -public class SignProtection extends EssentialsSign -{ - private final transient Set<Material> protectedBlocks = EnumSet.noneOf(Material.class); - - public SignProtection() - { - super("Protection"); - protectedBlocks.add(Material.CHEST); - protectedBlocks.add(Material.BURNING_FURNACE); - protectedBlocks.add(Material.FURNACE); - protectedBlocks.add(Material.DISPENSER); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - sign.setLine(3, "§4" + username); - if (hasAdjacentBlock(sign.getBlock())) - { - final SignProtectionState state = isBlockProtected(sign.getBlock(), player, username, true); - if (state == SignProtectionState.NOSIGN || state == SignProtectionState.OWNER - || player.isAuthorized("essentials.signs.protection.override")) - { - sign.setLine(3, "§1" + username); - return true; - } - } - player.sendMessage(_("signProtectInvalidLocation")); - return false; - } - - @Override - protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - final SignProtectionState state = checkProtectionSign(sign, player, username); - return state == SignProtectionState.OWNER; - } - - public boolean hasAdjacentBlock(final Block block, final Block... ignoredBlocks) - { - final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) - { - for (Block ignoredBlock : ignoredBlocks) - { - if (b.getLocation().equals(ignoredBlock.getLocation())) - { - continue; - } - } - if (protectedBlocks.contains(b.getType())) - { - return true; - } - } - return false; - } - - private void checkIfSignsAreBroken(final Block block, final User player, final String username, final IEssentials ess) - { - final Map<Location, SignProtectionState> signs = getConnectedSigns(block, player, username, false); - for (Map.Entry<Location, SignProtectionState> entry : signs.entrySet()) - { - if (entry.getValue() != SignProtectionState.NOSIGN) - { - final Block sign = entry.getKey().getBlock(); - if (!hasAdjacentBlock(sign, block)) - { - block.setType(Material.AIR); - final Trade trade = new Trade(new ItemStack(Material.SIGN, 1), ess); - trade.pay(player); - } - } - } - } - - private Map<Location, SignProtectionState> getConnectedSigns(final Block block, final User user, final String username, boolean secure) - { - final Map<Location, SignProtectionState> signs = new HashMap<Location, SignProtectionState>(); - getConnectedSigns(block, signs, user, username, secure ? 4 : 2); - return signs; - } - - private void getConnectedSigns(final Block block, final Map<Location, SignProtectionState> signs, final User user, final String username, final int depth) - { - final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) - { - final Location loc = b.getLocation(); - if (signs.containsKey(loc)) - { - continue; - } - final SignProtectionState check = checkProtectionSign(b, user, username); - signs.put(loc, check); - - if (protectedBlocks.contains(b.getType()) && depth > 0) - { - getConnectedSigns(b, signs, user, username, depth - 1); - } - } - } - - - public enum SignProtectionState - { - NOT_ALLOWED, ALLOWED, NOSIGN, OWNER - } - - private SignProtectionState checkProtectionSign(final Block block, final User user, final String username) - { - if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) - { - final BlockSign sign = new BlockSign(block); - if (sign.getLine(0).equals(this.getSuccessName())) - { - return checkProtectionSign(sign, user, username); - } - } - return SignProtectionState.NOSIGN; - } - - private SignProtectionState checkProtectionSign(final ISign sign, final User user, final String username) - { - if (user == null || username == null) - { - return SignProtectionState.NOT_ALLOWED; - } - if (user.isAuthorized("essentials.signs.protection.override")) - { - return SignProtectionState.OWNER; - } - if (Util.stripFormat(sign.getLine(3)).equalsIgnoreCase(username)) - { - return SignProtectionState.OWNER; - } - for (int i = 1; i <= 2; i++) - { - final String line = sign.getLine(i); - if (line.startsWith("(") && line.endsWith(")") && user.inGroup(line.substring(1, line.length() - 1))) - { - return SignProtectionState.ALLOWED; - } - else if (line.equalsIgnoreCase(username)) - { - return SignProtectionState.ALLOWED; - } - } - return SignProtectionState.NOT_ALLOWED; - } - - private Block[] getAdjacentBlocks(final Block block) - { - return new Block[] - { - block.getRelative(BlockFace.NORTH), - block.getRelative(BlockFace.SOUTH), - block.getRelative(BlockFace.EAST), - block.getRelative(BlockFace.WEST), - block.getRelative(BlockFace.DOWN), - block.getRelative(BlockFace.UP) - }; - } - - public SignProtectionState isBlockProtected(final Block block, final User user, final String username, boolean secure) - { - final Map<Location, SignProtectionState> signs = getConnectedSigns(block, user, username, secure); - SignProtectionState retstate = SignProtectionState.NOSIGN; - for (SignProtectionState state : signs.values()) - { - if (state == SignProtectionState.ALLOWED) - { - retstate = state; - } - else if (state == SignProtectionState.NOT_ALLOWED && retstate != SignProtectionState.ALLOWED) - { - retstate = state; - } - } - if (!secure || retstate == SignProtectionState.NOSIGN) - { - for (SignProtectionState state : signs.values()) - { - if (state == SignProtectionState.OWNER) - { - return state; - } - } - } - return retstate; - } - - public boolean isBlockProtected(final Block block) - { - final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) - { - if (b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN) - { - final Sign sign = (Sign)b.getState(); - if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) - { - return true; - } - } - if (protectedBlocks.contains(b.getType())) - { - final Block[] faceChest = getAdjacentBlocks(b); - - for (Block a : faceChest) - { - if (a.getType() == Material.SIGN_POST || a.getType() == Material.WALL_SIGN) - { - final Sign sign = (Sign)a.getState(); - if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) - { - return true; - } - } - } - } - } - return false; - } - - @Override - public Set<Material> getBlocks() - { - return protectedBlocks; - } - - @Override - protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException - { - for (Block adjBlock : getAdjacentBlocks(block)) - { - final SignProtectionState state = isBlockProtected(adjBlock, player, username, true); - - if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) - && !player.isAuthorized("essentials.signs.protection.override")) - { - player.sendMessage(_("noPlacePermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); - return false; - } - } - return true; - - } - - @Override - protected boolean onBlockInteract(final Block block, final User player, final String username, final IEssentials ess) throws SignException - { - final SignProtectionState state = isBlockProtected(block, player, username, false); - - if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN || state == SignProtectionState.ALLOWED) - { - return true; - } - - if (state == SignProtectionState.NOT_ALLOWED - && player.isAuthorized("essentials.signs.protection.override")) - { - return true; - } - - - player.sendMessage(_("noAccessPermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); - return false; - } - - @Override - protected boolean onBlockBreak(final Block block, final User player, final String username, final IEssentials ess) throws SignException - { - final SignProtectionState state = isBlockProtected(block, player, username, false); - - if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN) - { - checkIfSignsAreBroken(block, player, username, ess); - return true; - } - - if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) - && player.isAuthorized("essentials.signs.protection.override")) - { - checkIfSignsAreBroken(block, player, username, ess); - return true; - } - - - player.sendMessage(_("noDestroyPermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); - return false; - } - - @Override - public boolean onBlockBreak(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false); - - return state == SignProtectionState.NOSIGN; - } - - @Override - public boolean onBlockExplode(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false); - - return state == SignProtectionState.NOSIGN; - } - - @Override - public boolean onBlockBurn(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false); - - return state == SignProtectionState.NOSIGN; - } - - @Override - public boolean onBlockIgnite(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false); - - return state == SignProtectionState.NOSIGN; - } - - @Override - public boolean onBlockPush(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false); - - return state == SignProtectionState.NOSIGN; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignSell.java b/Essentials/src/com/earth2me/essentials/signs/SignSell.java deleted file mode 100644 index 442a503c2..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignSell.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; - - -public class SignSell extends EssentialsSign -{ - public SignSell() - { - super("Sell"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 1, 2, player, ess); - validateTrade(sign, 3, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 1, 2, player, ess); - final Trade money = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - money.pay(player); - charge.charge(player); - Trade.log("Sign", "Sell", "Interact", username, charge, username, money, sign.getBlock().getLocation(), ess); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java b/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java deleted file mode 100644 index 7c4cfcd54..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import com.earth2me.essentials.commands.Commandspawnmob; - - -public class SignSpawnmob extends EssentialsSign -{ - public SignSpawnmob() - { - super("Spawnmob"); - } - - @Override - protected boolean onSignCreate(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException - { - validateInteger(sign, 1); - validateTrade(sign, 3, ess); - return true; - } - - @Override - protected boolean onSignInteract(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - Commandspawnmob command = new Commandspawnmob(); - command.setEssentials(ess); - String[] args = new String[] - { - sign.getLine(2), sign.getLine(1) - }; - try - { - command.run(ess.getServer(), player, "spawnmob", args); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - charge.charge(player); - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignTime.java b/Essentials/src/com/earth2me/essentials/signs/SignTime.java deleted file mode 100644 index 99c579ff4..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignTime.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; - - -public class SignTime extends EssentialsSign -{ - public SignTime() - { - super("Time"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 2, ess); - final String timeString = sign.getLine(1); - if ("Day".equalsIgnoreCase(timeString)) - { - sign.setLine(1, "§2Day"); - return true; - } - if ("Night".equalsIgnoreCase(timeString)) - { - sign.setLine(1, "§2Night"); - return true; - } - throw new SignException(_("onlyDayNight")); - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 2, ess); - charge.isAffordableFor(player); - final String timeString = sign.getLine(1); - long time = player.getWorld().getTime(); - time -= time % 24000; - if ("§2Day".equalsIgnoreCase(timeString)) - { - player.getWorld().setTime(time + 24000); - charge.charge(player); - return true; - } - if ("§2Night".equalsIgnoreCase(timeString)) - { - player.getWorld().setTime(time + 37700); - charge.charge(player); - return true; - } - throw new SignException(_("onlyDayNight")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignTrade.java b/Essentials/src/com/earth2me/essentials/signs/SignTrade.java deleted file mode 100644 index 41f9fb2a5..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignTrade.java +++ /dev/null @@ -1,357 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.*; -import org.bukkit.inventory.ItemStack; - -//TODO: Sell Enchantment on Trade signs? -public class SignTrade extends EssentialsSign -{ - - public SignTrade() - { - super("Trade"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - validateTrade(sign, 1, false, ess); - validateTrade(sign, 2, true, ess); - final Trade charge = getTrade(sign, 2, true, true, ess); - charge.isAffordableFor(player); - sign.setLine(3, "§8" + username); - charge.charge(player); - Trade.log("Sign", "Trade", "Create", username, charge, username, null, sign.getBlock().getLocation(), ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - if (sign.getLine(3).substring(2).equalsIgnoreCase(username)) - { - final Trade store = rechargeSign(sign, ess, player); - Trade stored = null; - try - { - stored = getTrade(sign, 1, true, true, ess); - subtractAmount(sign, 1, stored, ess); - stored.pay(player); - } - catch (SignException e) - { - if (store == null) - { - throw new SignException(_("tradeSignEmptyOwner"), e); - } - } - Trade.log("Sign", "Trade", "OwnerInteract", username, store, username, stored, sign.getBlock().getLocation(), ess); - } - else - { - final Trade charge = getTrade(sign, 1, false, false, ess); - final Trade trade = getTrade(sign, 2, false, true, ess); - charge.isAffordableFor(player); - addAmount(sign, 1, charge, ess); - subtractAmount(sign, 2, trade, ess); - if (!trade.pay(player, false)) - { - subtractAmount(sign, 1, charge, ess); - addAmount(sign, 2, trade, ess); - throw new ChargeException("Full inventory"); - } - charge.charge(player); - Trade.log("Sign", "Trade", "Interact", sign.getLine(3), charge, username, trade, sign.getBlock().getLocation(), ess); - } - sign.updateSign(); - return true; - } - - private Trade rechargeSign(final ISign sign, final IEssentials ess, final User player) throws SignException, ChargeException - { - final Trade trade = getTrade(sign, 2, false, false, ess); - if (trade.getItemStack() != null && player.getItemInHand() != null - && trade.getItemStack().getTypeId() == player.getItemInHand().getTypeId() - && trade.getItemStack().getDurability() == player.getItemInHand().getDurability() - && trade.getItemStack().getEnchantments().equals(player.getItemInHand().getEnchantments())) - { - int amount = player.getItemInHand().getAmount(); - amount -= amount % trade.getItemStack().getAmount(); - if (amount > 0) - { - final ItemStack stack = player.getItemInHand().clone(); - stack.setAmount(amount); - final Trade store = new Trade(stack, ess); - addAmount(sign, 2, store, ess); - store.charge(player); - return store; - } - } - return null; - } - - @Override - protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - if ((sign.getLine(3).length() > 3 && sign.getLine(3).substring(2).equalsIgnoreCase(username)) - || player.isAuthorized("essentials.signs.trade.override")) - { - try - { - final Trade stored1 = getTrade(sign, 1, true, false, ess); - final Trade stored2 = getTrade(sign, 2, true, false, ess); - stored1.pay(player); - stored2.pay(player); - Trade.log("Sign", "Trade", "Break", username, stored2, username, stored1, sign.getBlock().getLocation(), ess); - } - catch (SignException e) - { - if (player.isAuthorized("essentials.signs.trade.override")) - { - return true; - } - throw e; - } - return true; - } - else - { - return false; - } - } - - protected final void validateTrade(final ISign sign, final int index, final boolean amountNeeded, final IEssentials ess) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - throw new SignException("Empty line"); - } - final String[] split = line.split("[ :]+"); - - if (split.length == 1 && !amountNeeded) - { - final Double money = getMoney(split[0]); - if (money != null) - { - if (Util.shortCurrency(money, ess).length() * 2 > 15) - { - throw new SignException("Line can be too long!"); - } - sign.setLine(index, Util.shortCurrency(money, ess) + ":0"); - return; - } - } - - if (split.length == 2 && amountNeeded) - { - final Double money = getMoney(split[0]); - Double amount = getDoublePositive(split[1]); - if (money != null && amount != null) - { - amount -= amount % money; - if (amount < 0.01 || money < 0.01) - { - throw new SignException(_("moreThanZero")); - } - sign.setLine(index, Util.shortCurrency(money, ess) + ":" + Util.shortCurrency(amount, ess).substring(1)); - return; - } - } - - if (split.length == 2 && !amountNeeded) - { - final int amount = getIntegerPositive(split[0]); - - if (amount < 1) - { - throw new SignException(_("moreThanZero")); - } - if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) - && getItemStack(split[1], amount, ess).getTypeId() == 0) - { - throw new SignException(_("moreThanZero")); - } - String newline = amount + " " + split[1] + ":0"; - if ((newline + amount).length() > 15) - { - throw new SignException("Line can be too long!"); - } - sign.setLine(index, newline); - return; - } - - if (split.length == 3 && amountNeeded) - { - final int stackamount = getIntegerPositive(split[0]); - int amount = getIntegerPositive(split[2]); - amount -= amount % stackamount; - if (amount < 1 || stackamount < 1) - { - throw new SignException(_("moreThanZero")); - } - if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) - && getItemStack(split[1], stackamount, ess).getTypeId() == 0) - { - throw new SignException(_("moreThanZero")); - } - sign.setLine(index, stackamount + " " + split[1] + ":" + amount); - return; - } - throw new SignException(_("invalidSignLine", index + 1)); - } - - protected final Trade getTrade(final ISign sign, final int index, final boolean fullAmount, final boolean notEmpty, final IEssentials ess) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - throw new SignException("Empty line"); - } - final String[] split = line.split("[ :]+"); - - if (split.length == 2) - { - try - { - final Double money = getMoney(split[0]); - final Double amount = notEmpty ? getDoublePositive(split[1]) : getDouble(split[1]); - if (money != null && amount != null) - { - return new Trade(fullAmount ? amount : money, ess); - } - } - catch (SignException e) - { - throw new SignException(_("tradeSignEmpty"), e); - } - } - - if (split.length == 3) - { - if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) - { - final int stackamount = getIntegerPositive(split[0]); - int amount = getInteger(split[2]); - amount -= amount % stackamount; - if (notEmpty && (amount < 1 || stackamount < 1)) - { - throw new SignException(_("tradeSignEmpty")); - } - return new Trade(fullAmount ? amount : stackamount, ess); - } - else - { - final int stackamount = getIntegerPositive(split[0]); - final ItemStack item = getItemStack(split[1], stackamount, ess); - int amount = getInteger(split[2]); - amount -= amount % stackamount; - if (notEmpty && (amount < 1 || stackamount < 1 || item.getTypeId() == 0)) - { - throw new SignException(_("tradeSignEmpty")); - } - item.setAmount(fullAmount ? amount : stackamount); - return new Trade(item, ess); - } - } - throw new SignException(_("invalidSignLine", index + 1)); - } - - protected final void subtractAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException - { - final Double money = trade.getMoney(); - if (money != null) - { - changeAmount(sign, index, -money, ess); - } - final ItemStack item = trade.getItemStack(); - if (item != null) - { - changeAmount(sign, index, -item.getAmount(), ess); - } - final Integer exp = trade.getExperience(); - if (exp != null) - { - changeAmount(sign, index, -exp.intValue(), ess); - } - } - - protected final void addAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException - { - final Double money = trade.getMoney(); - if (money != null) - { - changeAmount(sign, index, money, ess); - } - final ItemStack item = trade.getItemStack(); - if (item != null) - { - changeAmount(sign, index, item.getAmount(), ess); - } - final Integer exp = trade.getExperience(); - if (exp != null) - { - changeAmount(sign, index, exp.intValue(), ess); - } - } - - //TODO: Translate these exceptions. - private void changeAmount(final ISign sign, final int index, final double value, final IEssentials ess) throws SignException - { - - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - throw new SignException("Empty line"); - } - final String[] split = line.split("[ :]+"); - - if (split.length == 2) - { - final Double money = getMoney(split[0]); - final Double amount = getDouble(split[1]); - if (money != null && amount != null) - { - final String newline = Util.shortCurrency(money, ess) + ":" + Util.shortCurrency(amount + value, ess).substring(1); - if (newline.length() > 15) - { - throw new SignException("This sign is full: Line too long!"); - } - sign.setLine(index, newline); - return; - } - } - - if (split.length == 3) - { - if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) - { - final int stackamount = getIntegerPositive(split[0]); - final int amount = getInteger(split[2]); - final String newline = stackamount + " " + split[1] + ":" + (amount + Math.round(value)); - if (newline.length() > 15) - { - throw new SignException("This sign is full: Line too long!"); - } - sign.setLine(index, newline); - return; - } - else - { - final int stackamount = getIntegerPositive(split[0]); - //TODO: Unused local variable - final ItemStack item = getItemStack(split[1], stackamount, ess); - final int amount = getInteger(split[2]); - final String newline = stackamount + " " + split[1] + ":" + (amount + Math.round(value)); - if (newline.length() > 15) - { - throw new SignException("This sign is full: Line too long!"); - } - sign.setLine(index, newline); - return; - } - } - throw new SignException(_("invalidSignLine", index + 1)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignWarp.java b/Essentials/src/com/earth2me/essentials/signs/SignWarp.java deleted file mode 100644 index 76e8e730b..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignWarp.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class SignWarp extends EssentialsSign -{ - public SignWarp() - { - super("Warp"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 3, ess); - final String warpName = sign.getLine(1); - - if (warpName.isEmpty()) - { - sign.setLine(1, "§dWarp name!"); - return false; - } - else - { - try - { - ess.getWarps().getWarp(warpName); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - final String group = sign.getLine(2); - if ("Everyone".equalsIgnoreCase(group) || "Everybody".equalsIgnoreCase(group)) - { - sign.setLine(2, "§2Everyone"); - } - return true; - } - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final String warpName = sign.getLine(1); - final String group = sign.getLine(2); - if ((!group.isEmpty() - && ("§2Everyone".equals(group) - || player.inGroup(group))) - || (group.isEmpty() && (!ess.getSettings().getPerWarpPermission() || player.isAuthorized("essentials.warp." + warpName)))) - { - final Trade charge = getTrade(sign, 3, ess); - try - { - player.getTeleport().warp(warpName, charge, TeleportCause.PLUGIN); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - return true; - } - return false; - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignWeather.java b/Essentials/src/com/earth2me/essentials/signs/SignWeather.java deleted file mode 100644 index 559fcc2e3..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/SignWeather.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.ChargeException; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; - - -public class SignWeather extends EssentialsSign -{ - public SignWeather() - { - super("Weather"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 2, ess); - final String timeString = sign.getLine(1); - if ("Sun".equalsIgnoreCase(timeString)) - { - sign.setLine(1, "§2Sun"); - return true; - } - if ("Storm".equalsIgnoreCase(timeString)) - { - sign.setLine(1, "§2Storm"); - return true; - } - throw new SignException(_("onlySunStorm")); - } - - @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 2, ess); - charge.isAffordableFor(player); - final String weatherString = sign.getLine(1); - if ("§2Sun".equalsIgnoreCase(weatherString)) - { - player.getWorld().setStorm(false); - charge.charge(player); - return true; - } - if ("§2Storm".equalsIgnoreCase(weatherString)) - { - player.getWorld().setStorm(true); - charge.charge(player); - return true; - } - throw new SignException(_("onlySunStorm")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/signs/Signs.java b/Essentials/src/com/earth2me/essentials/signs/Signs.java deleted file mode 100644 index 2cf05ee77..000000000 --- a/Essentials/src/com/earth2me/essentials/signs/Signs.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.earth2me.essentials.signs; - - -public enum Signs -{ - BALANCE(new SignBalance()), - BUY(new SignBuy()), - DISPOSAL(new SignDisposal()), - ENCHANT(new SignEnchant()), - FREE(new SignFree()), - GAMEMODE(new SignGameMode()), - HEAL(new SignHeal()), - KIT(new SignKit()), - MAIL(new SignMail()), - PROTECTION(new SignProtection()), - SELL(new SignSell()), - SPAWNMOB(new SignSpawnmob()), - TIME(new SignTime()), - TRADE(new SignTrade()), - WARP(new SignWarp()), - WEATHER(new SignWeather()); - - private final EssentialsSign sign; - - private Signs(final EssentialsSign sign) - { - this.sign = sign; - } - - public EssentialsSign getSign() - { - return sign; - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java index 83452884b..e7a93e7fe 100644 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java +++ b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java @@ -1,10 +1,12 @@ package com.earth2me.essentials.storage; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.api.IEssentials; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; +import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; @@ -12,46 +14,72 @@ import org.bukkit.plugin.Plugin; public abstract class AbstractDelayedYamlFileReader<T extends StorageObject> implements Runnable { - private final transient File file; private final transient Class<T> clazz; protected final transient IEssentials plugin; + private final transient ReentrantLock lock = new ReentrantLock(); - public AbstractDelayedYamlFileReader(final IEssentials ess, final File file, final Class<T> clazz) + public AbstractDelayedYamlFileReader(final IEssentials ess, final Class<T> clazz) { - this.file = file; this.clazz = clazz; this.plugin = ess; - ess.scheduleAsyncDelayedTask(this); } - public abstract void onStart(); + public void schedule(boolean instant) + { + if (instant || ((Essentials)plugin).testing) + { + run(); + } + else + { + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, this); + } + } + + public abstract File onStart() throws IOException; @Override public void run() { - onStart(); + lock.lock(); try { - final FileReader reader = new FileReader(file); + final File file = onStart(); try { - final T object = new YamlStorageReader(reader, plugin).load(clazz); - onSuccess(object); - } - finally - { + final FileReader reader = new FileReader(file); try { - reader.close(); + final T object = new YamlStorageReader(reader, plugin).load(clazz); + onSuccess(object); } - catch (IOException ex) + finally { - Bukkit.getLogger().log(Level.SEVERE, "File can't be closed: " + file.toString(), ex); + try + { + reader.close(); + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, "File can't be closed: " + file.toString(), ex); + } } - } + } + catch (FileNotFoundException ex) + { + onException(ex); + Bukkit.getLogger().log(Level.INFO, "File not found: {0}", file.toString()); + } + catch (ObjectLoadException ex) + { + onException(ex); + File broken = new File(file.getAbsolutePath() + ".broken." + System.currentTimeMillis()); + file.renameTo(broken); + Bukkit.getLogger().log(Level.SEVERE, "The file " + file.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause()); + } } - catch (FileNotFoundException ex) + catch (IOException ex) { onException(); if (plugin.getSettings() == null || plugin.getSettings().isDebug()) @@ -59,14 +87,13 @@ public abstract class AbstractDelayedYamlFileReader<T extends StorageObject> imp Bukkit.getLogger().log(Level.INFO, "File not found: " + file.toString()); } } - catch (ObjectLoadException ex) + finally { - onException(); - Bukkit.getLogger().log(Level.SEVERE, "File broken: " + file.toString(), ex.getCause()); + lock.unlock(); } } public abstract void onSuccess(T object); - public abstract void onException(); + public abstract void onException(Exception exception); } diff --git a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java index e8b3992ae..d3289310e 100644 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java +++ b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java @@ -1,53 +1,83 @@ package com.earth2me.essentials.storage; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.api.IEssentials; import java.io.File; import java.io.FileNotFoundException; +import java.io.IOException; import java.io.PrintWriter; +import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; public abstract class AbstractDelayedYamlFileWriter implements Runnable { - private final transient File file; + private final transient Plugin plugin; + private final transient ReentrantLock lock = new ReentrantLock(); - public AbstractDelayedYamlFileWriter(IEssentials ess, File file) + public AbstractDelayedYamlFileWriter(final IEssentials ess) { - this.file = file; - ess.scheduleAsyncDelayedTask(this); + this.plugin = ess; } + public void schedule() + { + if (((Essentials)plugin).testing) + { + run(); + } + else + { + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, this); + } + } + + public abstract File getFile() throws IOException; + public abstract StorageObject getObject(); @Override public void run() { - PrintWriter pw = null; + lock.lock(); try { - final StorageObject object = getObject(); - final File folder = file.getParentFile(); - if (!folder.exists()) + final File file = getFile(); + PrintWriter pw = null; + try { - folder.mkdirs(); + final StorageObject object = getObject(); + final File folder = file.getParentFile(); + if (!folder.exists()) + { + folder.mkdirs(); + } + pw = new PrintWriter(file); + new YamlStorageWriter(pw).save(object); + } + catch (FileNotFoundException ex) + { + Bukkit.getLogger().log(Level.SEVERE, file.toString(), ex); + } + finally + { + onFinish(); + if (pw != null) + { + pw.close(); + } } - pw = new PrintWriter(file); - new YamlStorageWriter(pw).save(object); } - catch (FileNotFoundException ex) + catch (IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, file.toString(), ex); + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } finally { - onFinish(); - if (pw != null) - { - pw.close(); - } + lock.unlock(); } - } public abstract void onFinish(); diff --git a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java b/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java index b651dd40b..ea48dc269 100644 --- a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java +++ b/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java @@ -1,25 +1,31 @@ package com.earth2me.essentials.storage; -import com.earth2me.essentials.IConf; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.api.IReload; +import com.earth2me.essentials.api.IEssentials; import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import org.bukkit.Bukkit; -public abstract class AsyncStorageObjectHolder<T extends StorageObject> implements IConf, IStorageObjectHolder<T>, IReload +public abstract class AsyncStorageObjectHolder<T extends StorageObject> implements IStorageObjectHolder<T> { private transient T data; private final transient ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final transient Class<T> clazz; protected final transient IEssentials ess; + private final transient StorageObjectDataWriter writer; + private final transient StorageObjectDataReader reader; + private final transient AtomicBoolean loaded = new AtomicBoolean(false); public AsyncStorageObjectHolder(final IEssentials ess, final Class<T> clazz) { this.ess = ess; this.clazz = clazz; + writer = new StorageObjectDataWriter(); + reader = new StorageObjectDataReader(); try { this.data = clazz.newInstance(); @@ -30,16 +36,29 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen } } + /** + * Warning: If you access this method, you have to acquire a read or write lock first + * + * + * @return Object storing all the data + */ + @Override public T getData() { + if (!loaded.get()) + { + reader.schedule(true); + } return data; } + @Override public void acquireReadLock() { rwl.readLock().lock(); } + @Override public void acquireWriteLock() { while (rwl.getReadHoldCount() > 0) @@ -50,17 +69,19 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen rwl.readLock().lock(); } + @Override public void close() { unlock(); } + @Override public void unlock() { if (rwl.isWriteLockedByCurrentThread()) { rwl.writeLock().unlock(); - new StorageObjectDataWriter(); + writer.schedule(); } while (rwl.getReadHoldCount() > 0) { @@ -69,29 +90,34 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen } @Override - public void reloadConfig() + public void onReload() { - new StorageObjectDataReader(); + onReload(true); } - @Override - public void onReload() + public void onReload(final boolean instant) { - new StorageObjectDataReader(); + reader.schedule(instant); } public abstract void finishRead(); public abstract void finishWrite(); - public abstract File getStorageFile(); + public abstract File getStorageFile() throws IOException; private class StorageObjectDataWriter extends AbstractDelayedYamlFileWriter { public StorageObjectDataWriter() { - super(ess, getStorageFile()); + super(ess); + } + + @Override + public File getFile() throws IOException + { + return getStorageFile(); } @Override @@ -114,13 +140,19 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen { public StorageObjectDataReader() { - super(ess, getStorageFile(), clazz); + super(ess, clazz); } @Override - public void onStart() + public File onStart() throws IOException { + final File file = getStorageFile(); + while (rwl.getReadHoldCount() > 0) + { + rwl.readLock().unlock(); + } rwl.writeLock().lock(); + return file; } @Override @@ -131,11 +163,11 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen data = object; } rwl.writeLock().unlock(); - finishRead(); + loaded.set(true); } @Override - public void onException() + public void onException(final Exception exception) { if (data == null) { @@ -149,6 +181,11 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen } } rwl.writeLock().unlock(); + loaded.set(true); + if (exception instanceof FileNotFoundException) + { + writer.schedule(); + } } } } diff --git a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java b/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java index 5070be552..93412be56 100644 --- a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java +++ b/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java @@ -1,17 +1,12 @@ package com.earth2me.essentials.storage; -import java.beans.IntrospectionException; +import com.earth2me.essentials.Essentials; import java.lang.reflect.Field; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; -import org.bukkit.Bukkit; -import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.World; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; @@ -215,6 +210,22 @@ public class BukkitConstructor extends Constructor } return new EnchantmentLevel(enchant, level); } + if (node.getType().isEnum()) + { + final String val = (String)constructScalar((ScalarNode)node); + if (val.isEmpty()) + { + return null; + } + for (Object object : node.getType().getEnumConstants()) + { + if (object.toString().equalsIgnoreCase(val)) + { + return object; + } + } + return null; + } return super.construct(node); } } @@ -269,16 +280,12 @@ public class BukkitConstructor extends Constructor { return null; } - final World world = Bukkit.getWorld(worldName); - if (world == null) - { - return null; - } - return new Location(world, x, y, z, yaw, pitch); + return new Location(worldName, x, y, z, yaw, pitch); } return super.construct(node); } + @Override protected Object constructJavaBean2ndStep(final MappingNode node, final Object object) { Map<Class<? extends Object>, TypeDescription> typeDefinitions; @@ -287,7 +294,8 @@ public class BukkitConstructor extends Constructor final Field typeDefField = Constructor.class.getDeclaredField("typeDefinitions"); typeDefField.setAccessible(true); typeDefinitions = (Map<Class<? extends Object>, TypeDescription>)typeDefField.get((Constructor)BukkitConstructor.this); - if (typeDefinitions == null) { + if (typeDefinitions == null) + { throw new NullPointerException(); } } @@ -411,7 +419,7 @@ public class BukkitConstructor extends Constructor { Class<?> clazz; final String name = node.getTag().getClassName(); - if (plugin == null) + if (plugin == null || (plugin instanceof Essentials && ((Essentials)plugin).testing)) { clazz = super.getClassForNode(node); } diff --git a/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java b/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java index a664929f3..2eb062ae8 100644 --- a/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java +++ b/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java @@ -70,9 +70,9 @@ public class EnchantmentLevel implements Entry<Enchantment, Integer> if (entry.getKey() instanceof Enchantment && entry.getValue() instanceof Integer) { - final Enchantment enchantment = (Enchantment)entry.getKey(); - final Integer level = (Integer)entry.getValue(); - return this.enchantment.equals(enchantment) && this.level == level.intValue(); + final Enchantment objEnchantment = (Enchantment)entry.getKey(); + final Integer objLevel = (Integer)entry.getValue(); + return enchantment.equals(objEnchantment) && level == objLevel.intValue(); } } return false; diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java index f48e54002..0d582ece8 100644 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java +++ b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java @@ -1,9 +1,9 @@ package com.earth2me.essentials.storage; -import com.earth2me.essentials.user.UserData; +import com.earth2me.essentials.api.IReload; -public interface IStorageObjectHolder<T extends StorageObject> +public interface IStorageObjectHolder<T extends StorageObject> extends IReload { T getData(); diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectMap.java b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectMap.java new file mode 100644 index 000000000..788d80e65 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectMap.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.storage; + +import com.earth2me.essentials.api.IReload; +import com.earth2me.essentials.api.InvalidNameException; +import java.io.File; +import java.util.Set; + + +interface IStorageObjectMap<I> extends IReload +{ + boolean objectExists(final String name); + + I getObject(final String name); + + void removeObject(final String name) throws InvalidNameException; + + Set<String> getAllKeys(); + + int getKeySize(); + + File getStorageFile(final String name) throws InvalidNameException; +} diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java index d59adafe0..e92774809 100644 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java +++ b/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java @@ -3,5 +3,5 @@ package com.earth2me.essentials.storage; public interface IStorageReader { - <T extends StorageObject> T load(final Class<? extends T> clazz) throws ObjectLoadException; + <T extends StorageObject> T load(final Class<? extends T> clazz) throws ObjectLoadException; } diff --git a/Essentials/src/com/earth2me/essentials/storage/Location.java b/Essentials/src/com/earth2me/essentials/storage/Location.java new file mode 100644 index 000000000..6778027d7 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/storage/Location.java @@ -0,0 +1,115 @@ +package com.earth2me.essentials.storage; + +import java.lang.ref.WeakReference; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.World; + + +public class Location +{ + private WeakReference<org.bukkit.Location> location; + private final String worldname; + private UUID worldUID = null; + private final double x; + private final double y; + private final double z; + private final float yaw; + private final float pitch; + + public Location(org.bukkit.Location loc) + { + location = new WeakReference<org.bukkit.Location>(loc); + worldname = loc.getWorld().getName(); + worldUID = loc.getWorld().getUID(); + x = loc.getX(); + y = loc.getY(); + z = loc.getZ(); + yaw = loc.getYaw(); + pitch = loc.getPitch(); + } + + public Location(String worldname, double x, double y, double z, float yaw, float pitch) + { + this.worldname = worldname; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } + + public Location(String worldname, double x, double y, double z) + { + this.worldname = worldname; + this.x = x; + this.y = y; + this.z = z; + this.yaw = 0f; + this.pitch = 0f; + } + + public org.bukkit.Location getBukkitLocation() throws WorldNotLoadedException + { + + org.bukkit.Location loc = location == null ? null : location.get(); + if (loc == null) + { + World world = null; + if (worldUID != null) + { + world = Bukkit.getWorld(worldUID); + } + if (world == null) + { + world = Bukkit.getWorld(worldname); + } + if (world == null) + { + throw new WorldNotLoadedException(worldname); + } + loc = new org.bukkit.Location(world, getX(), getY(), getZ(), getYaw(), getPitch()); + location = new WeakReference<org.bukkit.Location>(loc); + } + return loc; + } + + public String getWorldName() + { + return worldname; + } + + public double getX() + { + return x; + } + + public double getY() + { + return y; + } + + public double getZ() + { + return z; + } + + public float getYaw() + { + return yaw; + } + + public float getPitch() + { + return pitch; + } + + + public static class WorldNotLoadedException extends Exception + { + public WorldNotLoadedException(String worldname) + { + super("World " + worldname + " is not loaded."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/ManagedFile.java b/Essentials/src/com/earth2me/essentials/storage/ManagedFile.java index a1918fa20..509783955 100644 --- a/Essentials/src/com/earth2me/essentials/ManagedFile.java +++ b/Essentials/src/com/earth2me/essentials/storage/ManagedFile.java @@ -1,6 +1,7 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.storage; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; import java.io.*; import java.math.BigInteger; import java.security.DigestInputStream; diff --git a/Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java b/Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java new file mode 100644 index 000000000..d3d118483 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java @@ -0,0 +1,138 @@ +package com.earth2me.essentials.storage; + +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.InvalidNameException; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.util.concurrent.UncheckedExecutionException; +import java.io.File; +import java.io.IOException; +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 org.bukkit.Bukkit; + + +public abstract class StorageObjectMap<I> extends CacheLoader<String, I> implements IStorageObjectMap<I> +{ + protected final transient IEssentials ess; + private final transient File folder; + protected final transient Cache<String, I> cache = CacheBuilder.newBuilder().softValues().build(this); + protected final transient ConcurrentSkipListSet<String> keys = new ConcurrentSkipListSet<String>(); + + public StorageObjectMap(final IEssentials ess, final String folderName) + { + super(); + this.ess = ess; + this.folder = new File(ess.getDataFolder(), folderName); + if (!folder.exists()) + { + folder.mkdirs(); + } + loadAllObjectsAsync(); + } + + private void loadAllObjectsAsync() + { + ess.scheduleAsyncDelayedTask(new Runnable() + { + @Override + public void run() + { + if (!folder.exists() || !folder.isDirectory()) + { + return; + } + keys.clear(); + cache.invalidateAll(); + for (String string : folder.list()) + { + try + { + if (!string.endsWith(".yml")) + { + continue; + } + final String name = Util.decodeFileName(string.substring(0, string.length() - 4)); + keys.add(name.toLowerCase(Locale.ENGLISH)); + } + catch (InvalidNameException ex) + { + Bukkit.getLogger().log(Level.WARNING, "Invalid filename: " + string, ex); + } + } + } + }); + } + + @Override + public boolean objectExists(final String name) + { + return keys.contains(name.toLowerCase(Locale.ENGLISH)); + } + + @Override + public I getObject(final String name) + { + try + { + return (I)cache.get(name.toLowerCase(Locale.ENGLISH)); + } + catch (ExecutionException ex) + { + return null; + } + catch (UncheckedExecutionException ex) + { + return null; + } + } + + @Override + public abstract I load(final String name) throws Exception; + + @Override + public void removeObject(final String name) throws InvalidNameException + { + keys.remove(name.toLowerCase(Locale.ENGLISH)); + cache.invalidate(name.toLowerCase(Locale.ENGLISH)); + final File file = getStorageFile(name); + if (file.exists()) + { + file.delete(); + } + } + + @Override + public Set<String> getAllKeys() + { + return Collections.unmodifiableSet(keys); + } + + @Override + public int getKeySize() + { + return keys.size(); + } + + @Override + public File getStorageFile(final String name) throws InvalidNameException + { + if (!folder.exists() || !folder.isDirectory()) + { + throw new InvalidNameException(new IOException("Folder does not exists: " + folder)); + } + return new File(folder, Util.sanitizeFileName(name) + ".yml"); + } + + @Override + public void onReload() + { + loadAllObjectsAsync(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java index 5d1ff668a..ee7aa45cd 100644 --- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java +++ b/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java @@ -45,7 +45,8 @@ public class YamlStorageReader implements IStorageReader try { T object = (T)yaml.load(reader); - if (object == null) { + if (object == null) + { object = clazz.newInstance(); } return object; diff --git a/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java index fd1f0f863..6e641db69 100644 --- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java +++ b/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java @@ -11,7 +11,6 @@ import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; -import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; @@ -218,6 +217,11 @@ public class YamlStorageWriter implements IStorageWriter YAML.dumpAll(Collections.singletonList(data).iterator(), writer); } } + else if (data instanceof Enum) + { + writeMaterial(data.toString()); + writer.println(); + } else if (data instanceof Material) { writeMaterial(data); @@ -260,6 +264,10 @@ public class YamlStorageWriter implements IStorageWriter writer.print(output); } } + else if (data instanceof Enum) + { + writeMaterial(data.toString()); + } else if (data instanceof Material) { writeMaterial(data); @@ -320,7 +328,7 @@ public class YamlStorageWriter implements IStorageWriter writer.println(); writeIndention(depth); writer.print("world: "); - writeScalar(entry.getWorld().getName()); + writeScalar(entry.getWorldName()); writeIndention(depth); writer.print("x: "); writeScalar(entry.getX()); diff --git a/Essentials/src/com/earth2me/essentials/user/CooldownException.java b/Essentials/src/com/earth2me/essentials/user/CooldownException.java new file mode 100644 index 000000000..b986a5552 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/user/CooldownException.java @@ -0,0 +1,12 @@ +package com.earth2me.essentials.user; + + +public class CooldownException extends Exception +{ + + public CooldownException(String timeLeft) + { + super(timeLeft); + } + +} diff --git a/Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java b/Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java index 4cdee715b..65304e76a 100644 --- a/Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java +++ b/Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java @@ -1,6 +1,7 @@ package com.earth2me.essentials.user; import org.bukkit.Location; +import org.bukkit.permissions.Permission; public interface IOfflinePlayer @@ -12,4 +13,6 @@ public interface IOfflinePlayer Location getBedSpawnLocation(); void setBanned(boolean bln); + + boolean hasPermission(Permission perm); }
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/user/Inventory.java b/Essentials/src/com/earth2me/essentials/user/Inventory.java index 0812f54a0..16ba39937 100644 --- a/Essentials/src/com/earth2me/essentials/user/Inventory.java +++ b/Essentials/src/com/earth2me/essentials/user/Inventory.java @@ -7,7 +7,6 @@ import java.util.HashMap; import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; -import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -18,10 +17,42 @@ public class Inventory implements StorageObject private int size; @MapKeyType(Integer.class) @MapValueType(ItemStack.class) - private Map<Integer, ItemStack> items = new HashMap<Integer, ItemStack>(); + private Map<Integer, ItemStack> items = null; public Inventory() { - items.put(1, new ItemStack(Material.APPLE, 64)); + } + + public Inventory(ItemStack[] contents) + { + size = contents.length; + if (items == null) { + items = new HashMap<Integer, ItemStack>(size); + } + items.clear(); + for (int i = 0; i < contents.length; i++) + { + ItemStack itemStack = contents[i]; + if (itemStack == null) { + continue; + } + items.put(i, itemStack); + } + } + + public ItemStack[] getBukkitInventory() + { + if (items == null) { + throw new IllegalStateException(); + } + final ItemStack[] inventory = new ItemStack[size]; + for (Map.Entry<Integer, ItemStack> entry : items.entrySet()) + { + if (entry.getKey() < 0 || entry.getKey()>= size) { + continue; + } + inventory[entry.getKey()] = entry.getValue(); + } + return inventory; } } diff --git a/Essentials/src/com/earth2me/essentials/user/User.java b/Essentials/src/com/earth2me/essentials/user/User.java index 589e26737..59319fb20 100644 --- a/Essentials/src/com/earth2me/essentials/user/User.java +++ b/Essentials/src/com/earth2me/essentials/user/User.java @@ -1,25 +1,65 @@ package com.earth2me.essentials.user; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.IUser; +import com.earth2me.essentials.api.ChargeException; +import com.earth2me.essentials.Console; +import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.Teleport; -import com.earth2me.essentials.commands.IEssentialsCommand; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.*; +import com.earth2me.essentials.craftbukkit.InventoryWorkaround; +import com.earth2me.essentials.permissions.Permissions; +import com.earth2me.essentials.economy.register.Method; +import com.earth2me.essentials.utils.DateUtil; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Logger; import lombok.Cleanup; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; public class User extends UserBase implements IUser { + private CommandSender replyTo = null; + @Getter + private transient IUser teleportRequester; + @Getter + private transient boolean teleportRequestHere; + @Getter + private transient final ITeleport teleport; + @Getter + private transient long teleportRequestTime; + @Getter + @Setter + private transient long lastOnlineActivity; + private transient long lastActivity = System.currentTimeMillis(); + @Getter + @Setter + private boolean hidden = false; + private transient Location afkPosition; + private static final Logger logger = Bukkit.getLogger(); + private AtomicBoolean gotMailInfo = new AtomicBoolean(false); + public User(final Player base, final IEssentials ess) { super(base, ess); + teleport = new Teleport(this, ess); } public User(final OfflinePlayer offlinePlayer, final IEssentials ess) { super(offlinePlayer, ess); + teleport = new Teleport(this, ess); } public void example() @@ -48,12 +88,49 @@ public class User extends UserBase implements IUser } @Override - public long getLastTeleportTimestamp() + public void checkCooldown(final UserData.TimestampType cooldownType, final double cooldown, final boolean set, final IPermission bypassPermission) throws CooldownException { - acquireReadLock(); + final Calendar now = new GregorianCalendar(); + if (getTimestamp(cooldownType) > 0) + { + final Calendar cooldownTime = new GregorianCalendar(); + cooldownTime.setTimeInMillis(getTimestamp(cooldownType)); + cooldownTime.add(Calendar.SECOND, (int)cooldown); + cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); + if (cooldownTime.after(now) && !bypassPermission.isAuthorized(this)) + { + throw new CooldownException(DateUtil.formatDateDiff(cooldownTime.getTimeInMillis())); + } + } + if (set) + { + setTimestamp(cooldownType, now.getTimeInMillis()); + } + } + + @Override + public void giveMoney(final double value) + { + giveMoney(value, null); + } + + @Override + public void giveMoney(final double value, final CommandSender initiator) + { + + if (value == 0) + { + return; + } + acquireWriteLock(); try { - return getData().getTimestamps().get("lastteleport"); + setMoney(getMoney() + value); + sendMessage(_("addedToAccount", Util.displayCurrency(value, ess))); + if (initiator != null) + { + initiator.sendMessage(_("addedToOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName())); + } } finally { @@ -62,30 +139,63 @@ public class User extends UserBase implements IUser } @Override - public boolean isAuthorized(String node) + public void payUser(final IUser reciever, final double value) throws Exception { - throw new UnsupportedOperationException("Not supported yet."); + if (value == 0) + { + return; + } + if (canAfford(value)) + { + setMoney(getMoney() - value); + reciever.setMoney(reciever.getMoney() + value); + sendMessage(_("moneySentTo", Util.displayCurrency(value, ess), reciever.getDisplayName())); + reciever.sendMessage(_("moneyRecievedFrom", Util.displayCurrency(value, ess), getDisplayName())); + } + else + { + throw new Exception(_("notEnoughMoney")); + } } @Override - public boolean isAuthorized(IEssentialsCommand cmd) + public void takeMoney(final double value) { - throw new UnsupportedOperationException("Not supported yet."); + takeMoney(value, null); } @Override - public boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix) + public void takeMoney(final double value, final CommandSender initiator) { - throw new UnsupportedOperationException("Not supported yet."); + if (value == 0) + { + return; + } + setMoney(getMoney() - value); + sendMessage(_("takenFromAccount", Util.displayCurrency(value, ess))); + if (initiator != null) + { + initiator.sendMessage(_("takenFromOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName())); + } + } + + public void setHome() + { + setHome("home", getLocation()); + } + + public void setHome(final String name) + { + setHome(name, getLocation()); } @Override - public void setLastTeleportTimestamp(long time) + public void setLastLocation() { acquireWriteLock(); try { - getData().getTimestamps().put("lastteleport", time); + getData().setLastLocation(new com.earth2me.essentials.storage.Location(getLocation())); } finally { @@ -93,13 +203,49 @@ public class User extends UserBase implements IUser } } - @Override - public Location getLastLocation() + public void requestTeleport(final User player, final boolean here) + { + teleportRequestTime = System.currentTimeMillis(); + teleportRequester = player; + teleportRequestHere = here; + } + + public String getNick(boolean addprefixsuffix) { acquireReadLock(); try { - return getData().getLastLocation(); + final String nick = getData().getNickname(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final IRanks groups = ess.getRanks(); + // default: {PREFIX}{NICKNAMEPREFIX}{NAME}{SUFFIX} + String displayname = settings.getData().getChat().getDisplaynameFormat(); + if (settings.getData().getCommands().isDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) + { + displayname = displayname.replace("{NAME}", getName()); + displayname = displayname.replace("{NICKNAMEPREFIX}", ""); + } + else + { + displayname = displayname.replace("{NAME}", nick); + displayname = displayname.replace("{NICKNAMEPREFIX}", settings.getData().getChat().getNicknamePrefix()); + } + + if (displayname.contains("{PREFIX}")) + { + displayname = displayname.replace("{PREFIX}", groups.getPrefix(this)); + } + if (displayname.contains("{SUFFIX}")) + { + displayname = displayname.replace("{SUFFIX}", groups.getSuffix(this)); + } + displayname = displayname.replace("{WORLDNAME}", this.getWorld().getName()); + displayname = displayname.replace('&', '\u00a7'); + displayname = displayname.concat("\u00a7f"); + + return displayname; } finally { @@ -107,13 +253,101 @@ public class User extends UserBase implements IUser } } + public void setDisplayNick() + { + String name = getNick(true); + setDisplayName(name); + if (name.length() > 16) + { + name = getNick(false); + } + if (name.length() > 16) + { + name = name.substring(0, name.charAt(15) == '\u00a7' ? 15 : 16); + } + try + { + setPlayerListName(name); + } + catch (IllegalArgumentException e) + { + logger.info("Playerlist for " + name + " was not updated. Use a shorter displayname prefix."); + } + } + + @Override + public String getDisplayName() + { + return super.getDisplayName() == null ? super.getName() : super.getDisplayName(); + } + + @Override + public void updateDisplayName() + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (isOnlineUser() && settings.getData().getChat().getChangeDisplayname()) + { + setDisplayNick(); + } + } + @Override public double getMoney() { - acquireReadLock(); + if (ess.getPaymentMethod().hasMethod()) + { + try + { + final Method method = ess.getPaymentMethod().getMethod(); + if (!method.hasAccount(this.getName())) + { + throw new Exception(); + } + final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); + return account.balance(); + } + catch (Throwable ex) + { + } + } + return super.getMoney(); + } + + @Override + public void setMoney(final double value) + { + if (ess.getPaymentMethod().hasMethod()) + { + try + { + final Method method = ess.getPaymentMethod().getMethod(); + if (!method.hasAccount(this.getName())) + { + throw new Exception(); + } + final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); + account.set(value); + } + catch (Throwable ex) + { + } + } + super.setMoney(value); + } + + public void setAfk(final boolean set) + { + acquireWriteLock(); try { - return getData().getMoney(); + this.setSleepingIgnored(Permissions.SLEEPINGIGNORED.isAuthorized(this) ? true : set); + if (set && !getData().isAfk()) + { + afkPosition = getLocation(); + } + getData().setAfk(set); } finally { @@ -122,12 +356,38 @@ public class User extends UserBase implements IUser } @Override - public void takeMoney(double value) + public boolean toggleAfk() { - acquireWriteLock(); + final boolean now = super.toggleAfk(); + this.setSleepingIgnored(Permissions.SLEEPINGIGNORED.isAuthorized(this) ? true : now); + return now; + } + + //Returns true if status expired during this check + public boolean checkJailTimeout(final long currentTime) + { + acquireReadLock(); try { - getData().setMoney(getData().getMoney() - value); + if (getTimestamp(UserData.TimestampType.JAIL) > 0 && getTimestamp(UserData.TimestampType.JAIL) < currentTime && getData().isJailed()) + { + acquireWriteLock(); + + setTimestamp(UserData.TimestampType.JAIL, 0); + getData().setJailed(false); + sendMessage(_("haveBeenReleased")); + getData().setJail(null); + + try + { + teleport.back(); + } + catch (Exception ex) + { + } + return true; + } + return false; } finally { @@ -135,13 +395,21 @@ public class User extends UserBase implements IUser } } - @Override - public void giveMoney(double value) + //Returns true if status expired during this check + public boolean checkMuteTimeout(final long currentTime) { - acquireWriteLock(); + acquireReadLock(); try { - getData().setMoney(getData().getMoney() + value); + if (getTimestamp(UserData.TimestampType.MUTE) > 0 && getTimestamp(UserData.TimestampType.MUTE) < currentTime && getData().isMuted()) + { + acquireWriteLock(); + setTimestamp(UserData.TimestampType.MUTE, 0); + sendMessage(_("canTalkAgain")); + getData().setMuted(false); + return true; + } + return false; } finally { @@ -149,19 +417,118 @@ public class User extends UserBase implements IUser } } - @Override - public String getGroup() + //Returns true if status expired during this check + public boolean checkBanTimeout(final long currentTime) { - throw new UnsupportedOperationException("Not supported yet."); + acquireReadLock(); + try + { + if (getData().getBan() != null && getData().getBan().getTimeout() > 0 && getData().getBan().getTimeout() < currentTime && isBanned()) + { + acquireWriteLock(); + getData().setBan(null); + setBanned(false); + return true; + } + return false; + } + finally + { + unlock(); + } } - @Override - public void setLastLocation() + public void updateActivity(final boolean broadcast) { - acquireWriteLock(); + acquireReadLock(); + try + { + if (getData().isAfk()) + { + acquireWriteLock(); + getData().setAfk(false); + if (broadcast && !hidden) + { + ess.broadcastMessage(this, _("userIsNotAway", getDisplayName())); + } + } + lastActivity = System.currentTimeMillis(); + } + finally + { + unlock(); + } + } + + public void checkActivity() + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final long autoafkkick = settings.getData().getCommands().getAfk().getAutoAFKKick(); + if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis() + && !hidden + && !Permissions.KICK_EXEMPT.isAuthorized(this) + && !Permissions.AFK_KICKEXEMPT.isAuthorized(this)) + { + final String kickReason = _("autoAfkKickReason", autoafkkick / 60.0); + lastActivity = 0; + kickPlayer(kickReason); + + + for (Player player : ess.getServer().getOnlinePlayers()) + { + final IUser user = ess.getUser(player); + if (Permissions.KICK_NOTIFY.isAuthorized(user)) + { + player.sendMessage(_("playerKicked", Console.NAME, getName(), kickReason)); + } + } + } + final long autoafk = settings.getData().getCommands().getAfk().getAutoAFK(); + acquireReadLock(); try { - getData().setLastLocation(base.getLocation()); + if (!getData().isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && Permissions.AFK.isAuthorized(this)) + { + setAfk(true); + if (!hidden) + { + ess.broadcastMessage(this, _("userIsAway", getDisplayName())); + } + } + } + finally + { + unlock(); + } + } + + public Location getAfkPosition() + { + return afkPosition; + } + + public boolean toggleGodModeEnabled() + { + if (!isGodModeEnabled()) + { + setFoodLevel(20); + } + return super.toggleGodmode(); + } + + public boolean isGodModeEnabled() + { + acquireReadLock(); + try + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return (getData().isGodmode() + && !settings.getData().getWorldOptions(getLocation().getWorld().getName()).isGodmode()) + || (getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()); } finally { @@ -176,35 +543,158 @@ public class User extends UserBase implements IUser } @Override - public Location getHome(Location loc) throws Exception + public void updateCompass() { - throw new UnsupportedOperationException("Not supported yet."); + try + { + Location loc = getHome(getLocation()); + if (loc == null) + { + loc = getBedSpawnLocation(); + } + if (loc != null) + { + setCompassTarget(loc); + } + } + catch (Exception ex) + { + // Ignore + } } @Override - public boolean isHidden() + public List<String> getHomes() { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Teleport getTeleport() + public int compareTo(final IUser t) + { + return Util.stripColor(this.getDisplayName()).compareTo(Util.stripColor(t.getDisplayName())); + } + + @Override + public void requestTeleport(IUser user, boolean b) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void setJail(final String jail) + public void setReplyTo(CommandSender user) { - acquireWriteLock(); - try + replyTo = user; + } + + @Override + public CommandSender getReplyTo() + { + return replyTo; + } + + @Override + public boolean gotMailInfo() + { + return gotMailInfo.getAndSet(true); + } + + @Override + public void addMail(String mail) + { + super.addMail(mail); + gotMailInfo.set(false); + } + + @Override + public void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException + { + if (giveItemStack(itemStack, canSpew)) { - getData().setJail(jail); + sendMessage(_("InvFull")); } - finally + updateInventory(); + } + + @Override + public void giveItems(List<ItemStack> itemStacks, Boolean canSpew) throws ChargeException + { + boolean spew = false; + for (ItemStack itemStack : itemStacks) { - unlock(); + if (giveItemStack(itemStack, canSpew)) + { + spew = true; + } } + if (spew) + { + sendMessage(_("InvFull")); + } + updateInventory(); + } + + private boolean giveItemStack(ItemStack itemStack, Boolean canSpew) throws ChargeException + { + boolean spew = false; + + if (itemStack == null || itemStack.getType() == Material.AIR) + { + return spew; + } + + final Map<Integer, ItemStack> overfilled; + if (Permissions.OVERSIZEDSTACKS.isAuthorized(this)) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + int oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); + + overfilled = InventoryWorkaround.addItem(getInventory(), true, oversizedStackSize, itemStack); + } + else + { + overfilled = InventoryWorkaround.addItem(getInventory(), true, itemStack); + } + if (canSpew) + { + for (ItemStack overflowStack : overfilled.values()) + { + getWorld().dropItemNaturally(getLocation(), overflowStack); + spew = true; + } + } + else { + if (!overfilled.isEmpty()) { + throw new ChargeException("Inventory full"); + } + } + return spew; + } + + @Override + public boolean canAfford(final double cost) + { + final double mon = getMoney(); + if (Permissions.ECO_LOAN.isAuthorized(this)) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return (mon - cost) >= settings.getData().getEconomy().getMinMoney(); + } + return cost <= mon; + } + + public void updateMoneyCache(double userMoney) { + if (super.getMoney() != userMoney) { + super.setMoney(userMoney); + } + } + + public boolean canAfford(double amount, boolean b) { + return true; } @Override diff --git a/Essentials/src/com/earth2me/essentials/user/UserBase.java b/Essentials/src/com/earth2me/essentials/user/UserBase.java index 587ed084b..4e0ab75fb 100644 --- a/Essentials/src/com/earth2me/essentials/user/UserBase.java +++ b/Essentials/src/com/earth2me/essentials/user/UserBase.java @@ -1,11 +1,19 @@ package com.earth2me.essentials.user; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.InvalidNameException; import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import com.earth2me.essentials.storage.Location.WorldNotLoadedException; import java.io.File; +import java.io.IOException; +import java.util.*; +import lombok.Cleanup; import lombok.Delegate; import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.Entity; @@ -13,19 +21,21 @@ import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; import org.bukkit.permissions.ServerOperator; -import org.bukkit.OfflinePlayer; public abstract class UserBase extends AsyncStorageObjectHolder<UserData> implements Player, IOfflineUser { - @Delegate(types = { Player.class, Entity.class, CommandSender.class, ServerOperator.class, HumanEntity.class, ConfigurationSerializable.class, LivingEntity.class, Permissible.class - },excludes=IOfflinePlayer.class) + }, excludes = + { + IOfflinePlayer.class + }) protected Player base; protected transient OfflinePlayer offlinePlayer; @@ -33,14 +43,14 @@ public abstract class UserBase extends AsyncStorageObjectHolder<UserData> implem { super(ess, UserData.class); this.base = base; - reloadConfig(); + onReload(); } - + public UserBase(final OfflinePlayer offlinePlayer, final IEssentials ess) { super(ess, UserData.class); this.offlinePlayer = offlinePlayer; - reloadConfig(); + onReload(); } public final Player getBase() @@ -57,61 +67,401 @@ public abstract class UserBase extends AsyncStorageObjectHolder<UserData> implem { setBase(base); } - + public void update(final OfflinePlayer offlinePlayer) { this.offlinePlayer = offlinePlayer; } - + public void dispose() { this.offlinePlayer = Bukkit.getOfflinePlayer(base.getName()); this.base = null; } - - public boolean isOnlineUser() { + + public boolean isOnlineUser() + { return base != null; } @Override public String getName() { - if (isOnlineUser()) { + if (isOnlineUser()) + { return base.getName(); - } else { + } + else + { return offlinePlayer.getName(); } } - + @Override public String getDisplayName() { - if (isOnlineUser()) { + if (isOnlineUser()) + { return base.getDisplayName(); - } else { + } + else + { return offlinePlayer.getName(); } } - + @Override public Location getBedSpawnLocation() { - return base.getBedSpawnLocation(); + if (isOnlineUser()) + { + return base.getBedSpawnLocation(); + } + else + { + return offlinePlayer.getBedSpawnLocation(); + } } @Override public void setBanned(boolean bln) { - if (isOnlineUser()) { + if (isOnlineUser()) + { base.setBanned(bln); - } else { + } + else + { offlinePlayer.setBanned(bln); } } @Override - public File getStorageFile() + public boolean hasPermission(Permission prmsn) + { + if (isOnlineUser()) + { + return base.hasPermission(prmsn); + } + else + { + return false; + } + } + + @Override + public File getStorageFile() throws IOException + { + try + { + return ess.getUserMap().getUserFile(getName()); + } + catch (InvalidNameException ex) + { + throw new IOException(ex.getMessage(), ex); + } + } + + public long getTimestamp(final UserData.TimestampType name) { - return ess.getUserMap().getUserFile(getName()); + acquireReadLock(); + try + { + if (getData().getTimestamps() == null) + { + return 0; + } + Long ts = getData().getTimestamps().get(name); + return ts == null ? 0 : ts; + } + finally + { + unlock(); + } + } + + public void setTimestamp(final UserData.TimestampType name, final long value) + { + acquireWriteLock(); + try + { + if (getData().getTimestamps() == null) + { + getData().setTimestamps(new HashMap<UserData.TimestampType, Long>()); + } + getData().getTimestamps().put(name, value); + } + finally + { + unlock(); + } + } + + public void setMoney(final double value) + { + acquireWriteLock(); + try + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (Math.abs(value) > settings.getData().getEconomy().getMaxMoney()) + { + getData().setMoney(value < 0 ? -settings.getData().getEconomy().getMaxMoney() : settings.getData().getEconomy().getMaxMoney()); + } + else + { + getData().setMoney(value); + } + } + finally + { + unlock(); + } + } + + public double getMoney() + { + acquireReadLock(); + try + { + Double money = getData().getMoney(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (money == null) + { + money = (double)settings.getData().getEconomy().getStartingBalance(); + } + if (Math.abs(money) > settings.getData().getEconomy().getMaxMoney()) + { + money = money < 0 ? -settings.getData().getEconomy().getMaxMoney() : settings.getData().getEconomy().getMaxMoney(); + } + return money; + } + finally + { + unlock(); + } + } + + public void setHome(String name, Location loc) + { + acquireWriteLock(); + try + { + Map<String, com.earth2me.essentials.storage.Location> homes = getData().getHomes(); + if (homes == null) + { + homes = new HashMap<String, com.earth2me.essentials.storage.Location>(); + getData().setHomes(homes); + } + homes.put(Util.sanitizeKey(name), new com.earth2me.essentials.storage.Location(loc)); + } + finally + { + unlock(); + } + } + + public boolean toggleAfk() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isAfk(); + getData().setAfk(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean toggleGodmode() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isGodmode(); + getData().setGodmode(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean toggleMuted() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isMuted(); + getData().setMuted(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean toggleSocialSpy() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isSocialspy(); + getData().setSocialspy(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean toggleTeleportEnabled() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isTeleportEnabled(); + getData().setTeleportEnabled(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean isIgnoringPlayer(final String name) + { + acquireReadLock(); + try + { + return getData().getIgnore() == null ? false : getData().getIgnore().contains(name.toLowerCase(Locale.ENGLISH)); + } + finally + { + unlock(); + } + } + + public void setIgnoredPlayer(final String name, final boolean set) + { + acquireWriteLock(); + try + { + if (getData().getIgnore() == null) + { + getData().setIgnore(new HashSet<String>()); + } + if (set) + { + getData().getIgnore().add(name.toLowerCase(Locale.ENGLISH)); + } + else + { + getData().getIgnore().remove(name.toLowerCase(Locale.ENGLISH)); + } + } + finally + { + unlock(); + } + } + + public void addMail(String string) + { + acquireWriteLock(); + try + { + if (getData().getMails() == null) + { + getData().setMails(new ArrayList<String>()); + } + getData().getMails().add(string); + } + finally + { + unlock(); + } + } + + public List<String> getMails() + { + acquireReadLock(); + try + { + if (getData().getMails() == null) + { + return Collections.emptyList(); + } + else + { + return new ArrayList<String>(getData().getMails()); + } + } + finally + { + unlock(); + } + } + + public Location getHome(Location loc) + { + + acquireReadLock(); + try + { + if (getData().getHomes() == null) + { + return null; + } + ArrayList<Location> worldHomes = new ArrayList<Location>(); + for (com.earth2me.essentials.storage.Location location : getData().getHomes().values()) + { + if (location.getWorldName().equals(loc.getWorld().getName())) + { + try + { + worldHomes.add(location.getBukkitLocation()); + } + catch (WorldNotLoadedException ex) + { + continue; + } + } + } + if (worldHomes.isEmpty()) + { + return null; + } + if (worldHomes.size() == 1) + { + return worldHomes.get(0); + } + double distance = Double.MAX_VALUE; + Location target = null; + for (Location location : worldHomes) + { + final double d = loc.distanceSquared(location); + if (d < distance) + { + target = location; + distance = d; + } + } + return target; + } + finally + { + unlock(); + } } } diff --git a/Essentials/src/com/earth2me/essentials/user/UserData.java b/Essentials/src/com/earth2me/essentials/user/UserData.java index 4586d0627..d61d21a49 100644 --- a/Essentials/src/com/earth2me/essentials/user/UserData.java +++ b/Essentials/src/com/earth2me/essentials/user/UserData.java @@ -1,13 +1,9 @@ package com.earth2me.essentials.user; -import com.earth2me.essentials.storage.ListType; -import com.earth2me.essentials.storage.MapKeyType; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; +import com.earth2me.essentials.storage.*; import java.util.*; import lombok.Data; import lombok.EqualsAndHashCode; -import org.bukkit.Location; import org.bukkit.Material; @@ -15,8 +11,12 @@ import org.bukkit.Material; @EqualsAndHashCode(callSuper = false) public class UserData implements StorageObject { + public enum TimestampType + { + JAIL, MUTE, LASTHEAL, LASTTELEPORT, LOGIN, LOGOUT + } private String nickname; - private double money; + private Double money; @MapValueType(Location.class) private Map<String, Location> homes = new HashMap<String, Location>(); @ListType(Material.class) @@ -25,8 +25,9 @@ public class UserData implements StorageObject @MapKeyType(Material.class) private Map<Material, List<String>> powerTools = new HashMap<Material, List<String>>(); private Location lastLocation; + @MapKeyType(TimestampType.class) @MapValueType(Long.class) - private Map<String, Long> timestamps; + private Map<TimestampType, Long> timestamps = new HashMap<TimestampType, Long>(); private String jail; @ListType private List<String> mails; @@ -44,7 +45,7 @@ public class UserData implements StorageObject private String geolocation; private boolean socialspy; private boolean npc; - private boolean powertoolsenabled; + private boolean powerToolsEnabled; public UserData() { @@ -52,5 +53,57 @@ public class UserData implements StorageObject unlimited.add(Material.ARROW); unlimited.add(Material.APPLE); powerTools.put(Material.DEAD_BUSH, Collections.singletonList("test")); + timestamps.put(TimestampType.JAIL, Long.MIN_VALUE); + } + + public boolean hasUnlimited(Material mat) + { + return unlimited != null && unlimited.contains(mat); + } + + public void setUnlimited(Material mat, boolean state) + { + if (unlimited.contains(mat)) + { + unlimited.remove(mat); + } + if (state) + { + unlimited.add(mat); + } + } + + public List<String> getPowertool(Material mat) + { + return powerTools == null ? Collections.<String>emptyList() : powerTools.get(mat); + } + + + public boolean hasPowerTools() + { + return powerTools != null && !powerTools.isEmpty(); + } + + public void setPowertool(Material mat, List<String> commands) + { + if (powerTools == null) + { + powerTools = new HashMap<Material, List<String>>(); + } + powerTools.put(mat, commands); + } + + public void clearAllPowertools() + { + powerTools = null; + } + + public void removeHome(String home) + { + if (homes == null) + { + return; + } + homes.remove(home); } } diff --git a/Essentials/src/com/earth2me/essentials/user/UserMap.java b/Essentials/src/com/earth2me/essentials/user/UserMap.java index 821ee4c8f..96744da1d 100644 --- a/Essentials/src/com/earth2me/essentials/user/UserMap.java +++ b/Essentials/src/com/earth2me/essentials/user/UserMap.java @@ -1,85 +1,38 @@ package com.earth2me.essentials.user; -import com.earth2me.essentials.IConf; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.Util; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.util.concurrent.UncheckedExecutionException; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.api.IUserMap; +import com.earth2me.essentials.api.InvalidNameException; +import com.earth2me.essentials.storage.StorageObjectMap; 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 org.bukkit.Bukkit; import org.bukkit.entity.Player; -public class UserMap extends CacheLoader<String, User> implements IConf +public class UserMap extends StorageObjectMap<IUser> implements IUserMap { - private final transient IEssentials ess; - private final transient Cache<String, User> users = CacheBuilder.newBuilder().softValues().build(this); - private final transient ConcurrentSkipListSet<String> keys = new ConcurrentSkipListSet<String>(); - public UserMap(final IEssentials ess) { - super(); - this.ess = ess; - loadAllUsersAsync(ess); - } - - private void loadAllUsersAsync(final IEssentials ess) - { - ess.scheduleAsyncDelayedTask(new Runnable() - { - @Override - public void run() - { - final File userdir = new File(ess.getDataFolder(), "userdata"); - if (!userdir.exists()) - { - return; - } - keys.clear(); - users.invalidateAll(); - for (String string : userdir.list()) - { - if (!string.endsWith(".yml")) - { - continue; - } - final String name = string.substring(0, string.length() - 4); - keys.add(name.toLowerCase(Locale.ENGLISH)); - } - } - }); + super(ess, "users"); } + @Override public boolean userExists(final String name) { - return keys.contains(name.toLowerCase(Locale.ENGLISH)); + return objectExists(name); } - public User getUser(final String name) + @Override + public IUser getUser(final String name) { - try - { - return users.get(name.toLowerCase(Locale.ENGLISH)); - } - catch (ExecutionException ex) - { - return null; - } - catch (UncheckedExecutionException ex) - { - return null; - } + return getObject(name); } @Override - public User load(final String name) throws Exception + public IUser load(final String name) throws Exception { for (Player player : ess.getServer().getOnlinePlayers()) { @@ -99,30 +52,46 @@ public class UserMap extends CacheLoader<String, User> implements IConf } @Override - public void reloadConfig() + public void removeUser(final String name) throws InvalidNameException { - loadAllUsersAsync(ess); + removeObject(name); } - public void removeUser(final String name) + @Override + public Set<String> getAllUniqueUsers() { - keys.remove(name.toLowerCase(Locale.ENGLISH)); - users.invalidate(name.toLowerCase(Locale.ENGLISH)); + return getAllKeys(); } - public Set<String> getAllUniqueUsers() + @Override + public int getUniqueUsers() { - return Collections.unmodifiableSet(keys); + return getKeySize(); } - public int getUniqueUsers() + @Override + public File getUserFile(String name) throws InvalidNameException { - return keys.size(); + return getStorageFile(name); } - public File getUserFile(final String name) + @Override + public IUser getUser(final Player player) { - final File userFolder = new File(ess.getDataFolder(), "userdata"); - return new File(userFolder, Util.sanitizeFileName(name) + ".yml"); + if (player instanceof IUser) + { + return (IUser)player; + } + IUser user = getUser(player.getName()); + + if (user == null) + { + user = new User(player, ess); + } + else + { + ((User)user).update(player); + } + return user; } } diff --git a/Essentials/src/com/earth2me/essentials/utils/DateUtil.java b/Essentials/src/com/earth2me/essentials/utils/DateUtil.java new file mode 100644 index 000000000..3f925e6b5 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/utils/DateUtil.java @@ -0,0 +1,186 @@ +package com.earth2me.essentials.utils; + +import static com.earth2me.essentials.I18n._; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class DateUtil { + public static String formatDateDiff(long date) + { + Calendar c = new GregorianCalendar(); + c.setTimeInMillis(date); + Calendar now = new GregorianCalendar(); + return formatDateDiff(now, c); + } + + public static String formatDateDiff(Calendar fromDate, Calendar toDate) + { + boolean future = false; + if (toDate.equals(fromDate)) + { + return _("now"); + } + if (toDate.after(fromDate)) + { + future = true; + } + + StringBuilder sb = new StringBuilder(); + int[] types = new int[] + { + Calendar.YEAR, + Calendar.MONTH, + Calendar.DAY_OF_MONTH, + Calendar.HOUR_OF_DAY, + Calendar.MINUTE, + Calendar.SECOND + }; + String[] names = new String[] + { + _("year"), + _("years"), + _("month"), + _("months"), + _("day"), + _("days"), + _("hour"), + _("hours"), + _("minute"), + _("minutes"), + _("second"), + _("seconds") + }; + for (int i = 0; i < types.length; i++) + { + int diff = dateDiff(types[i], fromDate, toDate, future); + if (diff > 0) + { + sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]); + } + } + if (sb.length() == 0) + { + return "now"; + } + return sb.toString(); + } + + private static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future) + { + int diff = 0; + long savedDate = fromDate.getTimeInMillis(); + while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate))) + { + savedDate = fromDate.getTimeInMillis(); + fromDate.add(type, future ? 1 : -1); + diff++; + } + diff--; + fromDate.setTimeInMillis(savedDate); + return diff; + } + + public static long parseDateDiff(String time, boolean future) throws Exception + { + Pattern timePattern = Pattern.compile( + "(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?" + + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE); + Matcher m = timePattern.matcher(time); + int years = 0; + int months = 0; + int weeks = 0; + int days = 0; + int hours = 0; + int minutes = 0; + int seconds = 0; + boolean found = false; + while (m.find()) + { + if (m.group() == null || m.group().isEmpty()) + { + continue; + } + for (int i = 0; i < m.groupCount(); i++) + { + if (m.group(i) != null && !m.group(i).isEmpty()) + { + found = true; + break; + } + } + if (found) + { + if (m.group(1) != null && !m.group(1).isEmpty()) + { + years = Integer.parseInt(m.group(1)); + } + if (m.group(2) != null && !m.group(2).isEmpty()) + { + months = Integer.parseInt(m.group(2)); + } + if (m.group(3) != null && !m.group(3).isEmpty()) + { + weeks = Integer.parseInt(m.group(3)); + } + if (m.group(4) != null && !m.group(4).isEmpty()) + { + days = Integer.parseInt(m.group(4)); + } + if (m.group(5) != null && !m.group(5).isEmpty()) + { + hours = Integer.parseInt(m.group(5)); + } + if (m.group(6) != null && !m.group(6).isEmpty()) + { + minutes = Integer.parseInt(m.group(6)); + } + if (m.group(7) != null && !m.group(7).isEmpty()) + { + seconds = Integer.parseInt(m.group(7)); + } + break; + } + } + if (!found) + { + throw new Exception(_("illegalDate")); + } + Calendar c = new GregorianCalendar(); + if (years > 0) + { + c.add(Calendar.YEAR, years * (future ? 1 : -1)); + } + if (months > 0) + { + c.add(Calendar.MONTH, months * (future ? 1 : -1)); + } + if (weeks > 0) + { + c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1)); + } + if (days > 0) + { + c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1)); + } + if (hours > 0) + { + c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1)); + } + if (minutes > 0) + { + c.add(Calendar.MINUTE, minutes * (future ? 1 : -1)); + } + if (seconds > 0) + { + c.add(Calendar.SECOND, seconds * (future ? 1 : -1)); + } + return c.getTimeInMillis(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/DescParseTickFormat.java b/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java index 9c40acacc..e553bc80c 100644 --- a/Essentials/src/com/earth2me/essentials/DescParseTickFormat.java +++ b/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.utils; import static com.earth2me.essentials.I18n._; import java.text.SimpleDateFormat; @@ -15,9 +15,6 @@ import java.util.*; */ public final class DescParseTickFormat { - // ============================================ - // First some information vars. TODO: Should this be in a config file? - // -------------------------------------------- public static final Map<String, Integer> nameToTicks = new LinkedHashMap<String, Integer>(); public static final Set<String> resetAliases = new HashSet<String>(); public static final int ticksAtMidnight = 18000; diff --git a/Essentials/src/com/earth2me/essentials/ExecuteTimer.java b/Essentials/src/com/earth2me/essentials/utils/ExecuteTimer.java index 301669428..9c8d71992 100644 --- a/Essentials/src/com/earth2me/essentials/ExecuteTimer.java +++ b/Essentials/src/com/earth2me/essentials/utils/ExecuteTimer.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.utils; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; diff --git a/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java b/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java new file mode 100644 index 000000000..49b256417 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java @@ -0,0 +1,142 @@ +package com.earth2me.essentials.utils; + +import static com.earth2me.essentials.I18n._; +import java.util.HashSet; +import java.util.Set; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.LivingEntity; + +public class LocationUtil { + // The player can stand inside these materials + private static final Set<Integer> AIR_MATERIALS = new HashSet<Integer>(); + private static final HashSet<Byte> AIR_MATERIALS_TARGET = new HashSet<Byte>(); + + static + { + AIR_MATERIALS.add(Material.AIR.getId()); + AIR_MATERIALS.add(Material.SAPLING.getId()); + AIR_MATERIALS.add(Material.POWERED_RAIL.getId()); + AIR_MATERIALS.add(Material.DETECTOR_RAIL.getId()); + AIR_MATERIALS.add(Material.LONG_GRASS.getId()); + AIR_MATERIALS.add(Material.DEAD_BUSH.getId()); + AIR_MATERIALS.add(Material.YELLOW_FLOWER.getId()); + AIR_MATERIALS.add(Material.RED_ROSE.getId()); + AIR_MATERIALS.add(Material.BROWN_MUSHROOM.getId()); + AIR_MATERIALS.add(Material.RED_MUSHROOM.getId()); + AIR_MATERIALS.add(Material.TORCH.getId()); + AIR_MATERIALS.add(Material.REDSTONE_WIRE.getId()); + AIR_MATERIALS.add(Material.SEEDS.getId()); + AIR_MATERIALS.add(Material.SIGN_POST.getId()); + AIR_MATERIALS.add(Material.WOODEN_DOOR.getId()); + AIR_MATERIALS.add(Material.LADDER.getId()); + AIR_MATERIALS.add(Material.RAILS.getId()); + AIR_MATERIALS.add(Material.WALL_SIGN.getId()); + AIR_MATERIALS.add(Material.LEVER.getId()); + AIR_MATERIALS.add(Material.STONE_PLATE.getId()); + AIR_MATERIALS.add(Material.IRON_DOOR_BLOCK.getId()); + AIR_MATERIALS.add(Material.WOOD_PLATE.getId()); + AIR_MATERIALS.add(Material.REDSTONE_TORCH_OFF.getId()); + AIR_MATERIALS.add(Material.REDSTONE_TORCH_ON.getId()); + AIR_MATERIALS.add(Material.STONE_BUTTON.getId()); + AIR_MATERIALS.add(Material.SUGAR_CANE_BLOCK.getId()); + AIR_MATERIALS.add(Material.DIODE_BLOCK_OFF.getId()); + AIR_MATERIALS.add(Material.DIODE_BLOCK_ON.getId()); + AIR_MATERIALS.add(Material.TRAP_DOOR.getId()); + AIR_MATERIALS.add(Material.PUMPKIN_STEM.getId()); + AIR_MATERIALS.add(Material.MELON_STEM.getId()); + AIR_MATERIALS.add(Material.VINE.getId()); + AIR_MATERIALS.add(Material.NETHER_WARTS.getId()); + AIR_MATERIALS.add(Material.WATER_LILY.getId()); + + for (Integer integer : AIR_MATERIALS) + { + AIR_MATERIALS_TARGET.add(integer.byteValue()); + } + AIR_MATERIALS_TARGET.add((byte)Material.WATER.getId()); + AIR_MATERIALS_TARGET.add((byte)Material.STATIONARY_WATER.getId()); + } + + public static Location getTarget(final LivingEntity entity) throws Exception + { + final Block block = entity.getTargetBlock(AIR_MATERIALS_TARGET, 300); + if (block == null) + { + throw new Exception("Not targeting a block"); + } + return block.getLocation(); + } + + public static Location getSafeDestination(final Location loc) throws Exception + { + if (loc == null || loc.getWorld() == null) + { + throw new Exception(_("destinationNotSet")); + } + final World world = loc.getWorld(); + int x = loc.getBlockX(); + int y = (int)Math.round(loc.getY()); + int z = loc.getBlockZ(); + + while (isBlockAboveAir(world, x, y, z)) + { + y -= 1; + if (y < 0) + { + break; + } + } + + while (isBlockUnsafe(world, x, y, z)) + { + y += 1; + if (y >= world.getHighestBlockYAt(x, z)) + { + x += 1; + break; + } + } + while (isBlockUnsafe(world, x, y, z)) + { + y -= 1; + if (y <= 1) + { + x += 1; + y = world.getHighestBlockYAt(x, z); + if (x - 32 > loc.getBlockX()) + { + throw new Exception(_("holeInFloor")); + } + } + } + return new Location(world, x + 0.5D, y, z + 0.5D, loc.getYaw(), loc.getPitch()); + } + + private static boolean isBlockAboveAir(final World world, final int x, final int y, final int z) + { + return AIR_MATERIALS.contains(world.getBlockAt(x, y - 1, z).getType().getId()); + } + + public static boolean isBlockUnsafe(final World world, final int x, final int y, final int z) + { + final Block below = world.getBlockAt(x, y - 1, z); + if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA) + { + return true; + } + + if (below.getType() == Material.FIRE) + { + return true; + } + + if ((!AIR_MATERIALS.contains(world.getBlockAt(x, y, z).getType().getId())) + || (!AIR_MATERIALS.contains(world.getBlockAt(x, y + 1, z).getType().getId()))) + { + return true; + } + return isBlockAboveAir(world, x, y, z); + } +} diff --git a/Essentials/src/com/earth2me/essentials/utils/Util.java b/Essentials/src/com/earth2me/essentials/utils/Util.java new file mode 100644 index 000000000..720376c66 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/utils/Util.java @@ -0,0 +1,358 @@ +package com.earth2me.essentials.utils; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.InvalidNameException; +import com.earth2me.essentials.utils.gnu.inet.encoding.Punycode; +import com.earth2me.essentials.utils.gnu.inet.encoding.PunycodeException; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Collection; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Pattern; +import lombok.Cleanup; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.plugin.PluginManager; + + +public final class Util +{ + private Util() + { + } + private final static Pattern INVALIDFILECHARS = Pattern.compile("[^\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); + private final static Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); + + public static String sanitizeFileName(String name) throws InvalidNameException + { + try + { + String r = name.toLowerCase(Locale.ENGLISH); + r = r.replace('.', (char)('\ue200' + '.')); + r = r.replace('\\', (char)('\ue200' + '\\')); + r = r.replace('/', (char)('\ue200' + '/')); + r = r.replace('"', (char)('\ue200' + '"')); + r = r.replace('<', (char)('\ue200' + '<')); + r = r.replace('>', (char)('\ue200' + '>')); + r = r.replace('|', (char)('\ue200' + '|')); + r = r.replace('?', (char)('\ue200' + '?')); + r = r.replace('*', (char)('\ue200' + '*')); + r = r.replace(':', (char)('\ue200' + ':')); + r = r.replace('-', (char)('\ue200' + '-')); + r = INVALIDFILECHARS.matcher(r).replaceAll(""); + return Punycode.encode(r); + } + catch (PunycodeException ex) + { + throw new InvalidNameException(ex); + } + } + + public static String decodeFileName(String name) throws InvalidNameException + { + try + { + String r = Punycode.decode(name); + r = r.replace((char)('\ue200' + '.'), '.'); + r = r.replace((char)('\ue200' + '\\'), '\\'); + r = r.replace((char)('\ue200' + '/'), '/'); + r = r.replace((char)('\ue200' + '"'), '"'); + r = r.replace((char)('\ue200' + '<'), '<'); + r = r.replace((char)('\ue200' + '>'), '>'); + r = r.replace((char)('\ue200' + '|'), '|'); + r = r.replace((char)('\ue200' + '?'), '?'); + r = r.replace((char)('\ue200' + '*'), '*'); + r = r.replace((char)('\ue200' + ':'), ':'); + r = r.replace((char)('\ue200' + '-'), '-'); + return r; + } + catch (PunycodeException ex) + { + throw new InvalidNameException(ex); + } + } + + public static String sanitizeKey(String name) + { + return INVALIDCHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); + } + + public static String sanitizeString(final String string) + { + return INVALIDCHARS.matcher(string).replaceAll(""); + } + + 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 dFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US)); + + public static String formatAsCurrency(final double value) + { + + String str = dFormat.format(value); + if (str.endsWith(".00")) + { + str = str.substring(0, str.length() - 3); + } + return str; + } + + public static String displayCurrency(final double value, final IEssentials ess) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return _("currency", settings.getData().getEconomy().getCurrencySymbol(), formatAsCurrency(value)); + } + + public static String shortCurrency(final double value, final IEssentials ess) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getEconomy().getCurrencySymbol() + formatAsCurrency(value); + } + + public static double roundDouble(final double d) + { + return Math.round(d * 100.0) / 100.0; + } + + public static boolean isInt(final String sInt) + { + try + { + Integer.parseInt(sInt); + } + catch (NumberFormatException e) + { + return false; + } + return true; + } + + public static String joinList(Object... list) + { + return joinList(", ", list); + } + + public static String joinList(String seperator, Object... list) + { + StringBuilder buf = new StringBuilder(); + for (Object each : list) + { + if (buf.length() > 0) + { + buf.append(seperator); + } + + if (each instanceof Collection) + { + buf.append(joinList(seperator, ((Collection)each).toArray())); + } + else + { + try + { + buf.append(each.toString()); + } + catch (Exception e) + { + buf.append(each.toString()); + } + } + } + return buf.toString(); + } + + public static void registerPermissions(String path, Collection<String> nodes, boolean hasDefault, IEssentials ess) + { + if (nodes == null || nodes.isEmpty()) + { + return; + } + final PluginManager pluginManager = ess.getServer().getPluginManager(); + Permission basePerm = pluginManager.getPermission(path + ".*"); + if (basePerm != null && !basePerm.getChildren().isEmpty()) + { + basePerm.getChildren().clear(); + } + if (basePerm == null) + { + basePerm = new Permission(path + ".*", PermissionDefault.OP); + pluginManager.addPermission(basePerm); + Permission mainPerm = pluginManager.getPermission("essentials.*"); + if (mainPerm == null) + { + mainPerm = new Permission("essentials.*", PermissionDefault.OP); + pluginManager.addPermission(mainPerm); + } + mainPerm.getChildren().put(basePerm.getName(), Boolean.TRUE); + } + + for (String nodeName : nodes) + { + final String permissionName = path + "." + nodeName; + Permission perm = pluginManager.getPermission(permissionName); + if (perm == null) + { + final PermissionDefault defaultPerm = hasDefault && nodeName.equalsIgnoreCase("default") ? PermissionDefault.TRUE : PermissionDefault.OP; + perm = new Permission(permissionName, defaultPerm); + pluginManager.addPermission(perm); + } + basePerm.getChildren().put(permissionName, Boolean.TRUE); + } + basePerm.recalculatePermissibles(); + } + private static transient final Pattern DOT_PATTERN = Pattern.compile("\\."); + + public static Permission registerPermission(String permission, PermissionDefault defaultPerm) + { + final PluginManager pluginManager = Bukkit.getServer().getPluginManager(); + final String[] parts = DOT_PATTERN.split(permission); + final StringBuilder builder = new StringBuilder(permission.length()); + Permission parent = null; + for (int i = 0; i < parts.length - 1; i++) + { + builder.append(parts[i]).append(".*"); + String permString = builder.toString(); + Permission perm = pluginManager.getPermission(permString); + if (perm == null) + { + perm = new Permission(permString, PermissionDefault.FALSE); + pluginManager.addPermission(perm); + if (parent != null) + { + parent.getChildren().put(perm.getName(), Boolean.TRUE); + } + parent = perm; + } + builder.deleteCharAt(builder.length() - 1); + } + Permission perm = pluginManager.getPermission(permission); + if (perm == null) + { + perm = new Permission(permission, defaultPerm); + pluginManager.addPermission(perm); + if (parent != null) + { + parent.getChildren().put(perm.getName(), Boolean.TRUE); + } + parent = perm; + } + perm.recalculatePermissibles(); + return perm; + } + private static transient final Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00A7+[0-9A-FKa-fk]"); + private static transient final Pattern EASY_COLOR_PATTERN = Pattern.compile("&([0-9a-fk])"); + + public static String stripColor(final String input) + { + if (input == null) + { + return null; + } + + return VANILLA_COLOR_PATTERN.matcher(input).replaceAll(""); + } + + public static String replaceColor(final String input) + { + if (input == null) + { + return null; + } + + return EASY_COLOR_PATTERN.matcher(input).replaceAll("\u00a7$1"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/Punycode.java b/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/Punycode.java new file mode 100644 index 000000000..fdca948f6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/Punycode.java @@ -0,0 +1,321 @@ +package com.earth2me.essentials.utils.gnu.inet.encoding; + + +/** + * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software + * Foundation, Inc. + * + * Author: Oliver Hitz + * + * This file is part of GNU Libidn. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + */ +/** + * This class offers static methods for encoding/decoding strings + * using the Punycode algorithm. + * <ul> + * <li>RFC3492 Punycode + * </ul> + * Note that this implementation only supports 16-bit Unicode code + * points. + */ +/* + * Changes by snowleo: + * - Correctly catch wrong characters after the delimiter + * - If the string starts with the delimiter, it's an encoded string + * - If there is no delimiter, it's an ascii string. + * - Note: the string should never contain the delimiter. + */ +public class Punycode +{ + /* + * Punycode parameters + */ + final static int TMIN = 1; + final static int TMAX = 26; + final static int BASE = 36; + final static int INITIAL_N = 128; + final static int INITIAL_BIAS = 72; + final static int DAMP = 700; + final static int SKEW = 38; + final static char DELIMITER = '-'; + + /** + * Punycodes a unicode string. + * + * @param input Unicode string. + * @return Punycoded string. + */ + public static String encode(String input) + throws PunycodeException + { + int n = INITIAL_N; + int delta = 0; + int bias = INITIAL_BIAS; + StringBuffer output = new StringBuffer(); + + // Copy all basic code points to the output + int b = 0; + for (int i = 0; i < input.length(); i++) + { + char c = input.charAt(i); + if (isBasic(c)) + { + output.append(c); + b++; + } + } + + // Append delimiter + if (b < input.length()) // Changed by snowleo + { + output.append(DELIMITER); + } + + int h = b; + while (h < input.length()) + { + int m = Integer.MAX_VALUE; + + // Find the minimum code point >= n + for (int i = 0; i < input.length(); i++) + { + int c = input.charAt(i); + if (c >= n && c < m) + { + m = c; + } + } + + if (m - n > (Integer.MAX_VALUE - delta) / (h + 1)) + { + throw new PunycodeException(PunycodeException.OVERFLOW); + } + delta = delta + (m - n) * (h + 1); + n = m; + + for (int j = 0; j < input.length(); j++) + { + int c = input.charAt(j); + if (c < n) + { + delta++; + if (0 == delta) + { + throw new PunycodeException(PunycodeException.OVERFLOW); + } + } + if (c == n) + { + int q = delta; + + for (int k = BASE;; k += BASE) + { + int t; + if (k <= bias) + { + t = TMIN; + } + else if (k >= bias + TMAX) + { + t = TMAX; + } + else + { + t = k - bias; + } + if (q < t) + { + break; + } + output.append((char)digit2codepoint(t + (q - t) % (BASE - t))); + q = (q - t) / (BASE - t); + } + + output.append((char)digit2codepoint(q)); + bias = adapt(delta, h + 1, h == b); + delta = 0; + h++; + } + } + + delta++; + n++; + } + + return output.toString(); + } + + /** + * Decode a punycoded string. + * + * @param input Punycode string + * @return Unicode string. + */ + public static String decode(String input) + throws PunycodeException + { + int n = INITIAL_N; + int i = 0; + int bias = INITIAL_BIAS; + StringBuffer output = new StringBuffer(); + + int d = input.lastIndexOf(DELIMITER); + // Change start by snowleo + if (d < 0) { + return input; + } + else if (d > 0) // Change end by snowleo + { + for (int j = 0; j < d; j++) + { + char c = input.charAt(j); + if (!isBasic(c)) + { + throw new PunycodeException(PunycodeException.BAD_INPUT); + } + output.append(c); + } + d++; + } + else + { + d = 1; // Changed by snowleo + } + + while (d < input.length()) + { + int oldi = i; + int w = 1; + + for (int k = BASE;; k += BASE) + { + if (d == input.length()) + { + throw new PunycodeException(PunycodeException.BAD_INPUT); + } + int c = input.charAt(d++); + int digit = codepoint2digit(c); + if (digit > (Integer.MAX_VALUE - i) / w) + { + throw new PunycodeException(PunycodeException.OVERFLOW); + } + + i = i + digit * w; + + int t; + if (k <= bias) + { + t = TMIN; + } + else if (k >= bias + TMAX) + { + t = TMAX; + } + else + { + t = k - bias; + } + if (digit < t) + { + break; + } + w = w * (BASE - t); + } + + bias = adapt(i - oldi, output.length() + 1, oldi == 0); + + if (i / (output.length() + 1) > Integer.MAX_VALUE - n) + { + throw new PunycodeException(PunycodeException.OVERFLOW); + } + + n = n + i / (output.length() + 1); + i = i % (output.length() + 1); + output.insert(i, (char)n); + i++; + } + + return output.toString(); + } + + public final static int adapt(int delta, int numpoints, boolean first) + { + if (first) + { + delta = delta / DAMP; + } + else + { + delta = delta / 2; + } + + delta = delta + (delta / numpoints); + + int k = 0; + while (delta > ((BASE - TMIN) * TMAX) / 2) + { + delta = delta / (BASE - TMIN); + k = k + BASE; + } + + return k + ((BASE - TMIN + 1) * delta) / (delta + SKEW); + } + + public final static boolean isBasic(char c) + { + return c < 0x80; + } + + public final static int digit2codepoint(int d) + throws PunycodeException + { + if (d < 26) + { + // 0..25 : 'a'..'z' + return d + 'a'; + } + else if (d < 36) + { + // 26..35 : '0'..'9'; + return d - 26 + '0'; + } + else + { + throw new PunycodeException(PunycodeException.BAD_INPUT); + } + } + + public final static int codepoint2digit(int c) + throws PunycodeException + { + if (c - '0' < 10 && c >= '0') // Changed by snowleo + { + // '0'..'9' : 26..35 + return c - '0' + 26; + } + else if (c - 'a' < 26 && c >= 'a') // Changed by snowleo + { + // 'a'..'z' : 0..25 + return c - 'a'; + } + else + { + throw new PunycodeException(PunycodeException.BAD_INPUT); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/PunycodeException.java b/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/PunycodeException.java new file mode 100644 index 000000000..9db00d10d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/PunycodeException.java @@ -0,0 +1,45 @@ +package com.earth2me.essentials.utils.gnu.inet.encoding; + + +/** + * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software + * Foundation, Inc. + * + * Author: Oliver Hitz + * + * This file is part of GNU Libidn. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + */ +/** + * Exception handling for Punycode class. + */ +public class PunycodeException + extends Exception +{ + public static String OVERFLOW = "Overflow."; + public static String BAD_INPUT = "Bad input."; + + /** + * Creates a new PunycodeException. + * + * @param m message. + */ + public PunycodeException(String m) + { + super(m); + } +} diff --git a/Essentials/src/com/earth2me/essentials/textreader/ArrayListInput.java b/Essentials/src/com/earth2me/essentials/utils/textreader/ArrayListInput.java index 0da83f3b4..5943387a5 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/ArrayListInput.java +++ b/Essentials/src/com/earth2me/essentials/utils/textreader/ArrayListInput.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.textreader; +package com.earth2me.essentials.utils.textreader; import java.util.ArrayList; import java.util.Collections; diff --git a/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java b/Essentials/src/com/earth2me/essentials/utils/textreader/HelpInput.java index 4efb6c43f..cb3be1be4 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java +++ b/Essentials/src/com/earth2me/essentials/utils/textreader/HelpInput.java @@ -1,12 +1,15 @@ -package com.earth2me.essentials.textreader; +package com.earth2me.essentials.utils.textreader; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.permissions.HelpPermissions; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; +import lombok.Cleanup; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; @@ -21,8 +24,11 @@ public class HelpInput implements IText private final transient Map<String, Integer> bookmarks = new HashMap<String, Integer>(); private final static Logger logger = Logger.getLogger("Minecraft"); - public HelpInput(final User user, final String match, final IEssentials ess) throws IOException + public HelpInput(final IUser user, final String match, final IEssentials ess) throws IOException { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); boolean reported = false; final List<String> newLines = new ArrayList<String>(); String pluginName = ""; @@ -62,14 +68,14 @@ public class HelpInput implements IText if (pluginNameLow.contains("essentials")) { final String node = "essentials." + k.getKey(); - if (!ess.getSettings().isCommandDisabled(k.getKey()) && user.isAuthorized(node)) + if (!settings.getData().getCommands().isDisabled(k.getKey()) && user.hasPermission(node)) { pluginLines.add(_("helpLine", k.getKey(), k.getValue().get(DESCRIPTION))); } } else { - if (ess.getSettings().showNonEssCommandsInHelp()) + if (settings.getData().getCommands().getHelp().isShowNonEssCommandsInHelp()) { final Map<String, Object> value = k.getValue(); Object permissions = null; @@ -81,7 +87,7 @@ public class HelpInput implements IText { permissions = value.get(PERMISSIONS); } - if (user.isAuthorized("essentials.help." + pluginNameLow)) + if (HelpPermissions.getPermission(pluginNameLow).isAuthorized(user)) { pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); } @@ -90,7 +96,7 @@ public class HelpInput implements IText boolean enabled = false; for (Object o : (List<Object>)permissions) { - if (o instanceof String && user.isAuthorized(o.toString())) + if (o instanceof String && user.hasPermission(o.toString())) { enabled = true; break; @@ -103,14 +109,14 @@ public class HelpInput implements IText } else if (permissions instanceof String && !"".equals(permissions)) { - if (user.isAuthorized(permissions.toString())) + if (user.hasPermission(permissions.toString())) { pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); } } else { - if (!ess.getSettings().hidePermissionlessHelp()) + if (!settings.getData().getCommands().getHelp().isHidePermissionlessCommands()) { pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); } diff --git a/Essentials/src/com/earth2me/essentials/textreader/IText.java b/Essentials/src/com/earth2me/essentials/utils/textreader/IText.java index 851119701..c70554b28 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/IText.java +++ b/Essentials/src/com/earth2me/essentials/utils/textreader/IText.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.textreader; +package com.earth2me.essentials.utils.textreader; import java.util.List; import java.util.Map; diff --git a/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java b/Essentials/src/com/earth2me/essentials/utils/textreader/KeywordReplacer.java index d79483699..c38c39167 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java +++ b/Essentials/src/com/earth2me/essentials/utils/textreader/KeywordReplacer.java @@ -1,13 +1,14 @@ -package com.earth2me.essentials.textreader; +package com.earth2me.essentials.utils.textreader; -import com.earth2me.essentials.DescParseTickFormat; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +import com.earth2me.essentials.utils.DescParseTickFormat; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; +import lombok.Cleanup; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -36,14 +37,16 @@ public class KeywordReplacer implements IText String userName, address, version; if (sender instanceof Player) { - final User user = ess.getUser(sender); + @Cleanup + final IUser user = ess.getUser((Player)sender); + user.acquireReadLock(); user.setDisplayNick(); displayName = user.getDisplayName(); userName = user.getName(); ipAddress = user.getAddress().getAddress().toString(); address = user.getAddress().toString(); balance = Double.toString(user.getMoney()); - mails = Integer.toString(user.getMails().size()); + mails = Integer.toString(user.getData().getMails() == null ? 0 : user.getData().getMails().size()); world = user.getLocation().getWorld().getName(); worldTime12 = DescParseTickFormat.format12(user.getWorld().getTime()); worldTime24 = DescParseTickFormat.format24(user.getWorld().getTime()); diff --git a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java b/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextInput.java index a9f9e1480..4a94126d3 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java +++ b/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextInput.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.textreader; +package com.earth2me.essentials.utils.textreader; import java.util.ArrayList; import java.util.Collections; diff --git a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java b/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextPager.java index ea1b787d5..3c9e9cb55 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java +++ b/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextPager.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.textreader; +package com.earth2me.essentials.utils.textreader; import org.bukkit.command.CommandSender; diff --git a/Essentials/src/com/earth2me/essentials/textreader/TextInput.java b/Essentials/src/com/earth2me/essentials/utils/textreader/TextInput.java index 6e9256b4c..8c8b7faca 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/TextInput.java +++ b/Essentials/src/com/earth2me/essentials/utils/textreader/TextInput.java @@ -1,11 +1,14 @@ -package com.earth2me.essentials.textreader; +package com.earth2me.essentials.utils.textreader; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; +import com.earth2me.essentials.utils.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.api.InvalidNameException; import java.io.*; import java.lang.ref.SoftReference; import java.util.*; +import java.util.logging.Level; +import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -24,11 +27,18 @@ public class TextInput implements IText File file = null; if (sender instanceof Player) { - final User user = ess.getUser(sender); - file = new File(ess.getDataFolder(), filename + "_" + Util.sanitizeFileName(user.getName()) + ".txt"); - if (!file.exists()) + try { - file = new File(ess.getDataFolder(), filename + "_" + Util.sanitizeFileName(user.getGroup()) + ".txt"); + final IUser user = ess.getUser((Player)sender); + file = new File(ess.getDataFolder(), filename + "_" + Util.sanitizeFileName(user.getName()) + ".txt"); + if (!file.exists()) + { + file = new File(ess.getDataFolder(), filename + "_" + Util.sanitizeFileName(ess.getRanks().getMainGroup(user)) + ".txt"); + } + } + catch (InvalidNameException ex) + { + Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex); } } if (file == null || !file.exists()) @@ -75,9 +85,9 @@ public class TextInput implements IText if (line.length() > 0 && line.charAt(0) == '#') { bookmarks.put(line.substring(1).toLowerCase(Locale.ENGLISH).replaceAll("&[0-9a-fk]", ""), lineNumber); - chapters.add(line.substring(1).replace('&', '§').replace("§§", "&")); + chapters.add(line.substring(1).replace('&', '�').replace("�", "&")); } - lines.add(line.replace('&', '§').replace("§§", "&")); + lines.add(line.replace('&', '�').replace("�", "&")); lineNumber++; } } diff --git a/Essentials/src/com/earth2me/essentials/textreader/TextPager.java b/Essentials/src/com/earth2me/essentials/utils/textreader/TextPager.java index cb70839dd..cac760441 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/TextPager.java +++ b/Essentials/src/com/earth2me/essentials/utils/textreader/TextPager.java @@ -1,4 +1,4 @@ -package com.earth2me.essentials.textreader; +package com.earth2me.essentials.utils.textreader; import com.earth2me.essentials.I18n; import static com.earth2me.essentials.I18n._; diff --git a/Essentials/src/config.yml b/Essentials/src/config.yml index 3e003c9ae..d24dbe348 100644 --- a/Essentials/src/config.yml +++ b/Essentials/src/config.yml @@ -197,6 +197,13 @@ kits: - 273 1 - 274 1 - 275 1 + tools: + delay: 10 + items: + - 272 1 + - 273 1 + - 274 1 + - 275 1 # Essentials Sign Control # See http://ess.khhq.net/wiki/Sign_Tutorial for instructions on how to use these. @@ -308,6 +315,13 @@ repair-enchanted: true #If you set this to true any plugin that uses teleport will have the previous location registered. register-back-in-listener: false +#Set timeout in seconds for players to accept tpa before request is cancelled. +#Set to 0 for no timeout +tpa-accept-cancellation: 0 + +#Cancels a request made by tpa / tpc on world change to prevent cross world tp +cancel-tp-requests-on-world-change: false + #Delay to wait before people can cause attack damage after logging in login-attack-delay: 0 diff --git a/Essentials/src/items.csv b/Essentials/src/items.csv index 7f20e1048..8b462ab66 100644 --- a/Essentials/src/items.csv +++ b/Essentials/src/items.csv @@ -1,4 +1,4 @@ -#version: TeamCity +#version: ${build.number} #If you change this file, it will not be automatically updated after the next release, #item,id,metadata stone,1,0 diff --git a/Essentials/src/messages.properties b/Essentials/src/messages.properties index ea765213f..5be1c7067 100644 --- a/Essentials/src/messages.properties +++ b/Essentials/src/messages.properties @@ -1,4 +1,4 @@ -#version: TeamCity +#version: ${build.number} # Single quotes have to be doubled: '' # Translations start here # by: @@ -175,7 +175,7 @@ kitError2=\u00a7cThat kit does not exist or is improperly defined. kitError=\u00a7cThere are no valid kits. kitErrorHelp=\u00a7cPerhaps an item is missing a quantity in the configuration? kitGive=\u00a77Giving kit {0}. -kitInvFull=\u00a7cYour inventory was full, placing kit on the floor +InvFull=\u00a7cYour inventory was full, dropping items on the floor kitTimed=\u00a7cYou can''t use that kit again for another {0}. kits=\u00a77Kits: {0} lightningSmited=\u00a77Thou hast been smitten @@ -313,6 +313,7 @@ requiredBukkit= * ! * You need atleast build {0} of CraftBukkit, download it fro returnPlayerToJailError=Error occurred when trying to return player {0} to jail: {1} second=second seconds=seconds +seenBanReason=Reason: {0} seenOffline=Player {0} is offline since {1} seenOnline=Player {0} is online since {1} serverFull=Server is full @@ -343,6 +344,7 @@ teleportDisabled={0} has teleportation disabled. teleportHereRequest=\u00a7c{0}\u00a7c has requested that you teleport to them. teleportNewPlayerError=Failed to teleport new player teleportRequest=\u00a7c{0}\u00a7c has requested to teleport to you. +teleportRequestsCancelledWorldChange=\u00a77Pending teleport requests have been cancelled on world change. teleportRequestTimeoutInfo=\u00a77This request will timeout after {0} seconds. teleportTop=\u00a77Teleporting to top. teleportationCommencing=\u00a77Teleportation commencing... @@ -406,6 +408,7 @@ warpUsePermission=\u00a7cYou do not have Permission to use that warp. warpingTo=\u00a77Warping to {0}. warps=Warps: {0} warpsCount=\u00a77There are {0} warps. Showing page {1} of {2}. +warpOverwrite=\u00a7cYou cannot overwrite that warp. weatherStorm=\u00a77You set the weather to storm in {0} weatherStormFor=\u00a77You set the weather to storm in {0} for {1} seconds weatherSun=\u00a77You set the weather to sun in {0} diff --git a/Essentials/src/messages_fr.properties b/Essentials/src/messages_fr.properties index a101355ba..43edb4e32 100644 --- a/Essentials/src/messages_fr.properties +++ b/Essentials/src/messages_fr.properties @@ -1,4 +1,4 @@ -#version: TeamCity +#version: ${build.number} # Single quotes have to be doubled: '' # Translations start here # by: L\u00e9a Gris @@ -12,7 +12,6 @@ alertUsed=a utilis\u00e9 : autoAfkKickReason=Vous avez \u00e9t\u00e9 \u00e9ject\u00e9 pour inactivit\u00e9e sup\u00e9rieure \u00e0 {0} minutes. backAfterDeath=\u00a77Utilisez la commande /back pour retourner \u00e0 l''endroit ou vous \u00eates mort. backUsageMsg=\u00a77Retour \u00e0 votre emplacement pr\u00e9c\u00c3\u00a8dent. -backupDisabled=An external backup script has not been configured. backupFinished=Sauvegarde termin\u00e9 backupStarted=D\u00e9but de la sauvegarde... balance=\u00a77Solde : {0} @@ -51,7 +50,6 @@ creatingConfigFromTemplate=Cr\u00e9ation de la configuration \u00e0 partir du mo creatingEmptyConfig=Cr\u00e9ation d''une configuration vierge : {0} creative=cr\u00e9atif currency={0}{1} -currentWorld=Current World: {0} day=jour days=jours defaultBanReason=Le marteau du bannissement a frapp\u00e9 ! @@ -94,7 +92,6 @@ false=non feed=\u00a77Vous avez \u00e9t\u00e9 rassasi\u00e9. feedOther=\u00a77 est rassasi\u00e9 {0}. fileRenameError=Echec du changement de nom de {0} -flyMode=\u00a77Set fly mode {0} for {1}. foreverAlone=\u00a7cVous n''avez personne \u00e0 qui r\u00e9pondre freedMemory=A lib\u00e9r\u00e9 {0} Mo. gameMode=\u00a77Mode de jeu {0} pour {1}. @@ -113,12 +110,9 @@ haveBeenReleased=\u00a77Vous avez \u00e9t\u00e9 lib\u00e9r\u00e9. heal=\u00a77Vous avez \u00e9t\u00e9 soign\u00e9. healOther=\u00a77{0} a \u00e9t\u00e9 soign\u00e9. helpConsole=Pour voir l''aide tapez ? -helpFrom=\u00a77Commands from {0}: helpLine=\u00a76/{0}\u00a7f: {1} -helpMatching=\u00a77Commands matching "{0}": helpOp=\u00a7c[Aide Admin]\u00a7f \u00a77{0} : \u00a7f {1} helpPages=Page \u00a7c{0}\u00a7f sur \u00a7c{1}\u00a7f. -helpPlugin=\u00a74{0}\u00a7f: Plugin Help: /help {1} holeInFloor=Trou dans le Sol. homeSet=\u00a77R\u00e9sidence d\u00e9finie. homeSetToBed=\u00a77Votre r\u00e9sidence est d\u00e9sormais li\u00e9e \u00e0 ce lit. @@ -130,7 +124,7 @@ illegalDate=Format de date ill\u00e9gal. infoChapter=S\u00e9lectionnez le chapitre : infoChapterPages=Chapitre {0}, page \u00a7c{1}\u00a7f sur \u00a7c{2}\u00a7f: infoFileDoesNotExist=Le fichier info.txt n'existe pas. Le fichier est en cours de cr\u00e9ation pour vous. -infoPages=\u00a7e ---- \u00a76{2} \u00a7e--\u00a76 Page \u00a74{0}\u00a76/\u00a74{1} \u00a7e---- +infoPages=Page \u00a7c{0}\u00a7f de \u00a7c{1}\u00a7f. infoUnknownChapter=Chapitre inconnu. invBigger=Les inventaires des autres joueurs sont plus gros que le v\u00f4tre. invRestored=Votre inventaire vous a \u00e9t\u00e9 rendu. @@ -163,7 +157,6 @@ jailReleasedPlayerNotify=\u00a77Vous avez \u00e9t\u00e9 lib\u00e9r\u00e9 ! jailSentenceExtended=Dur\u00e9e d''emprisonnement rallong\u00e9e de : {0) jailSet=\u00a77La prison {0} a \u00e9t\u00e9 cr\u00e9\u00e9. jumpError=\u00c7a aurait pu faire mal au cerveau de votre ordinateur. -kickedAll=\u00a7cKicked all players from server kickDefault=\u00c9ject\u00e9 du serveur kickExempt=\u00a77Vous ne pouvez pas \u00e9jecter ce joueur. kill=\u00a77Tu\u00e9 {0}. @@ -171,7 +164,7 @@ kitError2=\u00a7cCe kit n'existe pas ou a \u00e9t\u00e9 mal d\u00e9fini. kitError=\u00a7cIl n'y a pas de kits valides. kitErrorHelp=\u00a7cPeut-\u00eatre qu'un objet manque d'une quantit\u00e9 dans la configuration ? kitGive=\u00a77Donner le kit {0}. -kitInvFull=\u00a7cVotre inventaire \u00e9tait plein, le kit est parre-terre. +InvFull=\u00a7cYour inventory was full, dropping items on the floor kitTimed=\u00a7cVous ne pouvez pas utiliser ce kit pendant encore {0}. kits=\u00a77Kits :{0} lightningSmited=\u00a77Vous venez d'\u00eatre foudroy\u00e9. @@ -212,6 +205,7 @@ mutedPlayer=Le joueur {0} est d\u00e9sormais muet. mutedPlayerFor={0} a \u00e9t\u00e9 muet pour {1}. mutedUserSpeaks={0} a essay\u00e9 de parler mais est muet. nearbyPlayers=Joueurs dans les environs : {0} +needTpohere=Vous avez besoin de l'acc\u00c3\u00a8s \u00e0 /tpohere pour t\u00e9l\u00e9porter d'autres joueurs. negativeBalanceError=L'utilisateur n'est pas autoris\u00e9 \u00e0 avoir un solde n\u00e9gatif. nickChanged=surnom modifi\u00e9. nickDisplayName=\u00a77Vous devez activer change-displayname dans la configuration Essentials. @@ -305,10 +299,11 @@ requestDenied=\u00a77Demande de t\u00e9l\u00e9portation refus\u00e9e. requestDeniedFrom=\u00a77{0} a refus\u00e9 votre demande de t\u00e9l\u00e9portation. requestSent=\u00a77Requ\u00eate envoy\u00e9e \u00e0 {0}\u00a77. requestTimedOut=\u00a7cLa de mande de t\u00e9l\u00e9portation a expir\u00e9. -requiredBukkit=* ! * Vous avez besoin au moins de la version {0} de CraftBukkit. T\u00e9l\u00e9chargez-la ici http://dl.bukkit.org/downloads/craftbukkit/ +requiredBukkit=* ! * Vous avez besoin au moins de la version {0} de CraftBukkit. T\u00e9l\u00e9chargez-la ici http://ci.bukkit.org. returnPlayerToJailError=Error occurred when trying to return player {0} to jail: {1} second=seconde seconds=secondes +seenBanReason=Reason: {0} seenOffline=Le joueur {0} est hors ligne depuis {1} seenOnline=Le joueur {0} est en ligne depuis {1} serverFull=Le serveur est plein. @@ -339,6 +334,7 @@ teleportDisabled={0} a la t\u00e9l\u00e9portation d\u00e9sactiv\u00e9. teleportHereRequest=\u00a7c{0}\u00a7c Vous a demand\u00e9 de vous t\u00e9l\u00e9porter \u00e0 lui/elle. teleportNewPlayerError=\u00c9chec de la t\u00e9l\u00e9portation du nouveau joueur. teleportRequest=\u00a7c{0}\u00a7c vous demande s''il peut se t\u00e9l\u00e9porter vers vous. +teleportRequestsCancelledWorldChange=\u00a77Pending teleport requests have been cancelled on world change. teleportRequestTimeoutInfo=\u00a77Cette demande de t\u00e9l\u00e9portation expirera dans {0} secondes. teleportTop=\u00a77T\u00e9l\u00e9portation vers le haut. teleportationCommencing=\u00a77D\u00e9but de la t\u00e9l\u00e9portation... @@ -392,18 +388,17 @@ voiceSilenced=\u00a77Vous avez \u00e9t\u00e9 r\u00e9duit au silence. warpDeleteError=Probl\u00c3\u00a8me concernant la suppression du fichier warp. warpListPermission=\u00a7cVous n'avez pas la permission d'afficher la liste des points de t\u00e9l\u00e9portation. warpNotExist=Ce point de t\u00e9l\u00e9portation n'existe pas. -warpOverwrite=\u00a7cYou cannot overwrite that warp. warpSet=\u00a77Le point de t\u00e9l\u00e9portation {0} a \u00e9t\u00e9 cr\u00e9\u00e9. warpUsePermission=\u00a7cVous n'avez pas la permission d'utiliser ce point de t\u00e9l\u00e9portation. warpingTo=\u00a77T\u00e9l\u00e9portation vers {0}. warps=point de t\u00e9l\u00e9portations : {0} warpsCount=\u00a77Il y a {0} points de t\u00e9l\u00e9portations. Page {1} sur {2}. +warpOverwrite=\u00a7cYou cannot overwrite that warp. weatherStorm=\u00a77Vous avez programm\u00e9 l''orage dans {0} weatherStormFor=\u00a77Vous avez programm\u00e9 l''orage dans {0} pour {1} secondes. weatherSun=\u00a77Vous avez programm\u00e9 le beau temps dans {0} weatherSunFor=\u00a77Vous avez programm\u00e9 le beau temps dans {0} pour {1} secondes. whoisBanned=\u00a79 - Banni : {0} -whoisExp=\u00a79 - Exp: {0} (Level {1}) whoisGamemode=\u00a79 - Mode de jeu : {0} whoisGeoLocation=\u00a79 - Emplacement : {0} whoisGod=\u00a79 - Mode Dieu : {0} @@ -423,12 +418,3 @@ year=ann\u00e9e years=ann\u00e9es youAreHealed=\u00a77Vous avez \u00e9t\u00e9 soign\u00e9. youHaveNewMail=\u00a7cVous avez {0} messages ! \u00a7fEntrez \u00a77/mail read\u00a7f pour voir votre courrier. -exp=\u00a7c{0} \u00a77has\u00a7c {1} \u00a77exp (level\u00a7c {2}\u00a77) and needs\u00a7c {3} \u00a77more exp to level up. -expSet=\u00a7c{0} \u00a77now has\u00a7c {1} \u00a77exp. -unvanished=\u00a7aYou are once again visible. -unvanishedReload=\u00a7cA reload has forced you to become visible. -vanished=\u00a7aYou have now been vanished. -tps=Current TPS = {0} -hatPlaced=\u00a7eEnjoy your new hat! -hatFail=\u00a7cYou must have something to wear in your hand. -hatArmor=\u00a7cError, you cannot use armor as a hat! diff --git a/Essentials/src/messages_nl.properties b/Essentials/src/messages_nl.properties index 17aa50829..342d5ca95 100644 --- a/Essentials/src/messages_nl.properties +++ b/Essentials/src/messages_nl.properties @@ -1,4 +1,4 @@ -#version: TeamCity +#version: ${build.number} # Single quotes have to be doubled: '' # Translations start here # by: Geertje123 @@ -171,7 +171,7 @@ kitError2=\u00a7cDie kit bestaat niet of is verkeerde beschreven. kitError=\u00a7cEr zijn geen geldige kits. kitErrorHelp=\u00a7cMisschien mist er een hoeveelheid van het item in de configuratie? kitGive=\u00a77Kit {0} wordt gegeven. -kitInvFull=\u00a7cJe inventory was vol, de kit wordt op de grond geplaatst +InvFull=\u00a7cYour inventory was full, dropping items on the floor kitTimed=\u00a7cJe kan die kit pas weer gebruiken over {0}. kits=\u00a77Kits: {0} lightningSmited=\u00a77Je bent zojuist verbrand @@ -309,6 +309,7 @@ requiredBukkit=* ! * You need atleast build {0} of CraftBukkit, download it from returnPlayerToJailError=Error occurred when trying to return player {0} to jail: {1} second=seconde seconds=seconde +seenBanReason=Reason: {0} seenOffline=Speler {0} is offline vanaf {1} seenOnline=Speler {0} is online vanaf {1} serverFull=Server is vol @@ -339,6 +340,7 @@ teleportDisabled={0} heeft teleporteren uit gezet. teleportHereRequest=\u00a7c{0}\u00a7c Heeft gevraagd of hij/zij naar jou mag teleporteren. teleportNewPlayerError=Fout bij het teleporteren van nieuwe speler. teleportRequest=\u00a7c{0}\u00a7c vraagt of hij jou kan teleporteren. +teleportRequestsCancelledWorldChange=\u00a77Pending teleport requests have been cancelled on world change. teleportRequestTimeoutInfo=\u00a77This request will timeout after {0} seconds. teleportTop=\u00a77Bezig met teleporteren naar de top. teleportationCommencing=\u00a77Aan het beginnen met teleporteren... @@ -398,6 +400,7 @@ warpUsePermission=\u00a7cOnbevoegd om die warp te gebruiken. warpingTo=\u00a77Aan het warpen naar {0}. warps=Warps: {0} warpsCount=\u00a77There are {0} warps. Showing page {1} of {2}. +warpOverwrite=\u00a7cYou cannot overwrite that warp. weatherStorm=\u00a77Je hebt het weer naar storm gezet in de {0} weatherStormFor=\u00a77Je hebt het weer in de {0} naar storm gezet voor {1} seconde weatherSun=\u00a77Je hebt het weer naar zon gezet in de {0} diff --git a/Essentials/src/plugin.yml b/Essentials/src/plugin.yml index 8cacc0c11..76e65e61f 100644 --- a/Essentials/src/plugin.yml +++ b/Essentials/src/plugin.yml @@ -1,9 +1,9 @@ # This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) -name: Essentials +name: Essentials3 main: com.earth2me.essentials.Essentials # Note to developers: This next line cannot change, or the automatic versioning system will break. -version: TeamCity -website: http://tiny.cc/EssentialsCommands +version: ${build.number} +website: http://tiny.cc/EssentialsWiki description: Provides an essential, core set of commands for Bukkit. authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits, md_5] commands: @@ -202,6 +202,9 @@ commands: kittycannon: description: Throw an exploding kitten at your opponent usage: /<command> + kittycannon: + description: Throw an exploding kitten at your opponent + usage: /<command> list: description: List all online players. usage: /<command> @@ -302,6 +305,10 @@ commands: description: Creates a jail where you specified named [jailname] usage: /<command> <jailname> aliases: [esetjail] + setspawn: + description: Set the spawnpoint to your current position. + usage: /<command> <group> + aliases: [esetspawn] setwarp: description: Creates a new warp. usage: /<command> <warp> @@ -314,6 +321,10 @@ commands: description: Toggles if you can see msg/mail commands in chat. usage: /<command> aliases: [esocialspy] + spawn: + description: Teleport to the spawnpoint. + usage: /<command> [player] + aliases: [esetspawn] spawner: description: Change the mob type of a spawner usage: /<command> <mob> @@ -369,7 +380,7 @@ commands: tpahere: description: Request that the specified player teleport to you. usage: /<command> <player> - aliases: [etpahere] + aliases: [come,etpahere,ecome] tpall: description: Teleport all online players to another player. usage: /<command> <player> |