diff options
332 files changed, 10259 insertions, 7497 deletions
diff --git a/.gitignore b/.gitignore index 6c25fbdd7..21875b641 100644 --- a/.gitignore +++ b/.gitignore @@ -37,4 +37,8 @@ /WebPush/apikey.php /WebPush/nbproject/private /.idea -*.iml
\ No newline at end of file +*.iml +/EssentialsSigns/nbproject/private/ +/Essentials2Compat/nbproject/private/ +/Essentials2Compat/dist/ +/Essentials2Compat/build/
\ No newline at end of file diff --git a/Essentials/nbproject/project.properties b/Essentials/nbproject/project.properties index 4e80ceafa..d9a76ba1e 100644 --- a/Essentials/nbproject/project.properties +++ b/Essentials/nbproject/project.properties @@ -120,7 +120,7 @@ javadoc.reference.PermissionsEx.jar=../lib/PermissionsEx-javadoc.jar javadoc.splitindex=true javadoc.use=true javadoc.version=false -javadoc.windowtitle= +javadoc.windowtitle=Essentials Docs. jnlp.codebase.type=no.codebase jnlp.descriptor=application jnlp.enabled=false 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 index ada36c9d7..ea52c2792 100644 --- a/Essentials/src/com/earth2me/essentials/Backup.java +++ b/Essentials/src/com/earth2me/essentials/Backup.java @@ -1,23 +1,29 @@ package com.earth2me.essentials; 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 +public class Backup implements Runnable, IBackup { - private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private static final Logger LOGGER = Bukkit.getLogger(); private transient final Server server; private transient final IEssentials ess; - private transient boolean running = false; + private transient final AtomicBoolean running = new AtomicBoolean(false); private transient int taskId = -1; - private transient boolean active = false; + private transient final AtomicBoolean active = new AtomicBoolean(false); public Backup(final IEssentials ess) { @@ -29,106 +35,119 @@ public class Backup implements Runnable } } - void onPlayerJoin() - { - startTask(); - } - - private void startTask() + @Override + public final void startTask() { - if (!running) + if (running.compareAndSet(false, true)) { - final long interval = ess.getSettings().getBackupInterval() * 1200; // minutes -> ticks + @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); - running = true; } } @Override public void run() { - if (active) + if (!active.compareAndSet(false, true)) { return; } - active = true; - final String command = ess.getSettings().getBackupCommand(); - if (command == null || "".equals(command)) + @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 cs = server.getConsoleSender(); - server.dispatchCommand(cs, "save-all"); - server.dispatchCommand(cs, "save-off"); + 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; + } - 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 { - @Override - public void run() + child.waitFor(); + String line; + do { - 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 + line = reader.readLine(); + if (line != null) { - 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")); - } - }); + 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/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/DescParseTickFormat.java b/Essentials/src/com/earth2me/essentials/DescParseTickFormat.java index bf3037e59..ab8e6d6a3 100644 --- a/Essentials/src/com/earth2me/essentials/DescParseTickFormat.java +++ b/Essentials/src/com/earth2me/essentials/DescParseTickFormat.java @@ -16,9 +16,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/Enchantments.java b/Essentials/src/com/earth2me/essentials/Enchantments.java index 5ce10d75d..c4c6be3a4 100644 --- a/Essentials/src/com/earth2me/essentials/Enchantments.java +++ b/Essentials/src/com/earth2me/essentials/Enchantments.java @@ -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>(); @@ -62,7 +67,7 @@ public class Enchantments ENCHANTMENTS.put("infarrows", 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/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java index 7e413f9cf..7a331c3d0 100644 --- a/Essentials/src/com/earth2me/essentials/Essentials.java +++ b/Essentials/src/com/earth2me/essentials/Essentials.java @@ -18,17 +18,14 @@ package com.earth2me.essentials; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.Economy; -import com.earth2me.essentials.api.IJails; -import com.earth2me.essentials.commands.EssentialsCommand; -import com.earth2me.essentials.commands.IEssentialsCommand; -import com.earth2me.essentials.commands.NoChargeException; -import com.earth2me.essentials.commands.NotEnoughArgumentsException; +import com.earth2me.essentials.api.*; +import com.earth2me.essentials.craftbukkit.BetterLocation; +import com.earth2me.essentials.listener.*; import com.earth2me.essentials.perm.PermissionsHandler; import com.earth2me.essentials.register.payment.Methods; -import com.earth2me.essentials.signs.SignBlockListener; -import com.earth2me.essentials.signs.SignEntityListener; -import com.earth2me.essentials.signs.SignPlayerListener; +import com.earth2me.essentials.settings.GroupsHolder; +import com.earth2me.essentials.settings.SettingsHolder; +import com.earth2me.essentials.user.UserMap; import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -42,20 +39,16 @@ 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; @@ -65,18 +58,21 @@ public class Essentials extends JavaPlugin implements IEssentials 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 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 IGroups groups; private transient final Methods paymentMethod = new Methods(); private transient PermissionsHandler permissionsHandler; - private transient AlternativeCommandsHandler alternativeCommandsHandler; - private transient UserMap userMap; + private transient IUserMap userMap; private transient ExecuteTimer execTimer; private transient I18n i18n; + private transient ICommandHandler commandHandler; + public transient boolean testing; @Override public ISettings getSettings() @@ -86,6 +82,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()) { @@ -100,10 +97,10 @@ 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); + permissionsHandler = new PermissionsHandler(this); Economy.setEss(this); } @@ -145,27 +142,33 @@ 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 GroupsHolder(this); + reloadList.add(groups); + warps = new Warps(this); + reloadList.add(warps); execTimer.mark("Init(Spawn/Warp)"); - worth = new Worth(this.getDataFolder()); - confList.add(worth); + worth = new Worth(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); reload(); } catch (YAMLException exception) @@ -195,11 +198,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); @@ -207,29 +209,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); + final EssentialsTimer timer = new EssentialsTimer(this); - getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 100); + getServer().getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 100); Economy.setEss(this); execTimer.mark("RegListeners"); final String timeroutput = execTimer.end(); @@ -245,6 +235,7 @@ public class Essentials extends JavaPlugin implements IEssentials i18n.onDisable(); Economy.setEss(null); Trade.closeLog(); + BetterLocation.cleanup(); } @Override @@ -252,10 +243,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()); @@ -264,202 +255,50 @@ 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()); - return pc.execute(sender, commandLabel, args); - } - } - - 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; } - + @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; + return userMap.getUser(player); } - - 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; - } - + @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 @@ -477,9 +316,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 @@ -503,8 +342,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); } @@ -516,27 +355,28 @@ 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() { @@ -550,19 +390,13 @@ public class Essentials extends JavaPlugin implements IEssentials } @Override - public AlternativeCommandsHandler getAlternativeCommandsHandler() - { - return alternativeCommandsHandler; - } - - @Override - public ItemDb getItemDb() + public IItemDb getItemDb() { return itemDb; } @Override - public UserMap getUserMap() + public IUserMap getUserMap() { return userMap; } @@ -572,46 +406,16 @@ public class Essentials extends JavaPlugin implements IEssentials { return i18n; } - - private static class EssentialsWorldListener implements Listener, Runnable { - 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 IGroups getGroups() + { + return groups; + } - @Override - public void run() - { - ess.reload(); - } + @Override + public ICommandHandler getCommandHandler() + { + return commandHandler; } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsCommandHandler.java b/Essentials/src/com/earth2me/essentials/EssentialsCommandHandler.java new file mode 100644 index 000000000..1c04a5694 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsCommandHandler.java @@ -0,0 +1,292 @@ +package com.earth2me.essentials; + +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.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()); + return pc.execute(sender, commandLabel, args); + } + } + + 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 (user != null && !user.isAuthorized(cmd)) + { + 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/EssentialsEntityListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java deleted file mode 100644 index e4879186d..000000000 --- a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import java.util.List; -import org.bukkit.Material; -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.EntityRegainHealthEvent.RegainReason; -import org.bukkit.event.entity.*; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsEntityListener implements Listener -{ - private final IEssentials ess; - - public EssentialsEntityListener(IEssentials ess) - { - this.ess = ess; - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onEntityDamage(EntityDamageEvent event) - { - if (event instanceof EntityDamageByEntityEvent) - { - EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event; - Entity eAttack = edEvent.getDamager(); - Entity eDefend = edEvent.getEntity(); - if (eDefend instanceof Player && eAttack instanceof Player) - { - User defender = ess.getUser(eDefend); - User attacker = ess.getUser(eAttack); - attacker.updateActivity(true); - ItemStack is = attacker.getItemInHand(); - List<String> commandList = attacker.getPowertool(is); - if (commandList != null && !commandList.isEmpty()) - { - for (String command : commandList) - { - - if (command != null && !command.isEmpty()) - { - attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", defender.getName())); - event.setCancelled(true); - return; - } - } - } - } - if (eDefend instanceof Animals && eAttack instanceof Player) - { - User player = ess.getUser(eAttack); - ItemStack hand = player.getItemInHand(); - if (hand != null && hand.getType() == Material.MILK_BUCKET) - { - ((Animals)eDefend).setAge(-24000); - hand.setType(Material.BUCKET); - player.setItemInHand(hand); - player.updateInventory(); - event.setCancelled(true); - } - } - } - if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled()) - { - final Player player = (Player)event.getEntity(); - player.setFireTicks(0); - player.setRemainingAir(player.getMaximumAir()); - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onEntityCombust(EntityCombustEvent event) - { - if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled()) - { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onEntityDeath(final EntityDeathEvent event) - { - if (event instanceof PlayerDeathEvent) - { - final PlayerDeathEvent pdevent = (PlayerDeathEvent)event; - final User user = ess.getUser(pdevent.getEntity()); - if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back")) - { - user.setLastLocation(); - user.sendMessage(_("backAfterDeath")); - } - if (!ess.getSettings().areDeathMessagesEnabled()) - { - pdevent.setDeathMessage(""); - } - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onFoodLevelChange(FoodLevelChangeEvent event) - { - if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled()) - { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onEntityRegainHealth(EntityRegainHealthEvent event) - { - if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player - && ess.getUser(event.getEntity()).isAfk() && ess.getSettings().getFreezeAfkPlayers()) - { - event.setCancelled(true); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java index f3b447dae..66fba3822 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java @@ -1,7 +1,13 @@ 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.user.UserData.TimestampType; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Set; import org.bukkit.entity.Player; @@ -9,7 +15,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>(); EssentialsTimer(final IEssentials ess) { @@ -22,19 +28,37 @@ public class EssentialsTimer implements Runnable final long currentTime = System.currentTimeMillis(); for (Player player : ess.getServer().getOnlinePlayers()) { - 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 && user.isAuthorized("essentials.mail") && !user.gotMailInfo()) + { + final List<String> mail = user.getMails(); + if (mail != null && !mail.isEmpty()) + { + user.sendMessage(_("youHaveNewMail", mail.size())); + } + } } - 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/I18n.java b/Essentials/src/com/earth2me/essentials/I18n.java index 63fdcc065..c5fdaae50 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; 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 20c6c300e..000000000 --- a/Essentials/src/com/earth2me/essentials/IEssentials.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.api.IJails; -import com.earth2me.essentials.perm.PermissionsHandler; -import com.earth2me.essentials.register.payment.Methods; -import org.bukkit.World; -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(); -} 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 30a073dde..000000000 --- a/Essentials/src/com/earth2me/essentials/ISettings.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.commands.IEssentialsCommand; -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.bukkit.ChatColor; -import org.bukkit.event.EventPriority; - - -public interface ISettings extends IConf -{ - boolean areSignsDisabled(); - - String format(String format, IUser user); - - String getAnnounceNewPlayerFormat(IUser user); - - boolean getAnnounceNewPlayers(); - - 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(); - - Object getKit(String name); - - Map<String, Object> 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(); - - List 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(); - - boolean permissionBasedItemSpawn(); - - boolean showNonEssCommandsInHelp(); - - boolean spawnIfNoHome(); - - boolean warnOnBuildDisallow(); - - boolean warnOnSmite(); - - double getMaxMoney(); - - boolean isEcoLogEnabled(); - - boolean removeGodOnDisconnect(); - - boolean changeDisplayName(); - - boolean isPlayerCommand(String string); - - boolean useBukkitPermissions(); - - boolean addPrefixSuffix(); - - boolean disablePrefix(); - - boolean disableSuffix(); - - long getAutoAfk(); - - long getAutoAfkKick(); - - boolean getFreezeAfkPlayers(); - - boolean areDeathMessagesEnabled(); - - public void setDebug(boolean debug); - - Set<String> getNoGodWorlds(); - - boolean getUpdateBedAtDaytime(); - - boolean getRepairEnchanted(); - - boolean getIsWorldTeleportPermissions(); - - boolean registerBackInListener(); - - boolean getDisableItemPickupWhileAfk(); - - EventPriority getRespawnPriority(); - - long getTpaAcceptCancellation(); -} diff --git a/Essentials/src/com/earth2me/essentials/IUser.java b/Essentials/src/com/earth2me/essentials/IUser.java deleted file mode 100644 index bff556ab4..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 java.net.InetSocketAddress; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.inventory.PlayerInventory; - - -/** - * @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); - - 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..775c0df4e 100644 --- a/Essentials/src/com/earth2me/essentials/ItemDb.java +++ b/Essentials/src/com/earth2me/essentials/ItemDb.java @@ -1,16 +1,20 @@ package com.earth2me.essentials; -import com.earth2me.essentials.api.IItemDb; 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 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 +23,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 +37,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 && user.isAuthorized("essentials.oversizedstacks")) + { + stack.setAmount(oversizedStackSize); + } } + return stack; } public ItemStack get(final String id, final int quantity) throws Exception @@ -92,10 +120,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 f8ab2d02e..8fc504b5c 100644 --- a/Essentials/src/com/earth2me/essentials/Jails.java +++ b/Essentials/src/com/earth2me/essentials/Jails.java @@ -1,17 +1,23 @@ 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 static com.earth2me.essentials.I18n._; 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.event.Event.Priority; import org.bukkit.event.Event.Type; -import org.bukkit.event.block.*; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockListener; +import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.*; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.plugin.PluginManager; @@ -24,7 +30,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(); registerListeners(); } @@ -37,9 +43,9 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett pluginManager.registerEvent(Type.BLOCK_DAMAGE, blockListener, Priority.Low, ess); pluginManager.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Low, ess); pluginManager.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.Low, ess); - pluginManager.registerEvent(Type.PLAYER_RESPAWN, playerListener, Priority.High, ess); - pluginManager.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, ess); - pluginManager.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.High, ess); + pluginManager.registerEvent(Type.PLAYER_RESPAWN, playerListener, Priority.Highest, ess); + pluginManager.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.Highest, ess); + pluginManager.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Highest, ess); } @Override @@ -114,12 +120,20 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett acquireReadLock(); try { - if (!(user.getBase() instanceof OfflinePlayer)) + if (!(user.isOnline())) { Location loc = getJail(jail); user.getTeleport().now(loc, false, TeleportCause.COMMAND); } - user.setJail(jail); + user.acquireWriteLock(); + try + { + user.getData().setJail(jail); + } + finally + { + unlock(); + } } finally { @@ -151,8 +165,10 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @Override 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); } @@ -161,8 +177,10 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @Override 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); } @@ -171,8 +189,10 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @Override 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); } @@ -185,8 +205,10 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @Override 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); } @@ -195,15 +217,17 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @Override 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) { @@ -214,15 +238,17 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @Override 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) { @@ -234,15 +260,17 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett @Override 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 53d2e8784..000000000 --- a/Essentials/src/com/earth2me/essentials/Kit.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.commands.NoChargeException; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import java.util.*; -import org.bukkit.Material; -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 Map<String, Object> kits = ess.getSettings().getKits(); - final StringBuilder list = new StringBuilder(); - for (String kiteItem : kits.keySet()) - { - if (user.isAuthorized("essentials.kit." + kiteItem.toLowerCase(Locale.ENGLISH))) - { - list.append(" ").append(kiteItem); - } - } - return list.toString(); - } - catch (Exception ex) - { - throw new Exception(_("kitError")); - } - - } - - 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> els) throws Exception - { - try - { - return (List<String>)els.get("items"); - } - catch (Exception e) - { - user.sendMessage(_("kitError2")); - throw new Exception(_("kitErrorHelp")); - } - } - - 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("[^0-9]+", 3); - final int id = Material.getMaterial(Integer.parseInt(parts[0])).getId(); - final int amount = parts.length > 1 ? Integer.parseInt(parts[parts.length > 2 ? 2 : 1]) : 1; - final short data = parts.length > 2 ? Short.parseShort(parts[1]) : 0; - final Map<Integer, ItemStack> overfilled; - if (user.isAuthorized("essentials.oversizedstacks")) - { - overfilled = InventoryWorkaround.addItem(user.getInventory(), true, ess.getSettings().getOversizedStackSize(), new ItemStack(id, amount, data)); - } - else - { - overfilled = InventoryWorkaround.addItem(user.getInventory(), true, new ItemStack(id, amount, data)); - } - for (ItemStack itemStack : overfilled.values()) - { - user.getWorld().dropItemNaturally(user.getLocation(), itemStack); - spew = true; - } - } - user.updateInventory(); - if (spew) - { - user.sendMessage(_("kitInvFull")); - } - } - catch (Exception e) - { - user.updateInventory(); - throw new Exception(_("kitError2")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/Kits.java b/Essentials/src/com/earth2me/essentials/Kits.java new file mode 100644 index 000000000..612ea5196 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Kits.java @@ -0,0 +1,92 @@ +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 java.util.logging.Logger; +import org.bukkit.Bukkit; +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 fa0be02c7..000000000 --- a/Essentials/src/com/earth2me/essentials/OfflinePlayer.java +++ /dev/null @@ -1,860 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.craftbukkit.OfflineBedLocation; -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.entity.*; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.map.MapView; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionAttachment; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.Plugin; -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; - } - - public boolean isPlayer() - { - 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 getExperience() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setExperience(int i) - { - 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."); - } -} 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 dc9c9471e..000000000 --- a/Essentials/src/com/earth2me/essentials/Settings.java +++ /dev/null @@ -1,632 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.commands.IEssentialsCommand; -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.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; - - 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 List<String> getMultipleHomes() - { - return config.getKeys("sethome-multiple"); - } - - @Override - public int getHomeLimit(final User user) - { - final List<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", new ArrayList<String>(0))) - { - 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", new ArrayList<String>(0))) - { - 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", new ArrayList<String>(0))) - { - if (!c.equalsIgnoreCase(label)) - { - continue; - } - return true; - } - return false; - } - - @Override - public boolean isCommandOverridden(String name) - { - List<String> defaultList = new ArrayList<String>(1); - defaultList.add("god"); - for (String c : config.getStringList("overridden-commands", defaultList)) - { - 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); - } - - @Override - public Object getKit(String name) - { - Map<String, Object> kits = (Map<String, Object>)config.getProperty("kits"); - for (Map.Entry<String, Object> entry : kits.entrySet()) - { - if (entry.getKey().equalsIgnoreCase(name.replace('.', '_').replace('/', '_'))) - { - return entry.getValue(); - } - } - return null; - } - - @Override - public Map<String, Object> getKits() - { - return (Map<String, Object>)config.getProperty("kits"); - } - - @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.getByCode(Integer.parseInt(colorName, 16)); - } - - @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 config.getBoolean("signs-disabled", false); - } - - @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.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\\]"); - mFormat = new MessageFormat(format); - chatFormats.put(group, mFormat); - } - return mFormat; - } - - @Override - public boolean getAnnounceNewPlayers() - { - return !config.getString("newbies.announce-format", "-").isEmpty(); - } - - @Override - public String getAnnounceNewPlayerFormat(IUser user) - { - return format(config.getString("newbies.announce-format", "&dWelcome {DISPLAYNAME} to the server!"), user); - } - - @Override - public String format(String format, IUser user) - { - return format.replace('&', '§').replace("§§", "&").replace("{PLAYER}", user.getDisplayName()).replace("{DISPLAYNAME}", user.getDisplayName()).replace("{GROUP}", user.getGroup()).replace("{USERNAME}", user.getName()).replace("{ADDRESS}", user.getAddress().toString()); - } - - @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", Collections.<String>emptyList())); - chatFormats.clear(); - } - - @Override - public List<Integer> itemSpawnBlacklist() - { - final List<Integer> epItemSpwn = new ArrayList<Integer>(); - for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) - { - itemName = itemName.trim(); - if (itemName.isEmpty()) - { - continue; - } - ItemStack is; - try - { - is = ess.getItemDb().get(itemName); - epItemSpwn.add(is.getTypeId()); - } - catch (Exception ex) - { - logger.log(Level.SEVERE, _("unknownItemInList", itemName, "item-spawn-blacklist")); - } - } - return epItemSpwn; - } - - @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; - } - - @Override - public boolean isEcoLogEnabled() - { - return config.getBoolean("economy-log-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 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); - } - - @Override - public boolean getFreezeAfkPlayers() - { - return config.getBoolean("freeze-afk-players", false); - } - - @Override - public boolean areDeathMessagesEnabled() - { - return config.getBoolean("death-messages", true); - } - 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 getIsWorldTeleportPermissions() - { - return config.getBoolean("world-teleport-permissions", false); - } - - @Override - public boolean registerBackInListener() - { - return config.getBoolean("register-back-in-listener", false); - } - - @Override - public boolean getDisableItemPickupWhileAfk() - { - return config.getBoolean("disable-item-pickup-while-afk", true); - } - - @Override - public 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); - } -} diff --git a/Essentials/src/com/earth2me/essentials/Teleport.java b/Essentials/src/com/earth2me/essentials/Teleport.java index 9c21ffc6d..acbd9b3d9 100644 --- a/Essentials/src/com/earth2me/essentials/Teleport.java +++ b/Essentials/src/com/earth2me/essentials/Teleport.java @@ -1,8 +1,12 @@ package com.earth2me.essentials; -import com.earth2me.essentials.api.ITeleport; 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.commands.NotEnoughArgumentsException; +import com.earth2me.essentials.user.CooldownException; +import com.earth2me.essentials.user.UserData.TimestampType; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Logger; @@ -112,7 +116,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) @@ -139,30 +143,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.getGroups().getTeleportCooldown(user), !check, "essentials.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())); + } } @@ -190,7 +185,7 @@ public class Teleport implements Runnable, ITeleport { cancel(false); } - + public void teleport(Location loc, Trade chargeFor) throws Exception { teleport(new Target(loc), chargeFor, TeleportCause.PLUGIN); @@ -208,7 +203,7 @@ 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.getGroups().getTeleportDelay(user); if (chargeFor != null) { @@ -270,12 +265,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()), 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()), TeleportCause.COMMAND); + } + finally + { + user.unlock(); + } } public void home(IUser user, String home, Trade chargeFor) throws Exception diff --git a/Essentials/src/com/earth2me/essentials/Trade.java b/Essentials/src/com/earth2me/essentials/Trade.java index 6cd9ce93a..f92a1d504 100644 --- a/Essentials/src/com/earth2me/essentials/Trade.java +++ b/Essentials/src/com/earth2me/essentials/Trade.java @@ -1,8 +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.craftbukkit.InventoryWorkaround; import com.earth2me.essentials.craftbukkit.SetExpFix; -import static com.earth2me.essentials.I18n._; import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -12,6 +15,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.inventory.ItemStack; @@ -38,7 +42,7 @@ public class Trade { this(null, null, items, null, ess); } - + public Trade(final int exp, final IEssentials ess) { this(null, null, null, exp, ess); @@ -70,18 +74,23 @@ public class Trade throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (command != null && !command.isEmpty() && !user.isAuthorized("essentials.nocommandcost.all") && !user.isAuthorized("essentials.nocommandcost." + command) - && mon < ess.getSettings().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) - && 0 < ess.getSettings().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) + && mon < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) + && 0 < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) && !user.isAuthorized("essentials.eco.loan")) { throw new ChargeException(_("notEnoughMoney")); } - - if (exp != null && exp > 0 - && SetExpFix.getTotalExperience(user) < exp) { + + if (exp != null && exp > 0 + && SetExpFix.getTotalExperience(user) < exp) + { throw new ChargeException(_("notEnoughExperience")); } } @@ -145,8 +154,11 @@ public class Trade && !user.isAuthorized("essentials.nocommandcost.all") && !user.isAuthorized("essentials.nocommandcost." + command)) { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); final double mon = user.getMoney(); - final double cost = ess.getSettings().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); + final double cost = settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); if (mon < cost && cost > 0 && !user.isAuthorized("essentials.eco.loan")) { throw new ChargeException(_("notEnoughMoney")); @@ -173,7 +185,7 @@ public class Trade { return itemStack; } - + public Integer getExperience() { return exp; @@ -182,7 +194,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 (!ess.getSettings().isEcoLogEnabled()) + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getEconomy().isLogEnabled()) { return; } @@ -222,7 +237,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) { @@ -253,7 +268,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/User.java b/Essentials/src/com/earth2me/essentials/User.java deleted file mode 100644 index e23fe1de0..000000000 --- a/Essentials/src/com/earth2me/essentials/User.java +++ /dev/null @@ -1,554 +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.ChatColor; -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 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 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 (base instanceof OfflinePlayer) - { - return false; - } - - if (isOp()) - { - return true; - } - - if (isJailed()) - { - return false; - } - - return ess.getPermissionsHandler().hasPermission(base, node); - } - - 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.formatCurrency(value, ess))); - if (initiator != null) - { - initiator.sendMessage(_("addedToOthersAccount", Util.formatCurrency(value, ess), this.getDisplayName())); - } - } - - 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.formatCurrency(value, ess), reciever.getDisplayName())); - reciever.sendMessage(_("moneyRecievedFrom", Util.formatCurrency(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.formatCurrency(value, ess))); - if (initiator != null) - { - initiator.sendMessage(_("takenFromOthersAccount", Util.formatCurrency(value, ess), this.getDisplayName())); - } - } - - public boolean canAfford(final double cost) - { - final double mon = getMoney(); - return mon >= cost || isAuthorized("essentials.eco.loan"); - } - - 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.stripColor(this.getDisplayName()).compareToIgnoreCase(Util.stripColor(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 isTeleportRequestHere() - { - return teleportRequestHere; - } - - public String getNick(boolean addprefixsuffix) - { - final StringBuilder nickname = new StringBuilder(); - final String nick = getNickname(); - if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) - { - nickname.append(getName()); - } - else - { - nickname.append(ess.getSettings().getNicknamePrefix()).append(nick); - } - if (isOp()) - { - try - { - nickname.insert(0, ess.getSettings().getOperatorColor().toString()); - nickname.append("§f"); - } - catch (Exception e) - { - } - } - - if (addprefixsuffix && ess.getSettings().addPrefixSuffix()) - { - if (!ess.getSettings().disablePrefix()) - { - final String prefix = ess.getPermissionsHandler().getPrefix(base).replace('&', '§').replace("{WORLDNAME}", this.getWorld().getName()); - nickname.insert(0, prefix); - } - if (!ess.getSettings().disableSuffix()) - { - final String suffix = ess.getPermissionsHandler().getSuffix(base).replace('&', '§').replace("{WORLDNAME}", this.getWorld().getName()); - nickname.append(suffix); - if (suffix.length() < 2 || !suffix.substring(suffix.length() - 2, suffix.length() - 1).equals("§")) - { - nickname.append("§f"); - } - } - else - { - nickname.append("§f"); - } - } - - return nickname.toString(); - } - - 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) == '§' ? 15 : 16); - } - try - { - setPlayerListName(name); - } - catch (IllegalArgumentException e) - { - logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Use a shorter displayname prefix."); - } - } - - @Override - public String getDisplayName() - { - if (!(base instanceof OfflinePlayer) && ess.getSettings().changeDisplayName()) - { - setDisplayNick(); - } - return super.getDisplayName() == null ? super.getName() : super.getDisplayName(); - } - - 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); - } - - @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; - } - - //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()) - { - 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()) - { - 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(); - } - - public String getGroup() - { - return ess.getPermissionsHandler().getGroup(base); - } - - public boolean inGroup(final String group) - { - return ess.getPermissionsHandler().inGroup(base, group); - } - - public boolean canBuild() - { - return ess.getPermissionsHandler().canBuild(base, getGroup()); - } - - public long getTeleportRequestTime() - { - return teleportRequestTime; - } -} diff --git a/Essentials/src/com/earth2me/essentials/UserData.java b/Essentials/src/com/earth2me/essentials/UserData.java deleted file mode 100644 index e2a365ad2..000000000 --- a/Essentials/src/com/earth2me/essentials/UserData.java +++ /dev/null @@ -1,863 +0,0 @@ -package com.earth2me.essentials; - -import java.io.File; -import java.util.*; -import java.util.logging.Logger; -import org.bukkit.Location; -import org.bukkit.Material; -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; - private static final Logger logger = Logger.getLogger("Minecraft"); - - 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(); - savedInventory = _getSavedInventory(); - 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(); - } - 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() - { - Object o = config.getProperty("homes"); - - if (o instanceof Map) - { - return (Map<String, Object>)o; - } - else - { - 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(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 - { - //TODO: move this message to messages file - throw new Exception("Home " + name + " doesn't exist"); - } - } - - public boolean hasHome() - { - if (config.hasProperty("home")) - { - return true; - } - return false; - } - - public String getNickname() - { - return config.getString("nickname"); - } - - public void setNickname(String nick) - { - config.setProperty("nickname", nick); - config.save(); - } - private List<Integer> unlimited; - - private List<Integer> _getUnlimited() - { - return config.getIntList("unlimited", new ArrayList<Integer>()); - } - - 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<Integer, Object> powertools; - - @SuppressWarnings("unchecked") - private Map<Integer, Object> _getPowertools() - { - Object o = config.getProperty("powertools"); - - if (o instanceof Map) - { - return (Map<Integer, Object>)o; - } - else - { - return new HashMap<Integer, Object>(); - } - - } - - public void clearAllPowertools() - { - powertools.clear(); - config.setProperty("powertools", powertools); - config.save(); - } - - public List<String> getPowertool(ItemStack stack) - { - return (List<String>)powertools.get(stack.getTypeId()); - } - - 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", new ArrayList<String>()); - } - - 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 ItemStack[] savedInventory; - - public ItemStack[] getSavedInventory() - { - return savedInventory; - } - - private ItemStack[] _getSavedInventory() - { - int size = config.getInt("inventory.size", 0); - if (size < 1 || (getInventory() != null && size > getInventory().getSize())) - { - return null; - } - ItemStack[] is = new ItemStack[size]; - for (int i = 0; i < size; i++) - { - is[i] = config.getItemStack("inventory." + i); - } - return is; - } - - public void setSavedInventory(ItemStack[] is) - { - if (is == null || is.length == 0) - { - savedInventory = null; - config.removeProperty("inventory"); - } - else - { - savedInventory = is; - config.setProperty("inventory.size", is.length); - for (int i = 0; i < is.length; i++) - { - if (is[i] == null || is[i].getType() == Material.AIR) - { - continue; - } - config.setProperty("inventory." + i, is[i]); - } - } - config.save(); - } - 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", new ArrayList<String>()); - } - - 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", 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; - } - - public void setLastLogin(long time) - { - lastLogin = time; - config.setProperty("timestamps.login", time); - 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; - } - - public void setLastLoginAddress(String address) - { - lastLoginAddress = address; - config.setProperty("ipAddress", address); - config.save(); - } - 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() - { - final Object map = config.getProperty("timestamps.kits"); - - if (map instanceof Map) - { - return (Map<String, Object>)map; - } - else - { - 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 d15438c7d..000000000 --- a/Essentials/src/com/earth2me/essentials/UserMap.java +++ /dev/null @@ -1,123 +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(Util.sanitizeFileName(name)); - } - catch (ExecutionException ex) - { - return null; - } - catch (UncheckedExecutionException ex) - { - return null; - } - } - - @Override - public User load(final String name) throws Exception - { - for (Player player : ess.getServer().getOnlinePlayers()) - { - if (player.getName().equalsIgnoreCase(name)) - { - keys.add(Util.sanitizeFileName(name)); - return new User(player, ess); - } - } - final File userFile = getUserFile(name); - if (userFile.exists()) - { - keys.add(Util.sanitizeFileName(name)); - 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)); - } - - public Set<String> getAllUniqueUsers() - { - return Collections.unmodifiableSet(keys); - } - - public int getUniqueUsers() - { - return keys.size(); - } - - public File getUserFile(final String name) - { - final File userFolder = new File(ess.getDataFolder(), "userdata"); - return new File(userFolder, Util.sanitizeFileName(name) + ".yml"); - } -} diff --git a/Essentials/src/com/earth2me/essentials/Util.java b/Essentials/src/com/earth2me/essentials/Util.java index 386433326..6ca05c2a0 100644 --- a/Essentials/src/com/earth2me/essentials/Util.java +++ b/Essentials/src/com/earth2me/essentials/Util.java @@ -1,31 +1,91 @@ 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.InvalidNameException; +import com.earth2me.essentials.external.gnu.inet.encoding.Punycode; +import com.earth2me.essentials.external.gnu.inet.encoding.PunycodeException; 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 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 class Util +public final class Util { private Util() { } private final static Logger logger = Logger.getLogger("Minecraft"); - private final static Pattern INVALIDCHARS = Pattern.compile("[^a-z0-9]"); + private static Pattern unsafeChars = Pattern.compile("[^a-z0-9]"); + private static Pattern unsafeFileChars = Pattern.compile("[\u0000-\u001f]+"); - public static String sanitizeFileName(final String name) + public static String sanitizeFileName(String name) throws InvalidNameException { - return INVALIDCHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); + 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 = unsafeFileChars.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 unsafeChars.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); } public static String formatDateDiff(long date) @@ -419,7 +479,10 @@ public class Util public static String formatCurrency(final double value, final IEssentials ess) { - String str = ess.getSettings().getCurrencySymbol() + df.format(value); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + String str = settings.getData().getEconomy().getCurrencySymbol() + df.format(value); if (str.endsWith(".00")) { str = str.substring(0, str.length() - 3); @@ -478,6 +541,85 @@ public class Util } 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])"); diff --git a/Essentials/src/com/earth2me/essentials/Warps.java b/Essentials/src/com/earth2me/essentials/Warps.java index 57326b54a..97db07cbc 100644 --- a/Essentials/src/com/earth2me/essentials/Warps.java +++ b/Essentials/src/com/earth2me/essentials/Warps.java @@ -1,120 +1,116 @@ 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 Exception(_("warpNotExist")); + 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(); + } + 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 { - 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 index b597bd3e8..6b56850b1 100644 --- a/Essentials/src/com/earth2me/essentials/Worth.java +++ b/Essentials/src/com/earth2me/essentials/Worth.java @@ -1,61 +1,86 @@ package com.earth2me.essentials; +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.util.Locale; -import java.util.logging.Logger; +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 Worth implements IConf +public class Worth extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Worth> implements IWorth { - private static final Logger logger = Logger.getLogger("Minecraft"); - private final EssentialsConf config; - - public Worth(File dataFolder) + public Worth(final IEssentials ess) { - config = new EssentialsConf(new File(dataFolder, "worth.yml")); - config.setTemplateName("/worth.yml"); - config.load(); + super(ess, com.earth2me.essentials.settings.Worth.class); + onReload(false); } - public double getPrice(ItemStack itemStack) + @Override + public double getPrice(final 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)) + this.acquireReadLock(); + try { - result = config.getDouble("worth." + itemname, Double.NaN); + 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; } - if (Double.isNaN(result)) + finally { - result = config.getDouble("worth-" + itemStack.getTypeId(), Double.NaN); + this.unlock(); } - return result; } - public void setPrice(ItemStack itemStack, double price) + @Override + public void setPrice(final ItemStack itemStack, final 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); + acquireWriteLock(); + try { + if (getData().getSell() == null) { + getData().setSell(new HashMap<MaterialData, Double>()); + } + getData().getSell().put(itemStack.getData(), price); + } finally { + unlock(); } - config.removeProperty("worth-" + itemStack.getTypeId()); - config.save(); } @Override - public void reloadConfig() + public File getStorageFile() throws IOException { - config.load(); + return new File(ess.getDataFolder(), "worth.yml"); } } diff --git a/Essentials/src/com/earth2me/essentials/ChargeException.java b/Essentials/src/com/earth2me/essentials/api/ChargeException.java index 2fa4c7289..2fa4c7289 100644 --- a/Essentials/src/com/earth2me/essentials/ChargeException.java +++ b/Essentials/src/com/earth2me/essentials/api/ChargeException.java diff --git a/Essentials/src/com/earth2me/essentials/api/Economy.java b/Essentials/src/com/earth2me/essentials/api/Economy.java index 1d45c8df9..4e7b01fc4 100644 --- a/Essentials/src/com/earth2me/essentials/api/Economy.java +++ b/Essentials/src/com/earth2me/essentials/api/Economy.java @@ -1,13 +1,13 @@ 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 com.earth2me.essentials.craftbukkit.DummyOfflinePlayer; +import com.earth2me.essentials.user.User; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; +import lombok.Cleanup; +import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -39,40 +39,66 @@ public final class Economy { folder.mkdirs(); } - EssentialsConf npcConfig = new EssentialsConf(new File(folder, Util.sanitizeFileName(name) + ".yml")); + double startingBalance = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try { + startingBalance = settings.getData().getEconomy().getStartingBalance(); + } finally { + settings.unlock(); + } + IUser npc = new User(new DummyOfflinePlayer(name), ess); + npc.acquireWriteLock(); + try { + npc.getData().setNpc(true); + npc.setMoney(startingBalance); + } finally { + npc.unlock(); + } + + /*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(); + npcConfig.save();*/ } - private static void deleteNPC(String name) + private static void deleteNPC(final 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)); + IUser user = ess.getUser(name); + if (user != null) { + boolean npc = false; + user.acquireReadLock(); + try { + npc = user.getData().isNpc(); + } finally { + user.unlock(); + } + if (npc) { + try + { + ess.getUserMap().removeUser(name); + } + catch (InvalidNameException ex) + { + Bukkit.getLogger().log(Level.INFO, name, ex); + } } - ess.getUserMap().removeUser(name); } } - private static User getUserByName(String name) + private static IUser getUserByName(String name) { if (ess == null) { throw new RuntimeException(noCallBeforeLoad); } - User user; + IUser user; Player player = ess.getServer().getPlayer(name); if (player != null) { @@ -80,7 +106,7 @@ public final class Economy } else { - user = ess.getOfflineUser(name); + user = ess.getUser(name); } return user; } @@ -93,7 +119,7 @@ public final class Economy */ public static double getMoney(String name) throws UserDoesNotExistException { - User user = getUserByName(name); + IUser user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); @@ -110,7 +136,7 @@ public final class Economy */ public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException { - User user = getUserByName(name); + IUser user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); @@ -186,7 +212,15 @@ public final class Economy { throw new RuntimeException(noCallBeforeLoad); } - setMoney(name, ess.getSettings().getStartingBalance()); + double startingBalance = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try { + startingBalance = settings.getData().getEconomy().getStartingBalance(); + } finally { + settings.unlock(); + } + setMoney(name, startingBalance); } /** @@ -266,12 +300,14 @@ public final class Economy */ public static boolean isNPC(String name) throws UserDoesNotExistException { - User user = getUserByName(name); + @Cleanup + IUser user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } - return user.isNPC(); + user.acquireReadLock(); + return user.getData().isNpc(); } /** @@ -281,7 +317,7 @@ public final class Economy */ public static boolean createNPC(String name) { - User user = getUserByName(name); + IUser user = getUserByName(name); if (user == null) { createNPCFile(name); @@ -297,7 +333,7 @@ public final class Economy */ public static void removeNPC(String name) throws UserDoesNotExistException { - User user = getUserByName(name); + IUser user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(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/IEssentials.java b/Essentials/src/com/earth2me/essentials/api/IEssentials.java index c04bed0bd..9da294ca0 100644 --- a/Essentials/src/com/earth2me/essentials/api/IEssentials.java +++ b/Essentials/src/com/earth2me/essentials/api/IEssentials.java @@ -1,17 +1,20 @@ package com.earth2me.essentials.api; +import com.earth2me.essentials.listener.TNTExplodeListener; import com.earth2me.essentials.perm.IPermissionsHandler; import com.earth2me.essentials.register.payment.Methods; import org.bukkit.World; -import org.bukkit.command.CommandSender; +import org.bukkit.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 +22,11 @@ public interface IEssentials extends Plugin, IReload ISettings getSettings(); - IJails getJail(); + IGroups getGroups(); + + IJails getJails(); + + IKits getKits(); IWarps getWarps(); @@ -29,7 +36,9 @@ public interface IEssentials extends Plugin, IReload IUserMap getUserMap(); - IEssentialsEconomy getEconomy(); + IBackup getBackup(); + + ICommandHandler getCommandHandler(); World getWorld(String name); @@ -44,8 +53,8 @@ public interface IEssentials extends Plugin, IReload int scheduleSyncRepeatingTask(Runnable run, long delay, long period); IPermissionsHandler getPermissionsHandler(); + + void reload(); - IAlternativeCommandsHandler getAlternativeCommandsHandler(); - - void showCommandError(CommandSender sender, String commandLabel, Throwable exception); + TNTExplodeListener getTNTListener(); } 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..eea919f9d 100644 --- a/Essentials/src/com/earth2me/essentials/IEssentialsModule.java +++ b/Essentials/src/com/earth2me/essentials/api/IEssentialsModule.java @@ -1,5 +1,4 @@ -package com.earth2me.essentials; - +package com.earth2me.essentials.api; public interface IEssentialsModule { diff --git a/Essentials/src/com/earth2me/essentials/api/IGroups.java b/Essentials/src/com/earth2me/essentials/api/IGroups.java new file mode 100644 index 000000000..39a5f4182 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IGroups.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.api; + +import com.earth2me.essentials.settings.Groups; +import com.earth2me.essentials.storage.IStorageObjectHolder; + + +public interface IGroups extends IStorageObjectHolder<Groups> +{ + double getHealCooldown(IUser player); + + double getTeleportCooldown(IUser player); + + double getTeleportDelay(IUser player); + + String getPrefix(IUser player); + + String getSuffix(IUser player); + + int getHomeLimit(IUser player); + + String getChatFormat(IUser player); +} diff --git a/Essentials/src/com/earth2me/essentials/api/IItemDb.java b/Essentials/src/com/earth2me/essentials/api/IItemDb.java index ee4819215..5aa79f002 100644 --- a/Essentials/src/com/earth2me/essentials/api/IItemDb.java +++ b/Essentials/src/com/earth2me/essentials/api/IItemDb.java @@ -3,8 +3,10 @@ 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 18866d8e5..caa1ee0a8 100644 --- a/Essentials/src/com/earth2me/essentials/api/IJails.java +++ b/Essentials/src/com/earth2me/essentials/api/IJails.java @@ -12,7 +12,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..1cf6f89ed --- /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..bebf8380e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IPermission.java @@ -0,0 +1,14 @@ +package com.earth2me.essentials.api; + +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public interface IPermission +{ + String getPermission(); + + Permission getBukkitPermission(); + + PermissionDefault getPermissionDefault(); +} 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..c2a1deec5 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IReplyTo.java @@ -0,0 +1,9 @@ +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..bcb018355 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.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..ea7c8b930 100644 --- a/Essentials/src/com/earth2me/essentials/api/IUser.java +++ b/Essentials/src/com/earth2me/essentials/api/IUser.java @@ -1,43 +1,115 @@ package com.earth2me.essentials.api; -import com.earth2me.essentials.commands.IEssentialsCommand; +import com.earth2me.essentials.ChargeException; +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(); - boolean isAuthorized(String node); - boolean isAuthorized(IEssentialsCommand cmd); - - boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix); - - void setLastTeleportTimestamp(long time); - - Location getLastLocation(); + boolean isAuthorized(IPermission node); + //boolean isAuthorized(IEssentialsCommand cmd); + //boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix); Player getBase(); double getMoney(); void takeMoney(double value); + void takeMoney(double value, CommandSender initiator); + void giveMoney(double value); + void giveMoney(double value, CommandSender initiator); + + void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException; + + void giveItems(List<ItemStack> itemStacks, Boolean canSpew) throws ChargeException; + + void setMoney(double value); + + void payUser(final IUser reciever, final double value) throws Exception; + String getGroup(); + + boolean inGroup(String group); 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, String 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(); } diff --git a/Essentials/src/com/earth2me/essentials/api/IUserMap.java b/Essentials/src/com/earth2me/essentials/api/IUserMap.java index 9e609ab37..fd65b89d2 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); + + IUser getUser(final String playerName); - void removeUser(final String name); + 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..82669b52f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/IWarp.java @@ -0,0 +1,10 @@ +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..9f397ec20 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java @@ -0,0 +1,11 @@ +package com.earth2me.essentials.api; + + +public class InvalidNameException extends Exception +{ + + public InvalidNameException(Throwable thrwbl) + { + super(thrwbl); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java index a1c83606c..c5f02a990 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.perm.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 && user.isAuthorized(Permissions.AFK_OTHERS)) { - 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) { if (!user.toggleAfk()) { @@ -49,4 +46,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 54277d466..989275d56 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 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 { ess.broadcastMessage(user, "...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,"); ess.broadcastMessage(user, "who being naughty in My sight, shall snuff it."); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandback.java b/Essentials/src/com/earth2me/essentials/commands/Commandback.java index 67698598a..01a65ae64 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandback.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandback.java @@ -2,21 +2,15 @@ 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.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 { - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); charge.isAffordableFor(user); user.sendMessage(_("backUsageMsg")); user.getTeleport().back(charge); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java index 32c8c9e80..867135a93 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java @@ -1,26 +1,16 @@ 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) - { - throw new Exception(); - } + final IBackup backup = ess.getBackup(); backup.run(); sender.sendMessage(_("backupStarted")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java index 58f164ad6..73cadde0d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java @@ -1,37 +1,31 @@ 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; +import com.earth2me.essentials.perm.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) { throw new NotEnoughArgumentsException(); } - sender.sendMessage(_("balance", Util.formatCurrency(getPlayer(server, args, 0, true).getMoney(), ess))); + sender.sendMessage(_("balance", Util.formatCurrency(getPlayer(args, 0, true).getMoney(), ess))); } @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")) + || !user.isAuthorized(Permissions.BALANCE_OTHERS) ? user - : getPlayer(server, args, 0, true)).getMoney(); + : getPlayer(args, 0, true)).getMoney(); user.sendMessage(_("balance", Util.formatCurrency(bal, ess))); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java index 672f1c6ca..6c7237eb9 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.api.IUser; import com.earth2me.essentials.textreader.ArrayListInput; import com.earth2me.essentials.textreader.TextPager; import java.text.DateFormat; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.locks.ReentrantReadWriteLock; -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; @@ -109,7 +104,7 @@ public class Commandbalancetop extends EssentialsCommand final Map<String, Double> balances = new HashMap<String, Double>(); for (String u : ess.getUserMap().getAllUniqueUsers()) { - final User user = ess.getUserMap().getUser(u); + final IUser user = ess.getUserMap().getUser(u); if (user != null) { balances.put(user.getDisplayName(), user.getMoney()); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandban.java b/Essentials/src/com/earth2me/essentials/commands/Commandban.java index d39419686..4e0190b35 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandban.java @@ -2,32 +2,27 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.OfflinePlayer; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +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); - if (user.getBase() instanceof OfflinePlayer) + @Cleanup + final IUser user = getPlayer(args, 0, true); + if (user.isOnline()) { - if (sender instanceof Player - && !ess.getUser(sender).isAuthorized("essentials.ban.offline")) + if (user.isAuthorized("essentials.ban.exempt")) { sender.sendMessage(_("banExempt")); return; @@ -35,18 +30,21 @@ public class Commandban extends EssentialsCommand } else { - if (user.isAuthorized("essentials.ban.exempt")) + if (sender instanceof Player + && !ess.getUser((Player)sender).isAuthorized("essentials.ban.offline")) { 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 { @@ -58,7 +56,7 @@ public class Commandban extends EssentialsCommand for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); + final IUser player = ess.getUser(onlinePlayer); if (player.isAuthorized("essentials.ban.notify")) { 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 78d557934..3e9396519 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 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")) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java index 2691ad4f2..12b25a14a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java @@ -1,22 +1,16 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.event.block.BlockBreakEvent; public class Commandbreak extends EssentialsCommand { - public Commandbreak() - { - super("break"); - } - //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) 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..cd16aa1ee 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java @@ -1,23 +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 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")) { @@ -59,7 +53,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 ce891985e..92df03637 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java @@ -1,34 +1,31 @@ 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.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, 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(); } - User user = ess.getUser(sender); + @Cleanup + IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; String name; final String[] expandedArg = args[0].split(":"); if (expandedArg.length > 1 && (user == null || user.isAuthorized("essentials.delhome.others"))) { - user = getPlayer(server, expandedArg, 0, true); + user = getPlayer(expandedArg, 0, true); name = expandedArg[1]; } else if (user == null) @@ -41,11 +38,10 @@ public class Commanddelhome extends EssentialsCommand } //TODO: Think up a nice error message /* - * if (name.equalsIgnoreCase("bed")) { - * throw new Exception("You cannot remove the vanilla home point"); - * } + * 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 8f432ca6e..bf9ebaef6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java @@ -1,21 +1,17 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.User; +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 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) { @@ -37,7 +33,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: @@ -49,14 +45,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: @@ -68,7 +67,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..37d0fdd1d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java @@ -2,24 +2,21 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Enchantments; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; import com.earth2me.essentials.Util; -import java.util.*; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +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) @@ -78,7 +75,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); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java index 14bbf5e02..ddc6d775e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java @@ -1,12 +1,10 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Util; import java.util.HashMap; import java.util.Map; 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.entity.Player; @@ -14,61 +12,60 @@ 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 { - 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); @@ -95,61 +92,61 @@ 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) { - return; + loc.add(0, 1, 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()) + if (loc.getBlock().getTypeId() == 0) { - final Location loc = player.getLocation(); - loc.add(0, 3, 0); - while (loc.getBlockY() < player.getLocation().getBlockY() + 10 && loc.getBlock().getTypeId() != 0) + noteBlocks.put(player, loc.getBlock()); + loc.getBlock().setType(Material.NOTE_BLOCK); + } + } + taskid = ess.scheduleSyncRepeatingTask(new Runnable() + { + int i = 0; + + @Override + public void run() + { + 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) + final Block block = noteBlocks.get(onlinePlayer); + if (block == null || block.getType() != Material.NOTE_BLOCK) { - Commandessentials.this.stopTune(); - } - if (note.isEmpty()) - { - 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); - return; + } + }, 20, 2); + return; } 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..c815c6375 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java @@ -1,26 +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 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")) { - feedOtherPlayers(server,user,args[0]); + feedOtherPlayers(user, args[0]); } else { @@ -29,8 +23,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 62ace9357..dfab50ee6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java @@ -1,38 +1,32 @@ 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.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[0]); + 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().isEmpty() && user.isAuthorized("essentials.gamemode.others")) { - gamemodeOtherPlayers(server, user, args[0]); + gamemodeOtherPlayers(user, args[0]); return; } @@ -40,11 +34,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 name) + private void gamemodeOtherPlayers(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/Commandgc.java b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java index 9429bc5a8..8c7d2b485 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java @@ -1,20 +1,14 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import org.bukkit.Server; import org.bukkit.World; 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 { sender.sendMessage(_("gcmax", (Runtime.getRuntime().maxMemory() / 1024 / 1024))); sender.sendMessage(_("gctotal", (Runtime.getRuntime().totalMemory() / 1024 / 1024))); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java index c61702e59..3ce81b156 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java @@ -1,24 +1,18 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; 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")) { - final User otherUser = getPlayer(server, args, 0); + final IUser otherUser = getPlayer(args, 0); outputPosition(user, otherUser.getLocation(), user.getLocation()); } else @@ -26,18 +20,18 @@ public class Commandgetpos extends EssentialsCommand outputPosition(user, user.getLocation(), null); } } - + @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); } - + //TODO: Translate private void outputPosition(final CommandSender sender, final Location coords, final Location distance) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java index d6e3d8f98..446eff530 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java @@ -1,11 +1,9 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; 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; @@ -14,48 +12,31 @@ import org.bukkit.inventory.ItemStack; public class Commandgive extends EssentialsCommand { - public Commandgive() - { - super("give"); - } - //TODO: move these messages to message file @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())))) + && (!ess.getUser((Player)sender).isAuthorized("essentials.give.item-" + itemname) + && !ess.getUser((Player)sender).isAuthorized("essentials.give.item-" + stack.getTypeId()))) { throw new Exception(ChatColor.RED + "You are not allowed to spawn the item " + itemname); - } - - final User giveTo = getPlayer(server, args, 0); + } if (args.length > 2 && Integer.parseInt(args[2]) > 0) { stack.setAmount(Integer.parseInt(args[2])); - } - else if (ess.getSettings().getDefaultStackSize() > 0) - { - stack.setAmount(ess.getSettings().getDefaultStackSize()); - } - else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks")) - { - stack.setAmount(ess.getSettings().getOversizedStackSize()); - } + } if (args.length > 3) { @@ -66,7 +47,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) { @@ -84,17 +65,11 @@ public class Commandgive extends EssentialsCommand { throw new Exception(ChatColor.RED + "You can't give air."); } + + giveTo.giveItems(stack, false); 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 4d5bd424b..2530d8674 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java @@ -1,47 +1,41 @@ 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 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().isEmpty() && user.isAuthorized("essentials.god.others")) { - 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..3e4437aeb 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java @@ -1,55 +1,46 @@ 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.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 (!user.isAuthorized("essentials.heal.cooldown.bypass")) - { - user.healCooldown(); - } - healOtherPlayers(server, user, args[0]); + user.checkCooldown(TimestampType.LASTHEAL, ess.getGroups().getHealCooldown(user), true, "essentials.heal.cooldown.bypass"); + + healOtherPlayers(user, args[0]); return; } - if (!user.isAuthorized("essentials.heal.cooldown.bypass")) - { - user.healCooldown(); - } + user.checkCooldown(TimestampType.LASTHEAL, ess.getGroups().getHealCooldown(user), true, "essentials.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 769aac483..48c679736 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.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.textreader.*; -import org.bukkit.Server; 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; @@ -45,7 +39,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 20cd5cdd3..1622570a4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.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.api.IUser; import com.earth2me.essentials.Util; 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,7 +21,7 @@ public class Commandhelpop extends EssentialsCommand logger.log(Level.INFO, message); for (Player onlinePlayer : server.getOnlinePlayers()) { - final User player = ess.getUser(onlinePlayer); + final IUser player = ess.getUser(onlinePlayer); if (!player.isAuthorized("essentials.helpop.receive")) { continue; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java index 55bd75d0c..6fe74335c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java @@ -2,28 +2,22 @@ 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.api.IUser; import java.util.List; import java.util.Locale; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandhome extends EssentialsCommand { - 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) @@ -35,7 +29,7 @@ public class Commandhome extends EssentialsCommand } 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..d694c9fa4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java @@ -4,19 +4,13 @@ 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 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 1f5c32faa..4b772e0ec 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java @@ -1,43 +1,38 @@ 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 && user.getSavedInventory() == null) + if (args.length < 1 && user.getData().getInventory() == null) { throw new NotEnoughArgumentsException(); } - User invUser = user; + IUser invUser = user; if (args.length == 1) { - invUser = getPlayer(server, args, 0); + invUser = getPlayer(args, 0); } - if (invUser == user && user.getSavedInventory() != null) + user.acquireWriteLock(); + if (invUser == user && user.getData().getInventory() != null) { - invUser.getInventory().setContents(user.getSavedInventory()); - user.setSavedInventory(null); + invUser.getInventory().setContents(user.getData().getInventory().getBukkitInventory()); + user.getData().setInventory(null); user.sendMessage(_("invRestored")); throw new NoChargeException(); } - - if (user.getSavedInventory() == null) + if (user.getData().getInventory() == null) { - user.setSavedInventory(user.getInventory().getContents()); + user.getData().setInventory(new Inventory(user.getInventory().getContents())); } ItemStack[] invUserStack = invUser.getInventory().getContents(); final int userStackLength = user.getInventory().getContents().length; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java index 405b8b799..9483f2661 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java @@ -1,38 +1,27 @@ 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 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 (!user.isAuthorized("essentials.itemspawn.item-" + itemname) + && !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) { throw new Exception(_("cantSpawnItem", itemname)); } @@ -41,15 +30,7 @@ public class Commanditem extends EssentialsCommand { stack.setAmount(Integer.parseInt(args[1])); } - else if (ess.getSettings().getDefaultStackSize() > 0) - { - stack.setAmount(ess.getSettings().getDefaultStackSize()); - } - else if (ess.getSettings().getOversizedStackSize() > 0 && user.isAuthorized("essentials.oversizedstacks")) - { - stack.setAmount(ess.getSettings().getOversizedStackSize()); - } - + if (args.length > 2) { for (int i = 2; i < args.length; i++) @@ -78,16 +59,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..f7865e78b 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 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 39ca305e3..ff0c80d51 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java @@ -2,22 +2,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.api.IUser; 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(); @@ -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); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java index ae5db48fb..ada0c1296 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java @@ -2,28 +2,22 @@ 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 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); + final IUser user = getPlayer(args, 0); if (user.isAuthorized("essentials.kick.exempt")) { throw new Exception(_("kickExempt")); @@ -34,7 +28,7 @@ public class Commandkick extends EssentialsCommand for (Player onlinePlayer : server.getOnlinePlayers()) { - User player = ess.getUser(onlinePlayer); + final IUser player = ess.getUser(onlinePlayer); if (player.isAuthorized("essentials.kick.notify")) { 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 6d97b6af9..e460f5cbd 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 e56f9d67b..6b79a757b 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 b9679e8b9..7d952a8bb 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java @@ -1,39 +1,21 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.Mob; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.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.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 c003d28ac..a21e4b38d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java @@ -1,53 +1,56 @@ 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.Trade; +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.settings.Kit; +import java.util.Collection; +import java.util.Locale; 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) { - final String kitList = Kit.listKits(ess, user); - if (kitList.length() > 0) + Collection<String> kitList = ess.getKits().getList(); + if (kitList.isEmpty()) { - user.sendMessage(_("kits", kitList)); + user.sendMessage(_("noKits")); } else { - user.sendMessage(_("noKits")); + for (String kitName : kitList) + { + if (!user.isAuthorized("essentials.kit." + kitName)) + { + kitList.remove(kitName); + } + } + user.sendMessage(_("kits", Util.joinList(kitList))); } throw new NoChargeException(); } else { final String kitName = args[0].toLowerCase(Locale.ENGLISH); - final Object kit = ess.getSettings().getKit(kitName); + final Kit kit = ess.getKits().getKit(kitName); if (!user.isAuthorized("essentials.kit." + kitName)) { throw new Exception(_("noKitPermission", "essentials.kit." + kitName)); } - final Map<String, Object> els = (Map<String, Object>)kit; - final List<String> items = Kit.getItems(user, els); - Kit.checkTime(user, kitName, els); + //TODO: Check kit delay final Trade charge = new Trade("kit-" + kitName, ess); charge.isAffordableFor(user); - Kit.expandItems(ess, user, items); - + ess.getKits().sendKit(user, kit); + charge.charge(user); user.sendMessage(_("kitGive", kitName)); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java index be9ac61f5..0973b2137 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java @@ -1,8 +1,9 @@ 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.LightningStrike; import org.bukkit.entity.Player; @@ -10,16 +11,11 @@ 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)); @@ -63,7 +59,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 92833a66c..26a070ec2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java @@ -1,27 +1,22 @@ 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 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")) + if (ess.getUser((Player)sender).isAuthorized("essentials.list.hidden")) { showhidden = true; } @@ -43,26 +38,40 @@ public class Commandlist extends EssentialsCommand if (showhidden && playerHidden > 0) { online = _("listAmountHidden", server.getOnlinePlayers().length - playerHidden, playerHidden, server.getMaxPlayers()); - } else { - online = _("listAmount",server.getOnlinePlayers().length - playerHidden, server.getMaxPlayers()); + } + else + { + online = _("listAmount", server.getOnlinePlayers().length - playerHidden, server.getMaxPlayers()); } 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); + List<IUser> list = sort.get(group); if (list == null) { - list = new ArrayList<User>(); + list = new ArrayList<IUser>(); sort.put(group, list); } list.add(player); @@ -73,10 +82,10 @@ public class Commandlist extends EssentialsCommand { final StringBuilder groupString = new StringBuilder(); groupString.append(group).append(": "); - final List<User> users = sort.get(group); + final List<IUser> users = sort.get(group); Collections.sort(users); boolean first = true; - for (User user : users) + for (IUser user : users) { if (!first) { @@ -86,9 +95,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()) { @@ -102,10 +119,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; @@ -117,7 +134,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) { @@ -127,9 +144,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 4a9928b85..abd46b545 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java @@ -1,30 +1,23 @@ 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.Util; import java.util.List; -import org.bukkit.ChatColor; -import org.bukkit.Server; import org.bukkit.command.CommandSender; 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(); @@ -40,24 +33,24 @@ public class Commandmail extends EssentialsCommand { if (!user.isAuthorized("essentials.mail.send")) { - throw new Exception(_("noPerm","essentials.mail.send")); + 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())) { u.addMail(user.getName() + ": " + Util.stripColor(getFinalArg(args, 2))); } @@ -68,7 +61,7 @@ public class Commandmail extends EssentialsCommand { if (!user.isAuthorized("essentials.mail.sendall")) { - throw new Exception(_("noPerm","essentials.mail.sendall")); + throw new Exception(_("noPerm", "essentials.mail.sendall")); } ess.scheduleAsyncDelayedTask(new SendAll(user.getName() + ": " + Util.stripColor(getFinalArg(args, 1)))); user.sendMessage(_("mailSent")); @@ -76,7 +69,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 +78,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 +116,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 +151,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 1530f3ad7..e657b833d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandme.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandme.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.api.IUser; import com.earth2me.essentials.Util; -import org.bukkit.Server; 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")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java index 3fce3110c..d28d8e0fe 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java @@ -1,49 +1,54 @@ 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 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() >= ((user.isAuthorized("essentials.oversizedstacks")) + ? 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 (!user.isAuthorized("essentials.itemspawn.item-" + itemname) + && !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) { throw new Exception(_("cantSpawnItem", itemname)); } if (user.isAuthorized("essentials.oversizedstacks")) { - 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..3531d0708 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java @@ -4,19 +4,13 @@ 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 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 128d8eeb5..4c0b0a76c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java @@ -2,24 +2,19 @@ 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.api.IReplyTo; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.Util; 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,8 +24,10 @@ 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")); } @@ -56,7 +53,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); @@ -73,7 +70,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++; @@ -87,8 +84,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..59d401f96 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java @@ -1,29 +1,27 @@ 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; +import com.earth2me.essentials.user.UserData.TimestampType; +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() && player.isAuthorized("essentials.mute.exempt")) { throw new Exception(_("muteExempt")); } @@ -33,7 +31,7 @@ public class Commandmute extends EssentialsCommand String time = getFinalArg(args, 1); muteTimestamp = Util.parseDateDiff(time, true); } - player.setMuteTimeout(muteTimestamp); + player.setTimestamp(TimestampType.MUTE, muteTimestamp); final boolean muted = player.toggleMuted(); sender.sendMessage( muted diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java index 0afcf1650..368dd90a3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java @@ -1,9 +1,8 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -11,22 +10,17 @@ 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 { - otherUser = getPlayer(server, args, 0); + otherUser = getPlayer(args, 0); } catch (Exception ex) { @@ -51,22 +45,22 @@ public class Commandnear extends EssentialsCommand } if (otherUser == null || user.isAuthorized("essentials.near.others")) { - user.sendMessage(_("nearbyPlayers", getLocal(server, otherUser == null ? user : otherUser, radius))); + user.sendMessage(_("nearbyPlayers", getLocal(otherUser == null ? user : otherUser, radius))); } else { user.sendMessage(_("noAccessCommand")); } } - + @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { - - User otherUser = null; + + IUser otherUser = null; if (args.length > 0) { - otherUser = getPlayer(server, args, 0); + otherUser = getPlayer(args, 0); } else { @@ -83,19 +77,19 @@ 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(); final StringBuilder output = new StringBuilder(); final long radiusSquared = radius * radius; - + 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(); @@ -103,7 +97,7 @@ public class Commandnear extends EssentialsCommand { continue; } - + final long delta = (long)playerLoc.distanceSquared(loc); if (delta < radiusSquared) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java index b9fbccb37..add0a2129 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java @@ -1,9 +1,11 @@ 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.Util; import java.util.Locale; +import lombok.Cleanup; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -11,19 +13,17 @@ 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")); } @@ -33,21 +33,24 @@ public class Commandnick extends EssentialsCommand { 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,12 +60,12 @@ 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 || user.isAuthorized("essentials.nick.color")) { @@ -78,7 +81,7 @@ public class Commandnick extends EssentialsCommand { try { - setNickname(server, ess.getUser(player), "off"); + setNickname(ess.getUser(player), "off"); } catch (Exception ex) { @@ -86,7 +89,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]+$")) { @@ -94,8 +97,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 @@ -115,8 +118,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 df497a352..20bdc140a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java @@ -4,7 +4,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; @@ -13,13 +12,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) @@ -28,7 +22,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++; } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java index 01e1fcffb..837360f18 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java @@ -2,26 +2,20 @@ 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.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 1fad701b2..e87542acd 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandping.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandping.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; public class Commandping extends EssentialsCommand { - public Commandping() - { - super("ping"); - } - @Override - public void run(Server server, User player, String commandLabel, String[] args) throws Exception + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { - player.sendMessage(_("pong")); + user.sendMessage(_("pong")); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java index ca03364b2..78e338722 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java @@ -1,32 +1,27 @@ 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 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 +33,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:")) @@ -110,6 +105,7 @@ public class Commandpowertool extends EssentialsCommand user.sendMessage(_("powerToolRemoveAll", itemName)); } - 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 b16cbdc34..62a6fa298 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandptime.java @@ -2,9 +2,8 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.DescParseTickFormat; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; import java.util.*; -import org.bukkit.Server; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -22,13 +21,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 +30,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,7 +39,7 @@ public class Commandptime extends EssentialsCommand return; } - User user = ess.getUser(sender); + IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; if ((!users.contains(user) || users.size() > 1) && user != null && !user.isAuthorized("essentials.ptime.others")) { user.sendMessage(_("pTimeOthersPermission")); @@ -89,14 +83,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 +114,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 +128,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 +143,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 +175,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 +197,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 +225,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 7ef012d0d..3b20eb5de 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandr.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandr.java @@ -2,23 +2,17 @@ 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.api.IReplyTo; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.Util; -import org.bukkit.Server; 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,7 +25,7 @@ public class Commandr extends EssentialsCommand if (sender instanceof Player) { - User user = ess.getUser(sender); + IUser user = ess.getUser((Player)sender); if (user.isAuthorized("essentials.msg.color")) { message = Util.replaceColor(message); @@ -61,8 +55,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; } @@ -81,4 +75,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 b48ac5bcb..303ec8294 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java @@ -1,39 +1,38 @@ 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.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; } final String displayName = Util.stripColor(u.getDisplayName()).toLowerCase(Locale.ENGLISH); + settings.acquireReadLock(); if (!whois.equals(displayName) - && !displayName.equals(Util.stripColor(ess.getSettings().getNicknamePrefix()) + whois) + && !displayName.equals(Util.stripColor(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 d245d1239..66cdf625d 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) { @@ -92,8 +85,9 @@ public class Commandremove extends EssentialsCommand protected void removeEntities(final CommandSender sender, final World world, final ToRemove toRemove, int radius) throws Exception { int removed = 0; - if (radius > 0) { - radius*=radius; + if (radius > 0) + { + radius *= radius; } for (Chunk chunk : world.getLoadedChunks()) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java index cf9e43f9f..6ad0d729c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java @@ -1,24 +1,21 @@ package com.earth2me.essentials.commands; +import com.earth2me.essentials.ChargeException; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.*; +import com.earth2me.essentials.Trade; +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IUser; 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,7 +31,6 @@ public class Commandrepair extends EssentialsCommand } if (!item.getEnchantments().isEmpty() - && !ess.getSettings().getRepairEnchanted() && !user.isAuthorized("essentials.repair.enchanted")) { throw new Exception(_("repairEnchanted")); @@ -113,7 +109,6 @@ public class Commandrepair extends EssentialsCommand continue; } if (!item.getEnchantments().isEmpty() - && !ess.getSettings().getRepairEnchanted() && !user.isAuthorized("essentials.repair.enchanted")) { continue; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java index d87c4f41b..5445b9bc6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java @@ -4,19 +4,13 @@ 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 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 cf500e094..6b987c628 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandseen.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.api.IUser; +import com.earth2me.essentials.user.UserData.TimestampType; 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 { if (args.length < 1) { @@ -23,17 +18,17 @@ public class Commandseen extends EssentialsCommand } try { - User u = getPlayer(server, args, 0); - sender.sendMessage(_("seenOnline", u.getDisplayName(), Util.formatDateDiff(u.getLastLogin()))); + IUser u = getPlayer(args, 0); + sender.sendMessage(_("seenOnline", u.getDisplayName(), Util.formatDateDiff(u.getTimestamp(TimestampType.LOGIN)))); } catch (NoSuchFieldException e) { - User u = ess.getOfflineUser(args[0]); + IUser u = ess.getUser(args[0]); if (u == null) { throw new Exception(_("playerNotFound")); } - sender.sendMessage(_("seenOffline", u.getDisplayName(), Util.formatDateDiff(u.getLastLogout()))); + sender.sendMessage(_("seenOffline", u.getDisplayName(), Util.formatDateDiff(u.getTimestamp(TimestampType.LOGOUT)))); if (u.isBanned()) { sender.sendMessage(_("whoisBanned", _("true"))); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java index d59c09b1e..20923dcdd 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.craftbukkit.InventoryWorkaround; import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.craftbukkit.InventoryWorkaround; 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 e7687fcfd..c92c24dab 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 java.util.HashMap; import java.util.Locale; -import org.bukkit.Server; +import lombok.Cleanup; +import org.bukkit.Location; 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) { @@ -29,14 +26,19 @@ public class Commandsethome extends EssentialsCommand { if (user.isAuthorized("essentials.sethome.multiple")) { - if ((user.isAuthorized("essentials.sethome.multiple.unlimited")) || (user.getHomes().size() < ess.getSettings().getHomeLimit(user)) + if ((user.isAuthorized("essentials.sethome.multiple.unlimited")) || (user.getHomes().size() < ess.getGroups().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, Location>()); + } + user.getData().getHomes().put(args[0].toLowerCase(Locale.ENGLISH), user.getLocation()); } else { - throw new Exception(_("maxHomes", ess.getSettings().getHomeLimit(user))); + throw new Exception(_("maxHomes", ess.getGroups().getHomeLimit(user))); } } @@ -49,11 +51,8 @@ public class Commandsethome extends EssentialsCommand { if (user.isAuthorized("essentials.sethome.others")) { - 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")); @@ -63,13 +62,24 @@ public class Commandsethome extends EssentialsCommand { name = "home"; } - usersHome.setHome(name, user.getLocation()); + + usersHome.acquireWriteLock(); + if (usersHome.getData().getHomes() == null) + { + usersHome.getData().setHomes(new HashMap<String, Location>()); + } + usersHome.getData().getHomes().put(name, user.getLocation()); } } } else { - user.setHome(); + user.acquireWriteLock(); + if (user.getData().getHomes() == null) + { + user.getData().setHomes(new HashMap<String, Location>()); + } + user.getData().getHomes().put("home", user.getLocation()); } user.sendMessage(_("homeSet")); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java index 8ed298303..2fcad7bd2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.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 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/Commandsetwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java index 1a7d27b4b..5a0599789 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java @@ -1,32 +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.api.IWarps; 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(); - ess.getWarps().setWarp(args[0], loc); + final IWarps warps = ess.getWarps(); + Location warpLoc = null; + + try + { + warpLoc = warps.getWarp(args[0]); + } + catch (WarpNotFoundException ex) + { + } + + if (warpLoc == null || user.hasPermission("essentials.warp.overwrite." + args[0])) + { + warps.setWarp(args[0], loc); + } + else + { + 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 1d236b70a..3e0b3f52c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.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.inventory.ItemStack; public class Commandsetworth extends EssentialsCommand { - public Commandsetworth() - { - super("setworth"); - } - @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 < 2) { 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/Commandspawner.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java index 73c86eba4..23e3b9a7e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java @@ -2,24 +2,17 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.Mob; -import com.earth2me.essentials.User; import com.earth2me.essentials.Util; -import java.util.Locale; +import com.earth2me.essentials.api.IUser; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.block.CreatureSpawner; 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) { @@ -43,10 +36,6 @@ public class Commandspawner extends EssentialsCommand user.sendMessage(_("invalidMob")); return; } - if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) - { - throw new Exception(_("unableToSpawnMob")); - } if (!user.isAuthorized("essentials.spawner." + mob.name.toLowerCase())) { throw new Exception(_("unableToSpawnMob")); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java index f867a1503..9649a50e4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java @@ -3,26 +3,21 @@ 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.api.ISettings; +import com.earth2me.essentials.api.IUser; import java.util.Locale; import java.util.Random; import org.bukkit.DyeColor; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.entity.*; 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) { @@ -62,10 +57,6 @@ 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())) { throw new Exception(_("noPermToSpawnMob")); @@ -76,10 +67,10 @@ public class Commandspawnmob extends EssentialsCommand { 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); @@ -101,10 +92,6 @@ 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())) { throw new Exception(_("noPermToSpawnMob")); @@ -130,7 +117,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; @@ -184,7 +181,7 @@ public class Commandspawnmob extends EssentialsCommand } } - private void changeMobData(final CreatureType type, final Entity spawned, final String data, final User user) throws Exception + private void changeMobData(final CreatureType type, final Entity spawned, final String data, final IUser user) throws Exception { if (type == CreatureType.SLIME || type == CreatureType.MAGMA_CUBE) { @@ -238,7 +235,7 @@ public class Commandspawnmob extends EssentialsCommand { final Wolf wolf = ((Wolf)spawned); wolf.setTamed(true); - wolf.setOwner(user); + wolf.setOwner(user.getBase()); wolf.setSitting(true); if (data.equalsIgnoreCase("tamedbaby")) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java index 7f758ad2e..d93bbc466 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java @@ -1,27 +1,21 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; 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) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java index aa2ed5567..2e89faf85 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.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 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 { user.setHealth(0); user.sendMessage(_("suicideMessage")); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java index 144d19d15..fb631be20 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java @@ -2,33 +2,28 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.OfflinePlayer; -import com.earth2me.essentials.User; import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.user.Ban; +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.getBase() instanceof OfflinePlayer) { if (sender instanceof Player - && !ess.getUser(sender).isAuthorized("essentials.tempban.offline")) + && !ess.getUser((Player)sender).isAuthorized("essentials.tempban.offline")) { sender.sendMessage(_("tempbanExempt")); return; @@ -46,15 +41,17 @@ public class Commandtempban extends EssentialsCommand final long banTimestamp = Util.parseDateDiff(time, true); final String banReason = _("tempBanned", Util.formatDateDiff(banTimestamp)); - user.setBanReason(banReason); - user.setBanTimeout(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); + final IUser player = ess.getUser(onlinePlayer); if (player.isAuthorized("essentials.ban.notify")) { 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 c49f34fbd..991eea80d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java @@ -2,22 +2,17 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.DescParseTickFormat; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; 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 { // Which World(s) are we interested in? String worldSelector = null; @@ -25,7 +20,7 @@ public class Commandtime extends EssentialsCommand { worldSelector = args[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 (args.length == 0) @@ -34,7 +29,7 @@ public class Commandtime extends EssentialsCommand return; } - final User user = ess.getUser(sender); + final IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; if (user != null && !user.isAuthorized("essentials.time.set")) { user.sendMessage(_("timeSetPermission")); @@ -103,14 +98,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 f98343311..4406d5958 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java @@ -1,37 +1,35 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.OfflinePlayer; -import com.earth2me.essentials.User; import com.earth2me.essentials.Util; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.user.UserData.TimestampType; +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.getBase() instanceof OfflinePlayer) { if (sender instanceof Player - && !ess.getUser(sender).isAuthorized("essentials.togglejail.offline")) + && !ess.getUser((Player)sender).isAuthorized("essentials.togglejail.offline")) { sender.sendMessage(_("mayNotJail")); return; @@ -54,16 +52,16 @@ 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); + player.setTimestamp(TimestampType.JAIL, timeDiff); } sender.sendMessage((timeDiff > 0 ? _("playerJailedFor", player.getName(), Util.formatDateDiff(timeDiff)) @@ -71,31 +69,33 @@ public class Commandtogglejail extends EssentialsCommand 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); + player.acquireWriteLock(); + player.setTimestamp(TimestampType.JAIL, timeDiff); sender.sendMessage(_("jailSentenceExtended", Util.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.getBase() instanceof OfflinePlayer)) { 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..01fa24c1d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java @@ -2,26 +2,20 @@ 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.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 7ea3f0541..85c72605a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java @@ -3,21 +3,16 @@ 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.api.IUser; +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,13 +20,15 @@ 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())); } 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(); @@ -43,8 +40,8 @@ public class Commandtp extends EssentialsCommand throw new Exception("You need access to /tpohere to teleport other players."); } 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); target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); break; @@ -52,7 +49,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) { @@ -60,8 +57,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 34195d51a..6790883c6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java @@ -1,39 +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; 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())); } - if (!player.isIgnoredPlayer(user.getName())) + if (!player.isIgnoringPlayer(user.getName())) { player.requestTeleport(user, false); 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 c0abdc1ad..ad3bb0aa5 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; } @@ -50,14 +48,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 0cece3310..b32158069 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java @@ -1,40 +1,49 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.OfflinePlayer; import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +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.getBase() instanceof OfflinePlayer + final IUser target = user.getTeleportRequester(); + if (target.getBase() instanceof OfflinePlayer || (user.isTeleportRequestHere() && !target.isAuthorized("essentials.tpahere"))) { 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.isTeleportRequestHere()) { charge.isAffordableFor(user); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java index 376c2be44..b28898cd6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java @@ -1,36 +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; 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())); } 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 f21f1a6bc..ee1cd230f 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; @@ -48,7 +42,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 733091d1a..b2cb09ca2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java @@ -2,27 +2,24 @@ 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.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())); } - player.getTeleport().teleport(user, new Trade(this.getName(), ess), TeleportCause.COMMAND); + player.getTeleport().teleport(user, new Trade(commandName, ess), TeleportCause.COMMAND); user.sendMessage(_("teleporting")); player.sendMessage(_("teleporting")); throw new NoChargeException(); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java index 7c13b80d4..c7b5312c8 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java @@ -1,21 +1,15 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.OfflinePlayer; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import org.bukkit.OfflinePlayer; 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 { if (args.length < 1) { @@ -23,7 +17,7 @@ public class Commandtpo extends EssentialsCommand } //Just basically the old tp command - final User player = getPlayer(server, args, 0, true); + final IUser player = getPlayer(args, 0, true); // Check if user is offline if (player.getBase() instanceof OfflinePlayer) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java index e226f0702..bfd52562d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java @@ -1,21 +1,15 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.OfflinePlayer; -import com.earth2me.essentials.User; -import org.bukkit.Server; +import com.earth2me.essentials.api.IUser; +import org.bukkit.OfflinePlayer; 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) { @@ -23,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.getBase() instanceof OfflinePlayer) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java index 226fa44e3..c2fd75707 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java @@ -2,21 +2,15 @@ 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.api.IUser; import org.bukkit.Location; -import org.bukkit.Server; 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) { @@ -35,7 +29,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 20cc9d46f..d3fd4df67 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 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) diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java index 8bc3ad068..a18856d66 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..ebfad6ee8 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java @@ -1,35 +1,32 @@ 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 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")) { - target = getPlayer(server, args, 1); + target = getPlayer(args, 1); + target.acquireReadLock(); } if (args[0].equalsIgnoreCase("list")) @@ -39,16 +36,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 +50,45 @@ 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 (!user.isAuthorized("essentials.unlimited.item-" + itemname) + && !user.isAuthorized("essentials.unlimited.item-" + stack.getTypeId())) { 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 +103,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 51b64563b..06a203f85 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java @@ -2,13 +2,12 @@ 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.api.IUser; +import com.earth2me.essentials.api.IWarps; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; @@ -17,13 +16,8 @@ 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]+")) { @@ -36,7 +30,7 @@ public class Commandwarp extends EssentialsCommand } if (args.length > 0) { - User otherUser = null; + IUser otherUser = null; if (args.length == 2 && user.isAuthorized("essentials.warp.otherplayers")) { otherUser = ess.getUser(server.getPlayer(args[1])); @@ -53,14 +47,14 @@ public class Commandwarp 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 || 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")); @@ -73,20 +67,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 (!((IUser)sender).isAuthorized("essentials.warp." + warpName)) { iterator.remove(); } @@ -112,19 +106,16 @@ public class Commandwarp extends EssentialsCommand } } - private void warpUser(final User user, final String name) throws Exception + private void warpUser(final IUser user, final String name) throws Exception { - final Trade charge = new Trade(this.getName(), ess); + final Trade charge = new Trade(commandName, ess); charge.isAffordableFor(user); - if (ess.getSettings().getPerWarpPermission()) + + if (user.isAuthorized("essentials.warp." + name)) { - if (user.isAuthorized("essentials.warp." + name)) - { - user.getTeleport().warp(name, charge, TeleportCause.COMMAND); - return; - } - 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 7e211455e..1632722bc 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java @@ -1,23 +1,19 @@ 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.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 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) { @@ -26,7 +22,7 @@ public class Commandwhois extends EssentialsCommand boolean showhidden = false; if (sender instanceof Player) { - if (ess.getUser(sender).isAuthorized("essentials.list.hidden")) + if (ess.getUser((Player)sender).isAuthorized("essentials.list.hidden")) { showhidden = true; } @@ -36,15 +32,21 @@ public class Commandwhois extends EssentialsCommand showhidden = true; } final String whois = args[0].toLowerCase(Locale.ENGLISH); - final int prefixLength = Util.stripColor(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.stripColor(user.getNickname()); + user.acquireReadLock(); + final String nickName = Util.stripColor(user.getData().getNickname()); if (!whois.equalsIgnoreCase(nickName) && !whois.substring(prefixLength).equalsIgnoreCase(nickName) && !whois.equalsIgnoreCase(user.getName())) @@ -58,17 +60,14 @@ 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.formatCurrency(user.getMoney(), ess))); - } - sender.sendMessage(user.isAfk() + sender.sendMessage(_("whoisMoney", Util.formatCurrency(user.getMoney(), ess))); + 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)) + && (sender instanceof Player ? ess.getUser((Player)sender).isAuthorized("essentials.geoip.show") : true)) { 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 41554c8ce..920900a57 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java @@ -2,23 +2,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.api.IUser; 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,13 +48,11 @@ public class Commandworld extends EssentialsCommand } } - if (ess.getSettings().getIsWorldTeleportPermissions()) + + if (!user.isAuthorized("essentials.world." + world.getName())) { - if (!user.isAuthorized("essentials.world." + world.getName())) - { - user.sendMessage(_("invalidWorld")); //TODO: Make a "world teleport denied" translation - throw new NoChargeException(); - } + user.sendMessage(_("invalidWorld")); //TODO: Make a "world teleport denied" translation + throw new NoChargeException(); } double factor; @@ -80,7 +72,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 586b31873..57955b6ba 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.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 13328e1b5..a70471327 100644 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java @@ -1,55 +1,50 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.IEssentialsModule; -import com.earth2me.essentials.OfflinePlayer; import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IEssentialsModule; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.perm.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 transient Server server; protected final static Logger logger = Logger.getLogger("Minecraft"); + 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.server = ess.getServer(); + this.commandName = commandName; + this.permission = "essentials." + commandName; } - + @Override public void setEssentialsModule(final IEssentialsModule module) { this.module = module; } - @Override - public String getName() + protected IUser getPlayer(final String[] args, final int pos) throws NoSuchFieldException, NotEnoughArgumentsException { - return name; + return getPlayer(args, pos, false); } - protected User getPlayer(final Server server, final String[] args, final int pos) throws NoSuchFieldException, NotEnoughArgumentsException - { - return getPlayer(server, 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) { @@ -59,10 +54,10 @@ 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.getBase() instanceof OfflinePlayer || user.isHidden())) + if (!getOffline && (!user.isOnline() || user.isHidden())) { throw new NoSuchFieldException(_("playerNotFound")); } @@ -74,13 +69,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; @@ -90,28 +85,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) @@ -127,4 +122,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/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 new file mode 100644 index 000000000..6caea6dd2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java @@ -0,0 +1,17 @@ +package com.earth2me.essentials.commands; + + +public class WarpNotFoundException extends Exception +{ + public WarpNotFoundException() + { + super(""); + } + + public WarpNotFoundException(String message) + { + super(message); + } +} + + diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/BetterLocation.java b/Essentials/src/com/earth2me/essentials/craftbukkit/BetterLocation.java new file mode 100644 index 000000000..e57a7ddde --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/BetterLocation.java @@ -0,0 +1,254 @@ +package com.earth2me.essentials.craftbukkit; + +import java.lang.ref.WeakReference; +import java.util.*; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; + + +public class BetterLocation extends Location +{ + private transient String worldName; + private static BetterLocationListener listener = new BetterLocationListener(); + + public static BetterLocationListener getListener() + { + return listener; + } + + public static void cleanup() + { + synchronized (listener.locationMap) + { + listener.locationMap.clear(); + } + } + + public BetterLocation(final String worldName, final double x, final double y, final double z) + { + super(Bukkit.getWorld(worldName), x, y, z); + this.worldName = worldName; + addToMap(this); + } + + public BetterLocation(final String worldName, final double x, final double y, + final double z, final float yaw, final float pitch) + { + super(Bukkit.getWorld(worldName), x, y, z, yaw, pitch); + this.worldName = worldName; + addToMap(this); + } + + public BetterLocation(final World world, final double x, final double y, final double z) + { + super(world, x, y, z); + if (world == null) + { + throw new WorldNotLoadedException(); + } + this.worldName = world.getName(); + addToMap(this); + } + + public BetterLocation(final World world, final double x, final double y, + final double z, final float yaw, final float pitch) + { + super(world, x, y, z, yaw, pitch); + if (world == null) + { + throw new WorldNotLoadedException(); + } + this.worldName = world.getName(); + addToMap(this); + } + + public BetterLocation(final Location location) + { + super(location.getWorld(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); + if (location.getWorld() == null) + { + throw new WorldNotLoadedException(); + } + this.worldName = location.getWorld().getName(); + addToMap(this); + } + + @Override + public World getWorld() + { + World world = super.getWorld(); + if (world == null) + { + world = Bukkit.getWorld(worldName); + } + if (world == null) + { + throw new WorldNotLoadedException(); + } + else + { + super.setWorld(world); + } + return world; + } + + @Override + public void setWorld(final World world) + { + if (world == null) + { + throw new WorldNotLoadedException(); + } + if (!world.getName().equals(this.worldName)) + { + getListener().removeLocation(this); + this.worldName = world.getName(); + addToMap(this); + } + super.setWorld(world); + } + + public String getWorldName() + { + return worldName; + } + + private void addToMap(final BetterLocation location) + { + synchronized (listener.locationMap) + { + List<WeakReference<Location>> locations = listener.locationMap.get(location.getWorldName()); + if (locations == null) + { + locations = new LinkedList<WeakReference<Location>>(); + listener.locationMap.put(location.getWorldName(), locations); + } + locations.add(new WeakReference<Location>(location)); + } + } + + + public static class WorldNotLoadedException extends RuntimeException + { + public WorldNotLoadedException() + { + super("World is not loaded."); + } + } + + + public static class BetterLocationListener extends org.bukkit.event.world.WorldListener implements Runnable + { + private static Random random = new Random(); + private final transient Map<String, List<WeakReference<Location>>> locationMap = new HashMap<String, List<WeakReference<Location>>>(); + + @Override + public void onWorldLoad(final WorldLoadEvent event) + { + final String worldName = event.getWorld().getName(); + synchronized (locationMap) + { + final List<WeakReference<Location>> locations = locationMap.get(worldName); + if (locations != null) + { + for (final Iterator<WeakReference<Location>> it = locations.iterator(); it.hasNext();) + { + final WeakReference<Location> weakReference = it.next(); + final Location loc = weakReference.get(); + if (loc == null) + { + it.remove(); + } + else + { + loc.setWorld(event.getWorld()); + } + } + } + } + } + + @Override + public void onWorldUnload(final WorldUnloadEvent event) + { + final String worldName = event.getWorld().getName(); + synchronized (locationMap) + { + final List<WeakReference<Location>> locations = locationMap.get(worldName); + if (locations != null) + { + for (final Iterator<WeakReference<Location>> it = locations.iterator(); it.hasNext();) + { + final WeakReference<Location> weakReference = it.next(); + final Location loc = weakReference.get(); + if (loc == null) + { + it.remove(); + } + else + { + loc.setWorld(null); + } + } + } + } + } + + @Override + public void run() + { + synchronized (locationMap) + { + // Pick a world by random + final Collection<List<WeakReference<Location>>> allWorlds = locationMap.values(); + final int randomPick = (allWorlds.isEmpty() ? 0 : random.nextInt(allWorlds.size())); + List<WeakReference<Location>> locations = null; + final Iterator<List<WeakReference<Location>>> iterator = allWorlds.iterator(); + for (int i = 0; iterator.hasNext() && i < randomPick; i++) + { + iterator.next(); + } + if (iterator.hasNext()) + { + locations = iterator.next(); + } + if (locations != null) + { + for (final Iterator<WeakReference<Location>> it = locations.iterator(); it.hasNext();) + { + final WeakReference<Location> weakReference = it.next(); + final Location loc = weakReference.get(); + if (loc == null) + { + it.remove(); + } + } + } + } + } + + private void removeLocation(final BetterLocation location) + { + final String worldName = location.getWorldName(); + synchronized (locationMap) + { + final List<WeakReference<Location>> locations = locationMap.get(worldName); + if (locations != null) + { + for (final Iterator<WeakReference<Location>> it = locations.iterator(); it.hasNext();) + { + final WeakReference<Location> weakReference = it.next(); + final Location loc = weakReference.get(); + if (loc == null || loc == location) + { + it.remove(); + } + } + } + } + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/DummyOfflinePlayer.java b/Essentials/src/com/earth2me/essentials/craftbukkit/DummyOfflinePlayer.java new file mode 100644 index 000000000..66adf7b6f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/DummyOfflinePlayer.java @@ -0,0 +1,100 @@ +package com.earth2me.essentials.craftbukkit; + +import java.util.Map; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + + +public class DummyOfflinePlayer implements OfflinePlayer +{ + private final transient String name; + + public DummyOfflinePlayer(String name) + { + this.name = name; + } + + @Override + public boolean isOnline() + { + return false; + } + + @Override + public String getName() + { + return name; + } + + @Override + public boolean isBanned() + { + return false; + } + + @Override + public void setBanned(boolean bln) + { + } + + @Override + public boolean isWhitelisted() + { + return false; + } + + @Override + public void setWhitelisted(boolean bln) + { + } + + @Override + public Player getPlayer() + { + return Bukkit.getPlayerExact(name); + } + + @Override + public long getFirstPlayed() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getLastPlayed() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasPlayedBefore() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isOp() + { + return false; + } + + @Override + public void setOp(boolean bln) + { + } + + @Override + public Map<String, Object> serialize() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Location getBedSpawnLocation() + { + throw new UnsupportedOperationException("Not supported yet."); + } + +} diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java b/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java index 308568452..e99bf613b 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.craftbukkit; -import com.earth2me.essentials.craftbukkit.FakeInventory; import java.util.HashMap; import java.util.Map; import org.bukkit.Location; diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/OfflineBedLocation.java b/Essentials/src/com/earth2me/essentials/craftbukkit/OfflineBedLocation.java index 3ddfd20b5..6e0dcf94a 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/OfflineBedLocation.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/OfflineBedLocation.java @@ -1,13 +1,12 @@ package com.earth2me.essentials.craftbukkit; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.api.IEssentials; import java.util.logging.Level; import java.util.logging.Logger; import net.minecraft.server.NBTTagCompound; import net.minecraft.server.WorldNBTStorage; import org.bukkit.Location; import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; public class OfflineBedLocation @@ -39,7 +38,7 @@ public class OfflineBedLocation { spawnWorld = cserver.getWorlds().get(0).getName(); } - return new Location(cserver.getWorld(spawnWorld), playerStorage.getInt("SpawnX"), playerStorage.getInt("SpawnY"), playerStorage.getInt("SpawnZ")); + return new BetterLocation(spawnWorld, playerStorage.getInt("SpawnX"), playerStorage.getInt("SpawnY"), playerStorage.getInt("SpawnZ")); } return null; } diff --git a/Essentials/src/com/earth2me/essentials/external/gnu/inet/encoding/Punycode.java b/Essentials/src/com/earth2me/essentials/external/gnu/inet/encoding/Punycode.java new file mode 100644 index 000000000..831d071a7 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/external/gnu/inet/encoding/Punycode.java @@ -0,0 +1,321 @@ +package com.earth2me.essentials.external.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/external/gnu/inet/encoding/PunycodeException.java b/Essentials/src/com/earth2me/essentials/external/gnu/inet/encoding/PunycodeException.java new file mode 100644 index 000000000..4f8ce93d1 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/external/gnu/inet/encoding/PunycodeException.java @@ -0,0 +1,45 @@ +package com.earth2me.essentials.external.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/EssentialsBlockListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsBlockListener.java index 648bfcef5..0b461eb91 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.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; } @@ -24,15 +28,15 @@ public class EssentialsBlockListener implements Listener { return; } - final User user = ess.getUser(event.getPlayer()); // 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; } - 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( @@ -41,7 +45,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/listener/EssentialsEntityListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java new file mode 100644 index 000000000..26b5a55d1 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java @@ -0,0 +1,140 @@ +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 java.util.List; +import lombok.Cleanup; +import org.bukkit.Material; +import org.bukkit.entity.Animals; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; +import org.bukkit.event.entity.*; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsEntityListener extends EntityListener +{ + private final transient IEssentials ess; + + public EssentialsEntityListener(final IEssentials ess) + { + super(); + this.ess = ess; + } + + @Override + public void onEntityDamage(final EntityDamageEvent event) + { + if (event instanceof EntityDamageByEntityEvent) + { + final EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event; + final Entity eAttack = edEvent.getDamager(); + final Entity eDefend = edEvent.getEntity(); + if (eDefend instanceof Player && eAttack instanceof Player) + { + @Cleanup + final IUser attacker = ess.getUser((Player)eAttack); + attacker.acquireReadLock(); + attacker.updateActivity(true); + final ItemStack itemstack = attacker.getItemInHand(); + final List<String> commandList = attacker.getData().getPowertool(itemstack.getType()); + if (commandList != null && !commandList.isEmpty()) + { + for (String command : commandList) + { + + if (command != null && !command.isEmpty()) + { + final IUser defender = ess.getUser((Player)eDefend); + attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", defender.getName())); + event.setCancelled(true); + return; + } + } + } + } + if (eDefend instanceof Animals && eAttack instanceof Player) + { + final IUser player = ess.getUser((Player)eAttack); + final ItemStack hand = player.getItemInHand(); + if (hand != null && hand.getType() == Material.MILK_BUCKET) + { + ((Animals)eDefend).setAge(-24000); + hand.setType(Material.BUCKET); + player.setItemInHand(hand); + player.updateInventory(); + event.setCancelled(true); + } + } + } + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) + { + final Player player = (Player)event.getEntity(); + player.setFireTicks(0); + player.setRemainingAir(player.getMaximumAir()); + event.setCancelled(true); + } + } + + @Override + public void onEntityCombust(final EntityCombustEvent event) + { + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) + { + event.setCancelled(true); + } + } + + @Override + public void onEntityDeath(final EntityDeathEvent event) + { + if (event instanceof PlayerDeathEvent) + { + final PlayerDeathEvent pdevent = (PlayerDeathEvent)event; + final IUser user = ess.getUser((Player)pdevent.getEntity()); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (user.isAuthorized("essentials.back.ondeath") && !settings.getData().getCommands().isDisabled("back")) + { + user.setLastLocation(); + user.sendMessage(_("backAfterDeath")); + } + if (!settings.getData().getGeneral().isDeathMessages()) + { + pdevent.setDeathMessage(""); + } + } + } + + @Override + public void onFoodLevelChange(final FoodLevelChangeEvent event) + { + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) + { + event.setCancelled(true); + } + } + + @Override + public void onEntityRegainHealth(final EntityRegainHealthEvent event) + { + + if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player) + { + @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/EssentialsPlayerListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java index 8e151c3e9..5250fba52 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java +++ b/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java @@ -1,10 +1,15 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.listener; import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; 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 com.earth2me.essentials.user.UserData.TimestampType; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; @@ -12,6 +17,7 @@ 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; @@ -34,6 +40,7 @@ public class EssentialsPlayerListener implements Listener public EssentialsPlayerListener(final IEssentials parent) { + super(); this.ess = parent; this.server = parent.getServer(); } @@ -41,19 +48,18 @@ public class EssentialsPlayerListener implements Listener @EventHandler(priority = EventPriority.NORMAL) public void onPlayerRespawn(final PlayerRespawnEvent event) { - final User user = ess.getUser(event.getPlayer()); - updateCompass(user); - if (ess.getSettings().changeDisplayName()) - { - user.setDisplayNick(); - } + final IUser user = ess.getUser(event.getPlayer()); + user.updateCompass(); + user.updateDisplayName(); } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerChat(final PlayerChatEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (user.isMuted()) + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isMuted()) { event.setCancelled(true); user.sendMessage(_("playerMuted")); @@ -62,17 +68,14 @@ public class EssentialsPlayerListener implements Listener final Iterator<Player> it = event.getRecipients().iterator(); while (it.hasNext()) { - final User u = ess.getUser(it.next()); - if (u.isIgnoredPlayer(user.getName())) + final IUser player = ess.getUser(it.next()); + if (player.isIgnoringPlayer(user.getName())) { it.remove(); } } user.updateActivity(true); - if (ess.getSettings().changeDisplayName()) - { - user.setDisplayNick(); - } + user.updateDisplayName(); } @EventHandler(priority = EventPriority.HIGH) @@ -82,9 +85,14 @@ public class EssentialsPlayerListener implements Listener { return; } - final User user = ess.getUser(event.getPlayer()); + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); - if (user.isAfk() && ess.getSettings().getFreezeAfkPlayers()) + if (user.getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()) { final Location from = event.getFrom(); final Location to = event.getTo().clone(); @@ -112,15 +120,20 @@ public class EssentialsPlayerListener implements Listener @EventHandler(priority = EventPriority.MONITOR) public void onPlayerQuit(final PlayerQuitEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (ess.getSettings().removeGodOnDisconnect() && user.isGodModeEnabled()) + @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.getSavedInventory() != null) + if (user.getData().getInventory() != null) { - user.getInventory().setContents(user.getSavedInventory()); - user.setSavedInventory(null); + user.getInventory().setContents(user.getData().getInventory().getBukkitInventory()); + user.getData().setInventory(null); } user.updateActivity(false); user.dispose(); @@ -129,21 +142,24 @@ public class EssentialsPlayerListener implements Listener @EventHandler(priority = EventPriority.MONITOR) public void onPlayerJoin(final PlayerJoinEvent event) { - ess.getBackup().onPlayerJoin(); - final User user = ess.getUser(event.getPlayer()); + ess.getBackup().startTask(); + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireWriteLock(); - if (ess.getSettings().changeDisplayName()) - { - user.setDisplayNick(); - } - user.setLastLoginAddress(user.getAddress().getAddress().getHostAddress()); + user.updateDisplayName(); + user.getData().setIpAddress(user.getAddress().getAddress().getHostAddress()); user.updateActivity(false); if (user.isAuthorized("essentials.sleepingignored")) { user.setSleepingIgnored(true); } - if (!ess.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd")) + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + if (!settings.getData().getCommands().isDisabled("motd") && user.isAuthorized("essentials.motd")) { try { @@ -154,7 +170,7 @@ public class EssentialsPlayerListener implements Listener } catch (IOException ex) { - if (ess.getSettings().isDebug()) + if (settings.getData().getGeneral().isDebug()) { LOGGER.log(Level.WARNING, ex.getMessage(), ex); } @@ -165,10 +181,10 @@ public class EssentialsPlayerListener implements Listener } } - if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) + if (!settings.getData().getCommands().isDisabled("mail") && user.isAuthorized("essentials.mail")) { - final List<String> mail = user.getMails(); - if (mail.isEmpty()) + final List<String> mail = user.getData().getMails(); + if (mail == null || mail.isEmpty()) { user.sendMessage(_("noNewMail")); } @@ -186,18 +202,20 @@ public class EssentialsPlayerListener implements Listener { return; } - User user = ess.getUser(event.getPlayer()); - user.setNPC(false); + @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 == false && (user.isBanned() || event.getResult() == Result.KICK_BANNED)) + 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")); + 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; } @@ -208,21 +226,8 @@ public class EssentialsPlayerListener implements Listener } event.allow(); - user.setLastLogin(System.currentTimeMillis()); - updateCompass(user); - } - - private void updateCompass(final User user) - { - Location loc = user.getHome(user.getLocation()); - if (loc == null) - { - loc = user.getBedSpawnLocation(); - } - if (loc != null) - { - user.setCompassTarget(loc); - } + user.setTimestamp(TimestampType.LOGIN, System.currentTimeMillis()); + user.updateCompass(); } @EventHandler(priority = EventPriority.HIGH) @@ -233,28 +238,30 @@ public class EssentialsPlayerListener implements Listener return; } - final User user = ess.getUser(event.getPlayer()); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final IUser user = ess.getUser(event.getPlayer()); //There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports. - if ((event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND) && ess.getSettings().registerBackInListener()) + if ((event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND) && settings.getData().getCommands().getBack().isRegisterBackInListener()) { user.setLastLocation(); } - if (ess.getSettings().changeDisplayName()) - { - user.setDisplayNick(); - } - updateCompass(user); + user.updateDisplayName(); + user.updateCompass(); } @EventHandler(priority = EventPriority.HIGH) 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)) + @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(stack); + user.getInventory().addItem(hand); user.updateInventory(); } } @@ -262,8 +269,10 @@ public class EssentialsPlayerListener implements Listener @EventHandler(priority = EventPriority.HIGH) public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) { - final User user = ess.getUser(event.getPlayer()); - if (user.hasUnlimited(new ItemStack(event.getBucket()))) + @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() @@ -280,46 +289,59 @@ public class EssentialsPlayerListener implements Listener @EventHandler(priority = EventPriority.NORMAL) public void onPlayerAnimation(final PlayerAnimationEvent event) { - final User user = ess.getUser(event.getPlayer()); + final IUser user = ess.getUser(event.getPlayer()); user.updateActivity(true); - if (event.getAnimationType() == PlayerAnimationType.ARM_SWING - && user.hasPowerTools() && user.arePowerToolsEnabled()) + if (event.getAnimationType() == PlayerAnimationType.ARM_SWING) { usePowertools(user); } } - private void usePowertools(final User user) + private void usePowertools(final IUser user) { - final ItemStack is = user.getItemInHand(); - int id; - if (is == null || (id = is.getTypeId()) == 0) + user.acquireReadLock(); + try { - return; - } - final List<String> commandList = user.getPowertool(id); - if (commandList == null || commandList.isEmpty()) - { - return; - } + if (!user.getData().hasPowerTools() || !user.getData().isPowerToolsEnabled()) + { + return; + } - // We need to loop through each command and execute - for (String command : commandList) - { - if (command.matches(".*\\{player\\}.*")) + final ItemStack hand = user.getItemInHand(); + Material type; + if (hand == null || (type = hand.getType()) == Material.AIR) { - //user.sendMessage("Click a player to use this command"); - continue; + return; } - else if (command.startsWith("c:")) + final List<String> commandList = user.getData().getPowertool(type); + + if (commandList == null || commandList.isEmpty()) { - user.chat(command.substring(2)); + return; } - else + + // We need to loop through each command and execute + for (String command : commandList) { - user.getServer().dispatchCommand(user.getBase(), command); + if (command.matches(".*\\{player\\}.*")) + { + //user.sendMessage("Click a player to use this command"); + continue; + } + else if (command.startsWith("c:")) + { + user.chat(command.substring(2)); + } + else + { + user.getServer().dispatchCommand(user.getBase(), command); + } } } + finally + { + user.unlock(); + } } @EventHandler(priority = EventPriority.MONITOR) @@ -329,15 +351,17 @@ public class EssentialsPlayerListener implements Listener { return; } - final User user = ess.getUser(event.getPlayer()); + 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()) { - User spyer = ess.getUser(player); - if (spyer.isSocialSpyEnabled() && !user.equals(spyer)) + @Cleanup + IUser spyer = ess.getUser(player); + spyer.acquireReadLock(); + if (spyer.getData().isSocialspy() && !user.equals(spyer)) { player.sendMessage(user.getDisplayName() + " : " + event.getMessage()); } @@ -352,14 +376,27 @@ public class EssentialsPlayerListener implements Listener @EventHandler(priority = EventPriority.MONITOR) public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) { - if (ess.getSettings().getNoGodWorlds().contains(event.getPlayer().getLocation().getWorld().getName())) - { - User user = ess.getUser(event.getPlayer()); - if (user.isGodModeEnabledRaw()) + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (!settings.getData().getWorldOptions(event.getPlayer().getLocation().getWorld().getName()).isGodmode() && !user.isAuthorized("essentials.nogod.override")) + { + 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.MONITOR) @@ -374,21 +411,33 @@ public class EssentialsPlayerListener implements Listener return; } - if (ess.getSettings().getUpdateBedAtDaytime() && event.getClickedBlock().getType() == Material.BED_BLOCK) + @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()); } } @EventHandler(priority = EventPriority.LOW) - public void onPlayerPickupItem(PlayerPickupItemEvent event) + public void onPlayerPickupItem(final PlayerPickupItemEvent event) { - if (event.isCancelled() || !ess.getSettings().getDisableItemPickupWhileAfk()) + if (event.isCancelled()) + { + return; + } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getCommands().getAfk().isDisableItemPickupWhileAfk()) { return; } - final User user = ess.getUser(event.getPlayer()); - if (user.isAfk()) + @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/EssentialsPluginListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java index 11f42e701..8d8879f4a 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java +++ b/Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java @@ -1,5 +1,7 @@ -package com.earth2me.essentials; +package com.earth2me.essentials.listener; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IReload; import java.util.logging.Level; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -8,12 +10,13 @@ import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; -public class EssentialsPluginListener implements Listener, IConf +public class EssentialsPluginListener implements Listener, IReload { private final transient IEssentials ess; public EssentialsPluginListener(final IEssentials ess) { + super(); this.ess = ess; } @@ -21,10 +24,10 @@ public class EssentialsPluginListener implements Listener, IConf public void onPluginEnable(final PluginEnableEvent event) { ess.getPermissionsHandler().checkPermissions(); - ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin()); + ess.getCommandHandler().addPlugin(event.getPlugin()); if (!ess.getPaymentMethod().hasMethod() && ess.getPaymentMethod().setMethod(ess.getServer().getPluginManager())) { - ess.getLogger().log(Level.INFO, "Payment method found (" + ess.getPaymentMethod().getMethod().getName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")"); + ess.getLogger().log(Level.INFO, "Payment method found ({0} version: {1})", new Object[]{ess.getPaymentMethod().getMethod().getName(), ess.getPaymentMethod().getMethod().getVersion()}); } } @@ -32,7 +35,7 @@ public class EssentialsPluginListener implements Listener, IConf public void onPluginDisable(final PluginDisableEvent event) { ess.getPermissionsHandler().checkPermissions(); - ess.getAlternativeCommandsHandler().removePlugin(event.getPlugin()); + ess.getCommandHandler().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())) { @@ -42,9 +45,8 @@ public class EssentialsPluginListener implements Listener, IConf } @Override - public void reloadConfig() + public void onReload() { - ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); - ess.getPermissionsHandler().checkPermissions(); + //ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); } } diff --git a/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java b/Essentials/src/com/earth2me/essentials/listener/TNTExplodeListener.java index 54e49ad5f..a16710617 100644 --- a/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java +++ b/Essentials/src/com/earth2me/essentials/listener/TNTExplodeListener.java @@ -1,6 +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; @@ -11,7 +13,7 @@ import org.bukkit.event.entity.EntityExplodeEvent; 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) @@ -22,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); } } @@ -38,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; } @@ -53,6 +54,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/AbstractPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/AbstractPermissionsHandler.java new file mode 100644 index 000000000..6c01d7de1 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/perm/AbstractPermissionsHandler.java @@ -0,0 +1,10 @@ +package com.earth2me.essentials.perm; + + +public abstract class AbstractPermissionsHandler implements IPermissionsHandler +{ + @Override + public void checkPermissions() + { + } +} diff --git a/Essentials/src/com/earth2me/essentials/perm/AbstractSuperpermsPermission.java b/Essentials/src/com/earth2me/essentials/perm/AbstractSuperpermsPermission.java new file mode 100644 index 000000000..a4cef71a3 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/perm/AbstractSuperpermsPermission.java @@ -0,0 +1,31 @@ +package com.earth2me.essentials.perm; + +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IPermission; +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()); + } + } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.OP; + } +} diff --git a/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java index fad479444..4cee6b5ad 100644 --- a/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java @@ -1,12 +1,12 @@ package com.earth2me.essentials.perm; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.api.IEssentials; import java.util.List; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -public class ConfigPermissionsHandler implements IPermissionsHandler +/*public class ConfigPermissionsHandler extends AbstractPermissionsHandler { private final transient IEssentials ess; @@ -58,4 +58,4 @@ public class ConfigPermissionsHandler implements IPermissionsHandler { return null; } -} +}*/ diff --git a/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java b/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java index 8c3cdf1e2..9e9c25e1f 100644 --- a/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java @@ -8,7 +8,7 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -public class GroupManagerHandler implements IPermissionsHandler +public class GroupManagerHandler extends AbstractPermissionsHandler { private final transient GroupManager groupManager; diff --git a/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java index 27af48e8c..d769eddd7 100644 --- a/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java @@ -19,4 +19,6 @@ public interface IPermissionsHandler String getPrefix(Player base); String getSuffix(Player base); + + public void checkPermissions(); } diff --git a/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java index b51aeb055..5a931ef14 100644 --- a/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java @@ -5,7 +5,7 @@ import java.util.List; import org.bukkit.entity.Player; -public class NullPermissionsHandler implements IPermissionsHandler +public class NullPermissionsHandler extends AbstractPermissionsHandler { @Override public String getGroup(final Player base) diff --git a/Essentials/src/com/earth2me/essentials/perm/Permissions.java b/Essentials/src/com/earth2me/essentials/perm/Permissions.java new file mode 100644 index 000000000..80b6abf56 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/perm/Permissions.java @@ -0,0 +1,54 @@ +package com.earth2me.essentials.perm; + +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IPermission; +import java.util.Locale; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public enum Permissions implements IPermission +{ + AFK_OTHERS, + BALANCE_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; + } +} diff --git a/Essentials/src/com/earth2me/essentials/perm/Permissions2Handler.java b/Essentials/src/com/earth2me/essentials/perm/Permissions2Handler.java index 6b5ff5b73..3945f5375 100644 --- a/Essentials/src/com/earth2me/essentials/perm/Permissions2Handler.java +++ b/Essentials/src/com/earth2me/essentials/perm/Permissions2Handler.java @@ -8,7 +8,7 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -public class Permissions2Handler implements IPermissionsHandler +public class Permissions2Handler extends AbstractPermissionsHandler { private final transient PermissionHandler permissionHandler; diff --git a/Essentials/src/com/earth2me/essentials/perm/Permissions3Handler.java b/Essentials/src/com/earth2me/essentials/perm/Permissions3Handler.java index 190d5b8c5..7b0c1085f 100644 --- a/Essentials/src/com/earth2me/essentials/perm/Permissions3Handler.java +++ b/Essentials/src/com/earth2me/essentials/perm/Permissions3Handler.java @@ -8,7 +8,7 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -public class Permissions3Handler implements IPermissionsHandler +public class Permissions3Handler extends AbstractPermissionsHandler { private final transient PermissionHandler permissionHandler; diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java index 5d8e62232..6d7fbf777 100644 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java @@ -8,7 +8,7 @@ import ru.tehkode.permissions.PermissionUser; import ru.tehkode.permissions.bukkit.PermissionsEx; -public class PermissionsExHandler implements IPermissionsHandler +public class PermissionsExHandler extends AbstractPermissionsHandler { private final transient PermissionManager manager; diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java index 8c16aab7a..282a138ab 100644 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java @@ -15,18 +15,18 @@ public class PermissionsHandler implements IPermissionsHandler private transient String defaultGroup = "default"; private final transient Plugin plugin; private final static Logger LOGGER = Logger.getLogger("Minecraft"); - private transient boolean useSuperperms = false; + //private transient boolean useSuperperms = false; public PermissionsHandler(final Plugin plugin) { this.plugin = plugin; } - public PermissionsHandler(final Plugin plugin, final boolean useSuperperms) + /*public PermissionsHandler(final Plugin plugin, final boolean useSuperperms) { this.plugin = plugin; this.useSuperperms = useSuperperms; - } + }*/ public PermissionsHandler(final Plugin plugin, final String defaultGroup) { @@ -96,6 +96,7 @@ public class PermissionsHandler implements IPermissionsHandler return suffix; } + @Override public void checkPermissions() { final PluginManager pluginManager = plugin.getServer().getPluginManager(); @@ -166,14 +167,14 @@ public class PermissionsHandler implements IPermissionsHandler return; } - if (useSuperperms) - { + //if (useSuperperms) + //{ if (!(handler instanceof SuperpermsHandler)) { LOGGER.log(Level.INFO, "Essentials: Using superperms based permissions."); handler = new SuperpermsHandler(); } - } + /*} else { if (!(handler instanceof ConfigPermissionsHandler)) @@ -181,11 +182,11 @@ public class PermissionsHandler implements IPermissionsHandler LOGGER.log(Level.INFO, "Essentials: Using config based permissions. Enable superperms in config."); handler = new ConfigPermissionsHandler(plugin); } - } + }*/ } - public void setUseSuperperms(final boolean useSuperperms) + /*public void setUseSuperperms(final boolean useSuperperms) { this.useSuperperms = useSuperperms; - } + }*/ } diff --git a/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java b/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java index 70a118bcf..1828ec527 100644 --- a/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java @@ -4,7 +4,7 @@ import java.util.List; import org.bukkit.entity.Player; -public class SuperpermsHandler implements IPermissionsHandler +public class SuperpermsHandler extends AbstractPermissionsHandler { @Override public String getGroup(final Player base) diff --git a/Essentials/src/com/earth2me/essentials/settings/Chat.java b/Essentials/src/com/earth2me/essentials/settings/Chat.java index 623228c4e..82a18e051 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; 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..21b6f3b05 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Economy.java +++ b/Essentials/src/com/earth2me/essentials/settings/Economy.java @@ -40,4 +40,15 @@ public class Economy implements StorageObject @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..3b808fb41 100644 --- a/Essentials/src/com/earth2me/essentials/settings/General.java +++ b/Essentials/src/com/earth2me/essentials/settings/General.java @@ -25,9 +25,16 @@ 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; } diff --git a/Essentials/src/com/earth2me/essentials/settings/GroupsHolder.java b/Essentials/src/com/earth2me/essentials/settings/GroupsHolder.java new file mode 100644 index 000000000..2f0f016f6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/settings/GroupsHolder.java @@ -0,0 +1,168 @@ +package com.earth2me.essentials.settings; + +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IGroups; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import java.io.File; +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 GroupsHolder extends AsyncStorageObjectHolder<Groups> implements IGroups +{ + public GroupsHolder(final IEssentials ess) + { + super(ess, Groups.class); + } + + @Override + public File getStorageFile() + { + return new File(ess.getDataFolder(), "groups.yml"); + } + + public void registerPermissions() + { + acquireReadLock(); + try + { + final Map<String, GroupOptions> groups = getData().getGroups(); + if (groups == null || groups.isEmpty()) + { + return; + } + Util.registerPermissions("essentials.groups", groups.keySet(), true, ess); + } + finally + { + unlock(); + } + } + + public Collection<GroupOptions> getGroups(final IUser player) + { + acquireReadLock(); + try + { + final Map<String, GroupOptions> groups = getData().getGroups(); + if (groups == null || groups.isEmpty()) + { + return Collections.emptyList(); + } + final ArrayList<GroupOptions> list = new ArrayList(); + for (Entry<String, GroupOptions> entry : groups.entrySet()) + { + if (player.isAuthorized("essentials.groups." + entry.getKey())) + { + list.add(entry.getValue()); + } + } + return list; + } + finally + { + unlock(); + } + } + + @Override + public double getHealCooldown(final IUser player) + { + for (GroupOptions groupOptions : getGroups(player)) + { + if (groupOptions.getHealCooldown() != null) + { + return groupOptions.getHealCooldown(); + } + } + return 0; + } + + @Override + public double getTeleportCooldown(final IUser player) + { + for (GroupOptions groupOptions : getGroups(player)) + { + if (groupOptions.getTeleportCooldown() != null) + { + return groupOptions.getTeleportCooldown(); + } + } + return 0; + } + + @Override + public double getTeleportDelay(final IUser player) + { + for (GroupOptions groupOptions : getGroups(player)) + { + if (groupOptions.getTeleportDelay() != null) + { + return groupOptions.getTeleportDelay(); + } + } + return 0; + } + + @Override + public String getPrefix(final IUser player) + { + for (GroupOptions groupOptions : getGroups(player)) + { + if (groupOptions.getPrefix() != null) + { + return groupOptions.getPrefix(); + } + } + return ""; + } + + @Override + public String getSuffix(final IUser player) + { + for (GroupOptions groupOptions : getGroups(player)) + { + if (groupOptions.getSuffix() != null) + { + return groupOptions.getSuffix(); + } + } + return ""; + } + + @Override + public int getHomeLimit(final IUser player) + { + for (GroupOptions groupOptions : getGroups(player)) + { + if (groupOptions.getHomes() != null) + { + return groupOptions.getHomes(); + } + } + return 0; + } + + @Override + public String getChatFormat(final IUser player) + { + for (GroupOptions groupOptions : getGroups(player)) + { + if (groupOptions.getMessageFormat() != null) + { + return groupOptions.getMessageFormat(); + } + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getChat().getDefaultFormat(); + } +} 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/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..c35323dcd 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Spawns.java +++ b/Essentials/src/com/earth2me/essentials/settings/Spawns.java @@ -1,5 +1,6 @@ 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; @@ -13,6 +14,27 @@ import org.bukkit.Location; @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/Warp.java b/Essentials/src/com/earth2me/essentials/settings/Warp.java new file mode 100644 index 000000000..20a252afb --- /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.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Location; + +@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/Worth.java b/Essentials/src/com/earth2me/essentials/settings/Worth.java index 707f907cf..9487deb8f 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Worth.java +++ b/Essentials/src/com/earth2me/essentials/settings/Worth.java @@ -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/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/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/storage/AbstractDelayedYamlFileReader.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java index d48b4a060..a559684b8 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,58 +14,82 @@ 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; private final transient Plugin 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: " + 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(); - Bukkit.getLogger().log(Level.INFO, "File not found: " + file.toString()); + Bukkit.getLogger().log(Level.SEVERE, "File could not be opened: " + ex.getMessage(), ex); } - 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 697ef7730..d3289310e 100644 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java +++ b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java @@ -1,54 +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 java.util.logging.Logger; 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 31c61a63f..8259dbd79 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,25 +90,30 @@ 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 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 @@ -109,13 +135,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 @@ -126,10 +158,11 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen data = object; } rwl.writeLock().unlock(); + loaded.set(true); } @Override - public void onException() + public void onException(final Exception exception) { if (data == null) { @@ -143,6 +176,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..95cf9efa4 100644 --- a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java +++ b/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java @@ -1,17 +1,14 @@ package com.earth2me.essentials.storage; -import java.beans.IntrospectionException; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.craftbukkit.BetterLocation; 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 +212,20 @@ 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,12 +280,7 @@ 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 BetterLocation(worldName, x, y, z, yaw, pitch); } return super.construct(node); } @@ -411,7 +417,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/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..f23d4cc7b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectMap.java @@ -0,0 +1,24 @@ + +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/ManagedFile.java b/Essentials/src/com/earth2me/essentials/storage/ManagedFile.java index a1918fa20..0a2443f29 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; 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..ebd010de2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java @@ -0,0 +1,138 @@ +package com.earth2me.essentials.storage; + +import com.earth2me.essentials.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/YamlStorageWriter.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java index fd1f0f863..0b741eda1 100644 --- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java +++ b/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java @@ -1,5 +1,6 @@ package com.earth2me.essentials.storage; +import com.earth2me.essentials.craftbukkit.BetterLocation; import java.io.PrintWriter; import java.lang.reflect.Field; import java.lang.reflect.Modifier; @@ -24,12 +25,12 @@ public class YamlStorageWriter implements IStorageWriter private transient static final Pattern NON_WORD_PATTERN = Pattern.compile("\\W"); private transient final PrintWriter writer; private transient static final Yaml YAML = new Yaml(); - + public YamlStorageWriter(final PrintWriter writer) { this.writer = writer; } - + @Override public void save(final StorageObject object) { @@ -46,7 +47,7 @@ public class YamlStorageWriter implements IStorageWriter Logger.getLogger(YamlStorageWriter.class.getName()).log(Level.SEVERE, null, ex); } } - + private void writeToFile(final Object object, final int depth, final Class clazz) throws IllegalAccessException { for (Field field : clazz.getDeclaredFields()) @@ -55,7 +56,7 @@ public class YamlStorageWriter implements IStorageWriter if (Modifier.isPrivate(modifier) && !Modifier.isTransient(modifier) && !Modifier.isStatic(modifier)) { field.setAccessible(true); - + final Object data = field.get(object); if (writeKey(field, depth, data)) { @@ -86,7 +87,7 @@ public class YamlStorageWriter implements IStorageWriter } } } - + private boolean writeKey(final Field field, final int depth, final Object data) { final boolean commentPresent = writeComment(field, depth); @@ -110,7 +111,7 @@ public class YamlStorageWriter implements IStorageWriter } return false; } - + private boolean writeComment(final Field field, final int depth) { final boolean commentPresent = field.isAnnotationPresent(Comment.class); @@ -132,7 +133,7 @@ public class YamlStorageWriter implements IStorageWriter } return commentPresent; } - + private void writeCollection(final Collection<Object> data, final int depth) throws IllegalAccessException { writer.println(); @@ -163,7 +164,7 @@ public class YamlStorageWriter implements IStorageWriter } writer.println(); } - + private void writeMap(final Map<Object, Object> data, final int depth) throws IllegalArgumentException, IllegalAccessException { writer.println(); @@ -200,7 +201,7 @@ public class YamlStorageWriter implements IStorageWriter } } } - + private void writeIndention(final int depth) { for (int i = 0; i < depth; i++) @@ -208,7 +209,7 @@ public class YamlStorageWriter implements IStorageWriter writer.print(" "); } } - + private void writeScalar(final Object data) { if (data instanceof String || data instanceof Boolean || data instanceof Number) @@ -218,6 +219,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); @@ -243,7 +249,7 @@ public class YamlStorageWriter implements IStorageWriter throw new UnsupportedOperationException(); } } - + private void writeKey(final Object data) { if (data instanceof String || data instanceof Boolean || data instanceof Number) @@ -260,6 +266,10 @@ public class YamlStorageWriter implements IStorageWriter writer.print(output); } } + else if (data instanceof Enum) + { + writeMaterial(data.toString()); + } else if (data instanceof Material) { writeMaterial(data); @@ -277,12 +287,12 @@ public class YamlStorageWriter implements IStorageWriter throw new UnsupportedOperationException(); } } - + private void writeMaterial(final Object data) { writer.print(data.toString().toLowerCase(Locale.ENGLISH)); } - + private void writeMaterialData(final Object data) { final MaterialData matData = (MaterialData)data; @@ -293,7 +303,7 @@ public class YamlStorageWriter implements IStorageWriter writer.print(matData.getData()); } } - + private void writeItemStack(final Object data) { final ItemStack itemStack = (ItemStack)data; @@ -306,7 +316,7 @@ public class YamlStorageWriter implements IStorageWriter writeEnchantmentLevel(entry); } } - + private void writeEnchantmentLevel(Object data) { final Entry<Enchantment, Integer> enchLevel = (Entry<Enchantment, Integer>)data; @@ -314,13 +324,20 @@ public class YamlStorageWriter implements IStorageWriter writer.print(':'); writer.print(enchLevel.getValue()); } - + private void writeLocation(final Location entry, final int depth) { writer.println(); writeIndention(depth); writer.print("world: "); - writeScalar(entry.getWorld().getName()); + if (entry instanceof BetterLocation) + { + writeScalar(((BetterLocation)entry).getWorldName()); + } + else + { + writeScalar(entry.getWorld().getName()); + } writeIndention(depth); writer.print("x: "); writeScalar(entry.getX()); diff --git a/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java b/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java index 85c00c1b6..7d8fc78d0 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java +++ b/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java @@ -1,12 +1,14 @@ package com.earth2me.essentials.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 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 +23,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; String pluginName = ""; for (Plugin p : ess.getServer().getPluginManager().getPlugins()) @@ -48,14 +53,14 @@ public class HelpInput implements IText if (pluginName.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.isAuthorized(node)) { lines.add("§c" + k.getKey() + "§7: " + k.getValue().get(DESCRIPTION)); } } else { - if (ess.getSettings().showNonEssCommandsInHelp()) + if (settings.getData().getCommands().getHelp().isShowNonEssCommandsInHelp()) { final HashMap<String, Object> value = k.getValue(); Object permissions = null; @@ -96,7 +101,7 @@ public class HelpInput implements IText } else { - if (!ess.getSettings().hidePermissionlessHelp()) + if (!settings.getData().getCommands().getHelp().isHidePermissionlessCommands()) { lines.add("§c" + k.getKey() + "§7: " + value.get(DESCRIPTION)); } diff --git a/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java b/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java index a7aab67ba..a7a1117a2 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java +++ b/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java @@ -1,13 +1,14 @@ package com.earth2me.essentials.textreader; import com.earth2me.essentials.DescParseTickFormat; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +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,11 +37,13 @@ public class KeywordReplacer implements IText String version; if (sender instanceof Player) { - final User user = ess.getUser(sender); + @Cleanup + final IUser user = ess.getUser((Player)sender); + user.acquireReadLock(); displayName = user.getDisplayName(); ipAddress = user.getAddress().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/TextInput.java b/Essentials/src/com/earth2me/essentials/textreader/TextInput.java index 316a0b576..0856d5ff6 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/TextInput.java +++ b/Essentials/src/com/earth2me/essentials/textreader/TextInput.java @@ -1,11 +1,14 @@ package com.earth2me.essentials.textreader; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; import com.earth2me.essentials.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(user.getGroup()) + ".txt"); + } + } + catch (InvalidNameException ex) + { + Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex); } } if (file == null || !file.exists()) 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/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 0e544ae06..57469151b 100644 --- a/Essentials/src/com/earth2me/essentials/user/User.java +++ b/Essentials/src/com/earth2me/essentials/user/User.java @@ -1,25 +1,63 @@ package com.earth2me.essentials.user; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.IUser; +import com.earth2me.essentials.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.Util; +import com.earth2me.essentials.api.*; +import com.earth2me.essentials.craftbukkit.InventoryWorkaround; +import com.earth2me.essentials.register.payment.Method; +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() @@ -38,12 +76,83 @@ public class User extends UserBase implements IUser } @Override - public long getLastTeleportTimestamp() + public boolean isAuthorized(String node) { - acquireReadLock(); + if (!isOnlineUser()) + { + return false; + } + + if (getData().isJailed()) + { + return false; + } + //TODO: switch to Superperms only + return ess.getPermissionsHandler().hasPermission(base, node); + } + + @Override + public boolean isAuthorized(IPermission permission) + { + return isAuthorized(permission.getPermission()); + } + + /*@Override + public boolean isAuthorized(IEssentialsCommand cmd) + { + return isAuthorized(cmd, "essentials."); + } + + @Override + public boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix) + { + return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName())); + }*/ + + @Override + public void checkCooldown(final UserData.TimestampType cooldownType, final double cooldown, final boolean set, final String bypassPermission) throws CooldownException + { + 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) && !isAuthorized(bypassPermission)) + { + throw new CooldownException(Util.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.formatCurrency(value, ess))); + if (initiator != null) + { + initiator.sendMessage(_("addedToOthersAccount", Util.formatCurrency(value, ess), this.getDisplayName())); + } } finally { @@ -52,30 +161,69 @@ 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.formatCurrency(value, ess), reciever.getDisplayName())); + reciever.sendMessage(_("moneyRecievedFrom", Util.formatCurrency(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.formatCurrency(value, ess))); + if (initiator != null) + { + initiator.sendMessage(_("takenFromOthersAccount", Util.formatCurrency(value, ess), this.getDisplayName())); + } + } + + public boolean canAfford(final double cost) + { + final double mon = getMoney(); + return mon >= cost || isAuthorized("essentials.eco.loan"); + } + + 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(getLocation()); } finally { @@ -83,13 +231,50 @@ 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(); + @Cleanup + final IGroups groups = ess.getGroups(); + groups.acquireReadLock(); + // 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()); + } + 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('&', '§'); + displayname = displayname.concat("§f"); + + return displayname; } finally { @@ -97,13 +282,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) == '§' ? 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(this.isAuthorized("essentials.sleepingignored") ? true : set); + if (set && !getData().isAfk()) + { + afkPosition = getLocation(); + } + getData().setAfk(set); } finally { @@ -112,12 +385,60 @@ public class User extends UserBase implements IUser } @Override - public void takeMoney(double value) + public boolean toggleAfk() { - acquireWriteLock(); + final boolean now = super.toggleAfk(); + this.setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : now); + return now; + } + + //Returns true if status expired during this check + public boolean checkJailTimeout(final long currentTime) + { + acquireReadLock(); + try + { + 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 + { + unlock(); + } + } + + //Returns true if status expired during this check + public boolean checkMuteTimeout(final long currentTime) + { + 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 { @@ -125,13 +446,20 @@ public class User extends UserBase implements IUser } } - @Override - public void giveMoney(double value) + //Returns true if status expired during this check + public boolean checkBanTimeout(final long currentTime) { - acquireWriteLock(); + acquireReadLock(); try { - getData().setMoney(getData().getMoney() + value); + if (getData().getBan() != null && getData().getBan().getTimeout() > 0 && getData().getBan().getTimeout() < currentTime && isBanned()) + { + acquireWriteLock(); + getData().setBan(null); + setBanned(false); + return true; + } + return false; } finally { @@ -139,19 +467,95 @@ public class User extends UserBase implements IUser } } - @Override - public String getGroup() + public void updateActivity(final boolean broadcast) { - throw new UnsupportedOperationException("Not supported yet."); + acquireReadLock(); + try + { + if (getData().isAfk()) + { + acquireWriteLock(); + getData().setAfk(false); + if (broadcast && !hidden) + { + ess.broadcastMessage(this, _("userIsNotAway", getDisplayName())); + } + } + lastActivity = System.currentTimeMillis(); + } + finally + { + unlock(); + } } - @Override - public void setLastLocation() + public void checkActivity() { - acquireWriteLock(); + @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 && !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 IUser user = ess.getUser(player); + if (user.isAuthorized("essentials.kick.notify")) + { + player.sendMessage(_("playerKicked", Console.NAME, getName(), kickReason)); + } + } + } + final long autoafk = settings.getData().getCommands().getAfk().getAutoAFK(); + acquireReadLock(); + try + { + if (!getData().isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorized("essentials.afk")) + { + 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 { - getData().setLastLocation(base.getLocation()); + @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 { @@ -160,40 +564,155 @@ public class User extends UserBase implements IUser } @Override + public String getGroup() + { + return ess.getPermissionsHandler().getGroup(base); + } + + public boolean inGroup(final String group) + { + return ess.getPermissionsHandler().inGroup(base, group); + } + + public boolean canBuild() + { + return ess.getPermissionsHandler().canBuild(base, getGroup()); + } + + @Override public Location getHome(String name) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @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 (isAuthorized("essentials.oversizedstacks")) + { + @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; } } diff --git a/Essentials/src/com/earth2me/essentials/user/UserBase.java b/Essentials/src/com/earth2me/essentials/user/UserBase.java index 9dda2f950..c4a338ce9 100644 --- a/Essentials/src/com/earth2me/essentials/user/UserBase.java +++ b/Essentials/src/com/earth2me/essentials/user/UserBase.java @@ -1,12 +1,20 @@ package com.earth2me.essentials.user; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.InvalidNameException; +import com.earth2me.essentials.craftbukkit.BetterLocation; import com.earth2me.essentials.craftbukkit.OfflineBedLocation; import com.earth2me.essentials.storage.AsyncStorageObjectHolder; 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; @@ -15,18 +23,16 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.permissions.Permissible; 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, OtherExcludes.class}) protected Player base; protected transient OfflinePlayer offlinePlayer; @@ -34,14 +40,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() @@ -58,65 +64,387 @@ 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() { - if (isOnlineUser()) { + if (isOnlineUser()) + { return base.getBedSpawnLocation(); - } else { + } + else + { return OfflineBedLocation.getBedLocation(base.getName(), ess); - } + } } @Override public void setBanned(boolean bln) { - if (isOnlineUser()) { + if (isOnlineUser()) + { base.setBanned(bln); - } else { + } + else + { offlinePlayer.setBanned(bln); } } @Override - public File getStorageFile() + 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) + { + 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, Location> homes = getData().getHomes(); + if (homes == null) + { + homes = new HashMap<String, Location>(); + getData().setHomes(homes); + } + homes.put(Util.sanitizeKey(name), 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 (Location location : getData().getHomes().values()) + { + if (location.getWorld().equals(loc.getWorld())) { + worldHomes.add(location); + } + } + 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(); + } + } + + @Override + public Location getLocation() { - return ess.getUserMap().getUserFile(getName()); + return new BetterLocation(base.getLocation()); + } + + public static interface OtherExcludes { + Location getLocation(); } } diff --git a/Essentials/src/com/earth2me/essentials/user/UserData.java b/Essentials/src/com/earth2me/essentials/user/UserData.java index 4586d0627..7a11f5f9d 100644 --- a/Essentials/src/com/earth2me/essentials/user/UserData.java +++ b/Essentials/src/com/earth2me/essentials/user/UserData.java @@ -15,8 +15,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 +29,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 +49,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 +57,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/config.yml b/Essentials/src/config.yml index 877ff0c42..fac2f6080 100644 --- a/Essentials/src/config.yml +++ b/Essentials/src/config.yml @@ -247,6 +247,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 + ############################################################ # +------------------------------------------------------+ # # | EssentialsHome | # diff --git a/Essentials/src/messages.properties b/Essentials/src/messages.properties index bf029fc2b..1bf1ffca7 100644 --- a/Essentials/src/messages.properties +++ b/Essentials/src/messages.properties @@ -161,7 +161,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=\u00a77You have just been smited @@ -297,6 +297,7 @@ requiredBukkit= * ! * You need atleast build {0} of CraftBukkit, download it fro returnPlayerToJailError=Error occurred when trying to return player to jail. 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 @@ -324,6 +325,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... @@ -382,6 +384,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} @@ -405,3 +408,4 @@ year=year years=years youAreHealed=\u00a77You have been healed. youHaveNewMail=\u00a7cYou have {0} messages!\u00a7f Type \u00a77/mail read\u00a7f to view your mail. + diff --git a/Essentials/src/messages_da.properties b/Essentials/src/messages_da.properties index 73004e01f..bef1683a7 100644 --- a/Essentials/src/messages_da.properties +++ b/Essentials/src/messages_da.properties @@ -161,7 +161,7 @@ kitError2=\u00a7cDette kit eksisterer ikke eller er forkert defineret. kitError=\u00a7cDer er ikke nogen gyldige kits. kitErrorHelp=\u00a7cM\u00e5ske mangler en ting en m\u00e6ngde i konfigurationen? Eller m\u00c3\u00a5ske er der nisser p\u00c3\u00a5 spil? kitGive=\u00a77Giver kit til {0} (oversat korrekt?). -kitInvFull=\u00a7cDin inventory er fuld, placerer kit p\u00e5 gulvet. +InvFull=\u00a7cYour inventory was full, dropping items on the floor kitTimed=\u00a7cDu kan ikke benytte dette kit igen i {0}. kits=\u00a77Kits: {0} lightningSmited=\u00a77Du er blevet ramt af Guds vrede (din admin) @@ -297,6 +297,7 @@ requiredBukkit=* ! * You need atleast build {0} of CraftBukkit, download it from returnPlayerToJailError=En fejl opstod ved fors\u00f8g p\u00e5 at returnere spilleren til f\u00e6ngsel. second=sekund seconds=sekunder +seenBanReason=Reason: {0} seenOffline=Spilleren {0} har v\u00c3\u00a6ret offline i {1} seenOnline=Spilleren {0} har v\u00c3\u00a6ret online i {1} serverFull=Serveren er sgu fuld. Den b\u00c3\u00b8r melde sig til AA. @@ -324,6 +325,7 @@ teleportDisabled={0} har ikke teleportation aktiveret. teleportHereRequest=\u00a7c{0}\u00a7c har anmodet om, at du teleporterer dig til ham/hende. teleportNewPlayerError=Fejlede ved teleportering af ny spiller teleportRequest=\u00a7c{0}\u00a7c har anmodet om at teleportere til dig. +teleportRequestsCancelledWorldChange=\u00a77Pending teleport requests have been cancelled on world change. teleportRequestTimeoutInfo=\u00a77This request will timeout after {0} seconds. teleportTop=\u00a77Teleporterer til toppen. teleportationCommencing=\u00a77Teleport begynder... @@ -382,6 +384,7 @@ warpUsePermission=\u00a7cDu har ikke tilladelse til at benytte den warp. warpingTo=\u00a77Warper til {0}. warps=Warps: {0} warpsCount=\u00a77Der er {0} warps. Viser side {1} af {2}. +warpOverwrite=\u00a7cYou cannot overwrite that warp. weatherStorm=\u00a77Du har sat vejret til ''storm'' i {0} weatherStormFor=\u00a77Du har sat vejret til ''storm'' i {0} i {1} sekunder weatherSun=\u00a77Du har sat vejret til ''sol'' i {0} @@ -405,3 +408,4 @@ year=\u00e5r years=\u00e5r youAreHealed=\u00a77Du er blevet healed. Halleluja! youHaveNewMail=\u00a7cDu har {0} flaskeposter!\u00a7f Type \u00a77/mail read for at se din flaskepost. + diff --git a/Essentials/src/messages_de.properties b/Essentials/src/messages_de.properties index 90c1c0f01..6431f6f94 100644 --- a/Essentials/src/messages_de.properties +++ b/Essentials/src/messages_de.properties @@ -125,6 +125,7 @@ infoFileDoesNotExist=Datei info.txt existiert nicht. Erzeuge eine neue Datei. infoPages=Seite \u00a7c{0}\u00a7f von \u00a7c{1}\u00a7f: infoUnknownChapter=Unbekanntes Kapitel: invBigger=Das andere Inventar ist gr\u00f6sser als deins. +InvFull=\u00a7cYour inventory was full, dropping items on the floor invRestored=Dein Inventar wurde wieder hergestellt. invSee=Du siehst das Inventar von {0}. invSeeHelp=Benutze /invsee um dein Inventar wiederherzustellen. @@ -161,7 +162,6 @@ kitError2=\u00a7cDiese Ausr\u00fcstung existiert nicht oder ist ung\u00fcltig. kitError=\u00a7cEs gibt keine g\u00fcltigen Ausr\u00fcstungen. kitErrorHelp=\u00a7cEventuell fehlt bei einem Gegenstand die Menge? kitGive=\u00a77Gebe Ausr\u00fcstung {0}. -kitInvFull=\u00a7cDein Inventar ist voll, lege Ausr\u00fcstung auf den Boden kitTimed=\u00a7cDu kannst diese Ausr\u00fcstung nicht innerhalb von {0} anfordern. kits=\u00a77Ausr\u00fcstungen: {0} lightningSmited=\u00a77Du wurdest gepeinigt. @@ -297,6 +297,7 @@ requiredBukkit=* ! * You need atleast build {0} of CraftBukkit, download it from returnPlayerToJailError=Fehler beim Versuch, den Spieler ins Gef\u00e4ngnis zu teleportieren. second=Sekunde seconds=Sekunden +seenBanReason=Reason: {0} seenOffline=Spieler {0} ist offline seit {1} seenOnline=Spieler {0} ist online seit {1} serverFull=Server ist voll @@ -324,6 +325,7 @@ teleportDisabled={0} verweigert die Teleportierung. teleportHereRequest=\u00a7c{0}\u00a7c fragt, ob du dich zu ihm teleportierst. teleportNewPlayerError=Fehler beim Teleportieren eines neuen Spielers teleportRequest=\u00a7c{0}\u00a7c fragt, ob er sich zu dir teleportieren darf. +teleportRequestsCancelledWorldChange=\u00a77Pending teleport requests have been cancelled on world change. teleportRequestTimeoutInfo=\u00a77This request will timeout after {0} seconds. teleportTop=\u00a77Teleportiere nach oben. teleportationCommencing=\u00a77Teleportierung gestartet... @@ -382,6 +384,7 @@ warpUsePermission=\u00a7cDu hast keinen Zugriff f\u00fcr diesen Warp-Punkt. warpingTo=\u00a77Teleportiere zu Warp-Punkt {0}. warps=Warps: {0} warpsCount=\u00a77Es gibt {0} Warp-Punkte. Zeige Seite {1} von {2}. +warpOverwrite=\u00a7cYou cannot overwrite that warp. weatherStorm=\u00a77In {0} st\u00fcrmt es nun. weatherStormFor=\u00a77In {0} st\u00fcrmt es nun f\u00fcr {1} Sekunden. weatherSun=\u00a77In {0} scheint nun die Sonne. diff --git a/Essentials/src/messages_en.properties b/Essentials/src/messages_en.properties index 8eea25f5c..389d9c955 100644 --- a/Essentials/src/messages_en.properties +++ b/Essentials/src/messages_en.properties @@ -15,7 +15,7 @@ backUsageMsg=\u00a77Returning to previous location. backupFinished=Backup finished backupStarted=Backup started balance=\u00a77Balance: {0} -balanceTop=\u00a77 Top balances ({0}) +balanceTop=\u00a77Top balances ({0}) banExempt=\u00a7cYou can not ban that player. banIpAddress=\u00a77Banned IP address bannedIpsFileError=Error reading banned-ips.txt @@ -161,7 +161,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=\u00a77You have just been smited @@ -234,7 +234,7 @@ notAllowedToQuestion=\u00a7cYou are not authorized to use question. notAllowedToShout=\u00a7cYou are not authorized to shout. notEnoughExperience=You do not have enough experience. notEnoughMoney=You do not have sufficient funds. -notRecommendedBukkit=* ! * Bukkit version is not the recommended build for Essentials. +notRecommendedBukkit= * ! * Bukkit version is not the recommended build for Essentials. notSupportedYet=Not supported yet. nothingInHand = \u00a7cYou have nothing in your hand. now=now @@ -275,7 +275,7 @@ powerToolListEmpty={0} has no commands assigned. powerToolNoSuchCommandAssigned=Command \u00a7c{0}\u00a7f has not been assigned to {1}. powerToolRemove=Command \u00a7c{0}\u00a7f removed from {1}. powerToolRemoveAll=All commands removed from {0}. -powerToolsDisabled=All of your power tools have been enabled. +powerToolsDisabled=All of your power tools have been disabled. powerToolsEnabled=All of your power tools have been enabled. protectionOwner=\u00a76[EssentialsProtect] Protection owner: {0} questionFormat=\u00a77[Question]\u00a7f {0} @@ -290,13 +290,18 @@ repairNone=There were no items that needing repairing. requestAccepted=\u00a77Teleport request accepted. requestAcceptedFrom=\u00a77{0} accepted your teleport request. requestDenied=\u00a77Teleport request denied. -requestDeniedFrom=\u00a77{0} denied your teleport request +requestDeniedFrom=\u00a77{0} denied your teleport request. requestSent=\u00a77Request sent to {0}\u00a77. requestTimedOut=\u00a7cTeleport request has timed out +<<<<<<< HEAD +requiredBukkit= * ! * You need atleast build {0} of CraftBukkit, download it from http://ci.bukkit.org. +======= requiredBukkit=* ! * You need atleast build {0} of CraftBukkit, download it from http://ci.bukkit.org. +>>>>>>> refs/heads/master returnPlayerToJailError=Error occurred when trying to return player to jail. 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 @@ -324,6 +329,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... @@ -344,7 +350,7 @@ timeSetPermission=\u00a7cYou are not authorized to set the time. timeWorldCurrent=The current time in {0} is \u00a73{1} timeWorldSet=The time was set to {0} in: \u00a7c{1} tradeCompleted=\u00a77Trade completed. -tradeSignEmpty=The trade sign does not have enough supply left. +tradeSignEmpty=The trade sign has nothing available for you. tradeSignEmptyOwner=There is nothing to collect from this trade sign. treeFailure=\u00a7cTree generation failure. Try again on grass or dirt. treeSpawned=\u00a77Tree spawned. @@ -375,13 +381,14 @@ versionMismatch=Version mismatch! Please update {0} to the same version. versionMismatchAll=Version mismatch! Please update all Essentials jars to the same version. voiceSilenced=\u00a77Your voice has been silenced warpDeleteError=Problem deleting the warp file. -warpListPermission=\u00a7cYou do not have Permission to list that warps. +warpListPermission=\u00a7cYou do not have Permission to list warps. warpNotExist=That warp does not exist. warpSet=\u00a77Warp {0} set. 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_es.properties b/Essentials/src/messages_es.properties index 23d2dbf0e..1f58b9840 100644 --- a/Essentials/src/messages_es.properties +++ b/Essentials/src/messages_es.properties @@ -161,7 +161,7 @@ kitError2=\u00a7cEse kit no existe o esta mal escrito. kitError=\u00a7cNo hay ningun kit valido. kitErrorHelp=\u00a7cPerhaps an item is missing a quantity in the configuration? kitGive=\u00a77Dando kit a {0}. -kitInvFull=\u00a7cTu inventario esta lleno, su kit se pondra en el suelo +InvFull=\u00a7cYour inventory was full, dropping items on the floor kitTimed=\u00a7c No puedes usar ese kit de nuevo para otro{0}. kits=\u00a77Kits: {0} lightningSmited=\u00a77Acabas de ser golpeado @@ -297,6 +297,7 @@ requiredBukkit=* ! * You need atleast build {0} of CraftBukkit, download it from returnPlayerToJailError=Error al intentar quitar al jugador de la carcel. second=segundo seconds=segundos +seenBanReason=Reason: {0} seenOffline=El jugador {0} esta desconectado desde {1} seenOnline=El jugador {0} lleva conectado desde {1} serverFull=Servidor lleno @@ -324,6 +325,7 @@ teleportDisabled={0} tiene desactivado los teletransportes. teleportHereRequest=\u00a7c{0}\u00a7c ha pedido que te teletransportes con el. teleportNewPlayerError=Error al teletransportar al nuevo jugador teleportRequest=\u00a7c{0}\u00a7c te ha pedido teletransportarse contigo. +teleportRequestsCancelledWorldChange=\u00a77Pending teleport requests have been cancelled on world change. teleportRequestTimeoutInfo=\u00a77This request will timeout after {0} seconds. teleportTop=\u00a77Teletransportandote a la cima. teleportationCommencing=\u00a77Comenzando teletransporte... @@ -382,6 +384,7 @@ warpUsePermission=\u00a7cNo tienes permisos para usar ese teletransporte. warpingTo=\u00a77Teletransportandote a {0}. warps=Warps: {0} warpsCount=\u00a77Hay {0} teletransportes. Mostrando pagina {1} de {2}. +warpOverwrite=\u00a7cYou cannot overwrite that warp. weatherStorm=\u00a77Has establecido el tiempo a tormenta en este mundo. weatherStormFor=\u00a77Has establecido el tiempo a tormenta en este {1} durante {0} segundos. weatherSun=\u00a77Has establecido el tiempo a sol en este mundo. diff --git a/Essentials/src/messages_fr.properties b/Essentials/src/messages_fr.properties index 5f96bd678..da56fedce 100644 --- a/Essentials/src/messages_fr.properties +++ b/Essentials/src/messages_fr.properties @@ -161,7 +161,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. @@ -297,6 +297,7 @@ requiredBukkit=* ! * You need atleast build {0} of CraftBukkit, download it from returnPlayerToJailError=Erreur survenue lors de la tentative d''emprisonner de nouveau un joueur. 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. @@ -324,6 +325,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=\u00a77This request will timeout after {0} seconds. teleportTop=\u00a77T\u00e9l\u00e9portation vers le haut. teleportationCommencing=\u00a77D\u00e9but de la t\u00e9l\u00e9portation... @@ -382,6 +384,7 @@ warpUsePermission=\u00a7cVous n''avez pas la permission d''utiliser ce warp. warpingTo=\u00a77T\u00e9l\u00e9portation au warp {0}. warps=Raccourcis : {0} warpsCount=\u00a77Il y a {0} raccourcis. 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} diff --git a/Essentials/src/messages_nl.properties b/Essentials/src/messages_nl.properties index ae43f75f2..0bedee060 100644 --- a/Essentials/src/messages_nl.properties +++ b/Essentials/src/messages_nl.properties @@ -161,7 +161,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 @@ -297,6 +297,7 @@ requiredBukkit=* ! * You need atleast build {0} of CraftBukkit, download it from returnPlayerToJailError=Fout opgetreden bij terugzetten van speler in gevangenis. 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 @@ -324,6 +325,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... @@ -382,6 +384,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} @@ -405,3 +408,4 @@ year=jaar years=jaren youAreHealed=\u00a77Je bent genezen. youHaveNewMail=\u00a7cJe hebt {0} berichten!\u00a7f Type \u00a77/mail read\u00a7f om je berichten te bekijken. + diff --git a/Essentials/src/plugin.yml b/Essentials/src/plugin.yml index 2cb225390..c78091ea4 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://ci.earth2me.net/ +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] commands: @@ -341,7 +341,7 @@ commands: tpa: description: Request to teleport to the specified player. usage: /<command> <player> - aliases: [call,etpa,ecall] + aliases: [call,join,etpa,ecall,ejoin] tpaall: description: Requests all players online to teleport to you. usage: /<command> <player> @@ -353,7 +353,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> diff --git a/Essentials/test/com/earth2me/essentials/EconomyTest.java b/Essentials/test/com/earth2me/essentials/EconomyTest.java index 219d68b40..1fe8c76c5 100644 --- a/Essentials/test/com/earth2me/essentials/EconomyTest.java +++ b/Essentials/test/com/earth2me/essentials/EconomyTest.java @@ -3,6 +3,8 @@ package com.earth2me.essentials; import com.earth2me.essentials.api.Economy; import com.earth2me.essentials.api.NoLoanPermittedException; import com.earth2me.essentials.api.UserDoesNotExistException; +import com.earth2me.essentials.craftbukkit.DummyOfflinePlayer; +import com.earth2me.essentials.user.User; import java.io.IOException; import junit.framework.TestCase; import org.bukkit.World.Environment; @@ -34,7 +36,7 @@ public class EconomyTest extends TestCase { fail("IOException"); } - server.addPlayer(new OfflinePlayer(PLAYERNAME, ess)); + server.addPlayer(new User(new DummyOfflinePlayer(PLAYERNAME), ess)); } // only one big test, since we use static instances @@ -45,7 +47,7 @@ public class EconomyTest extends TestCase assertFalse("NPC does not exists", Economy.playerExists(NPCNAME)); assertTrue("Create NPC", Economy.createNPC(NPCNAME)); assertTrue("NPC exists", Economy.playerExists(NPCNAME)); - assertNotNull("NPC can be accessed", ess.getOfflineUser(NPCNAME)); + assertNotNull("NPC can be accessed", ess.getUser(NPCNAME)); try { Economy.removeNPC(NPCNAME); diff --git a/Essentials/test/com/earth2me/essentials/FakeServer.java b/Essentials/test/com/earth2me/essentials/FakeServer.java index b5ecc1e08..d54ca031a 100644 --- a/Essentials/test/com/earth2me/essentials/FakeServer.java +++ b/Essentials/test/com/earth2me/essentials/FakeServer.java @@ -2,6 +2,9 @@ package com.earth2me.essentials; import com.earth2me.essentials.craftbukkit.FakeWorld; import com.avaje.ebean.config.ServerConfig; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.craftbukkit.DummyOfflinePlayer; +import com.earth2me.essentials.user.User; import java.io.File; import java.util.*; import java.util.concurrent.Callable; @@ -324,13 +327,6 @@ public class FakeServer implements Server players.add(base1); } - public OfflinePlayer createPlayer(String name, IEssentials ess) - { - OfflinePlayer player = new OfflinePlayer(name, ess); - player.setLocation(new Location(worlds.get(0), 0, 0, 0, 0, 0)); - return player; - } - @Override public World createWorld(String string, Environment e, ChunkGenerator cg) { diff --git a/Essentials/test/com/earth2me/essentials/StorageTest.java b/Essentials/test/com/earth2me/essentials/StorageTest.java index b7fe23433..a04c6b34f 100644 --- a/Essentials/test/com/earth2me/essentials/StorageTest.java +++ b/Essentials/test/com/earth2me/essentials/StorageTest.java @@ -133,7 +133,7 @@ public class StorageTest extends TestCase } - @Test + /*@Test public void testOldUserdata() { ExecuteTimer ext = new ExecuteTimer(); @@ -157,5 +157,5 @@ public class StorageTest extends TestCase user.reloadConfig(); ext.mark("reloaded file (cached)"); System.out.println(ext.end()); - } + }*/ } diff --git a/Essentials/test/com/earth2me/essentials/UserTest.java b/Essentials/test/com/earth2me/essentials/UserTest.java index ef9ab515d..d9cd5789d 100644 --- a/Essentials/test/com/earth2me/essentials/UserTest.java +++ b/Essentials/test/com/earth2me/essentials/UserTest.java @@ -5,11 +5,14 @@ import junit.framework.TestCase; import org.bukkit.Location; import org.bukkit.World.Environment; import org.bukkit.plugin.InvalidDescriptionException; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.craftbukkit.DummyOfflinePlayer; +import com.earth2me.essentials.user.User; public class UserTest extends TestCase { - private final OfflinePlayer base1; + private final IUser base1; private final Essentials ess; private final FakeServer server; @@ -31,7 +34,7 @@ public class UserTest extends TestCase { fail("IOException"); } - base1 = server.createPlayer("testPlayer1", ess); + base1 = new User(new DummyOfflinePlayer("testPlayer1"), ess); server.addPlayer(base1); ess.getUser(base1); } @@ -41,7 +44,7 @@ public class UserTest extends TestCase System.out.println(getName() + " should " + what); } - public void testUpdate() + /*public void testUpdate() { OfflinePlayer base1alt = server.createPlayer(base1.getName(), ess); assertEquals(base1alt, ess.getUser(base1alt).getBase()); @@ -49,11 +52,11 @@ public class UserTest extends TestCase public void testHome() { - User user = ess.getUser(base1); + IUser user = ess.getUser(base1); Location loc = base1.getLocation(); user.setHome(); OfflinePlayer base2 = server.createPlayer(base1.getName(), ess); - User user2 = ess.getUser(base2); + IUser user2 = ess.getUser(base2); Location home = user2.getHome(loc); assertNotNull(home); @@ -63,12 +66,12 @@ public class UserTest extends TestCase assertEquals(loc.getZ(), home.getZ()); assertEquals(loc.getYaw(), home.getYaw()); assertEquals(loc.getPitch(), home.getPitch()); - } + }*/ - public void testMoney() + /*public void testMoney() { should("properly set, take, give, and get money"); - User user = ess.getUser(base1); + IUser user = ess.getUser(base1); double i; user.setMoney(i = 100.5); user.takeMoney(50); @@ -76,12 +79,12 @@ public class UserTest extends TestCase user.giveMoney(25); i += 25; assertEquals(user.getMoney(), i); - } + }*/ public void testGetGroup() { should("return the default group"); - User user = ess.getUser(base1); + IUser user = ess.getUser(base1); assertEquals(user.getGroup(), "default"); } } diff --git a/Essentials/test/com/earth2me/essentials/UtilTest.java b/Essentials/test/com/earth2me/essentials/UtilTest.java index 71282a18f..cff22c855 100644 --- a/Essentials/test/com/earth2me/essentials/UtilTest.java +++ b/Essentials/test/com/earth2me/essentials/UtilTest.java @@ -1,8 +1,11 @@ package com.earth2me.essentials; +import com.earth2me.essentials.api.InvalidNameException; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; +import java.util.logging.Level; +import java.util.logging.Logger; import junit.framework.TestCase; import org.bukkit.World.Environment; import org.bukkit.plugin.InvalidDescriptionException; @@ -36,7 +39,7 @@ public class UtilTest extends TestCase { Calendar c = new GregorianCalendar(); String resp = Util.formatDateDiff(c, c); - assertEquals(resp, "now"); + assertEquals("now", resp); } public void testFDDfuture() @@ -171,4 +174,26 @@ public class UtilTest extends TestCase b = new GregorianCalendar(2000, 3, 7, 10, 0, 0); assertEquals(" 10 years 6 months 10 days 13 hours 45 minutes 45 seconds", Util.formatDateDiff(a, b)); } + + public void filenameTest() { + try + { + assertEquals("_-", Util.sanitizeFileName("\u0000")); + assertEquals("_-", Util.sanitizeFileName("\u0001")); + assertEquals("_-", Util.sanitizeFileName("\u001f")); + assertEquals(" -", Util.sanitizeFileName(" ")); + assertEquals("_-", Util.sanitizeFileName("..")); + assertEquals("_-", Util.sanitizeFileName("..\\")); + assertEquals("_-", Util.sanitizeFileName("../")); + assertEquals("_-", Util.sanitizeFileName("\"")); + assertEquals("_-", Util.sanitizeFileName("<>?:*.")); + assertEquals("a-0fa", Util.sanitizeFileName("aä")); + + } + catch (InvalidNameException ex) + { + Logger.getLogger(UtilTest.class.getName()).log(Level.SEVERE, null, ex); + } + + } } diff --git a/Essentials2Compat/build.xml b/Essentials2Compat/build.xml new file mode 100644 index 000000000..2a6d21a52 --- /dev/null +++ b/Essentials2Compat/build.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- You may freely edit this file. See commented blocks below for --> +<!-- some examples of how to customize the build. --> +<!-- (If you delete it and reopen the project it will be recreated.) --> +<!-- By default, only the Clean and Build commands use this build script. --> +<!-- Commands such as Run, Debug, and Test only use this build script if --> +<!-- the Compile on Save feature is turned off for the project. --> +<!-- You can turn off the Compile on Save (or Deploy on Save) setting --> +<!-- in the project's Project Properties dialog box.--> +<project name="Essentials2Compat" default="default" basedir="."> + <description>Builds, tests, and runs the project Essentials2Compat.</description> + <import file="nbproject/build-impl.xml"/> + <!-- + + There exist several targets which are by default empty and which can be + used for execution of your tasks. These targets are usually executed + before and after some main targets. They are: + + -pre-init: called before initialization of project properties + -post-init: called after initialization of project properties + -pre-compile: called before javac compilation + -post-compile: called after javac compilation + -pre-compile-single: called before javac compilation of single file + -post-compile-single: called after javac compilation of single file + -pre-compile-test: called before javac compilation of JUnit tests + -post-compile-test: called after javac compilation of JUnit tests + -pre-compile-test-single: called before javac compilation of single JUnit test + -post-compile-test-single: called after javac compilation of single JUunit test + -pre-jar: called before JAR building + -post-jar: called after JAR building + -post-clean: called after cleaning build products + + (Targets beginning with '-' are not intended to be called on their own.) + + Example of inserting an obfuscator after compilation could look like this: + + <target name="-post-compile"> + <obfuscate> + <fileset dir="${build.classes.dir}"/> + </obfuscate> + </target> + + For list of available properties check the imported + nbproject/build-impl.xml file. + + + Another way to customize the build is by overriding existing main targets. + The targets of interest are: + + -init-macrodef-javac: defines macro for javac compilation + -init-macrodef-junit: defines macro for junit execution + -init-macrodef-debug: defines macro for class debugging + -init-macrodef-java: defines macro for class execution + -do-jar-with-manifest: JAR building (if you are using a manifest) + -do-jar-without-manifest: JAR building (if you are not using a manifest) + run: execution of project + -javadoc-build: Javadoc generation + test-report: JUnit report generation + + An example of overriding the target for project execution could look like this: + + <target name="run" depends="Essentials2Compat-impl.jar"> + <exec dir="bin" executable="launcher.exe"> + <arg file="${dist.jar}"/> + </exec> + </target> + + Notice that the overridden target depends on the jar target and not only on + the compile target as the regular run target does. Again, for a list of available + properties which you can use, check the target you are overriding in the + nbproject/build-impl.xml file. + + --> +</project> diff --git a/Essentials2Compat/manifest.mf b/Essentials2Compat/manifest.mf new file mode 100644 index 000000000..328e8e5bc --- /dev/null +++ b/Essentials2Compat/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/Essentials2Compat/nbproject/build-impl.xml b/Essentials2Compat/nbproject/build-impl.xml new file mode 100644 index 000000000..117d471db --- /dev/null +++ b/Essentials2Compat/nbproject/build-impl.xml @@ -0,0 +1,1092 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +*** GENERATED FROM project.xml - DO NOT EDIT *** +*** EDIT ../build.xml INSTEAD *** + +For the purpose of easier reading the script +is divided into following sections: + + - initialization + - compilation + - jar + - execution + - debugging + - javadoc + - junit compilation + - junit execution + - junit debugging + - applet + - cleanup + + --> +<project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="Essentials2Compat-impl"> + <fail message="Please build using Ant 1.8.0 or higher."> + <condition> + <not> + <antversion atleast="1.8.0"/> + </not> + </condition> + </fail> + <target depends="test,jar,javadoc" description="Build and test whole project." name="default"/> + <!-- + ====================== + INITIALIZATION SECTION + ====================== + --> + <target name="-pre-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init" name="-init-private"> + <property file="nbproject/private/config.properties"/> + <property file="nbproject/private/configs/${config}.properties"/> + <property file="nbproject/private/private.properties"/> + </target> + <target name="-pre-init-libraries"> + <property location="../lib/nblibraries.properties" name="libraries.path"/> + <dirname file="${libraries.path}" property="libraries.dir.nativedirsep"/> + <pathconvert dirsep="/" property="libraries.dir"> + <path path="${libraries.dir.nativedirsep}"/> + </pathconvert> + <basename file="${libraries.path}" property="libraries.basename" suffix=".properties"/> + <available file="${libraries.dir}/${libraries.basename}-private.properties" property="private.properties.available"/> + </target> + <target depends="-pre-init-libraries" if="private.properties.available" name="-init-private-libraries"> + <loadproperties encoding="ISO-8859-1" srcfile="${libraries.dir}/${libraries.basename}-private.properties"> + <filterchain> + <replacestring from="$${base}" to="${libraries.dir}"/> + <escapeunicode/> + </filterchain> + </loadproperties> + </target> + <target depends="-pre-init,-init-private,-init-private-libraries" name="-init-libraries"> + <loadproperties encoding="ISO-8859-1" srcfile="${libraries.path}"> + <filterchain> + <replacestring from="$${base}" to="${libraries.dir}"/> + <escapeunicode/> + </filterchain> + </loadproperties> + </target> + <target depends="-pre-init,-init-private,-init-libraries" name="-init-user"> + <property file="${user.properties.file}"/> + <!-- The two properties below are usually overridden --> + <!-- by the active platform. Just a fallback. --> + <property name="default.javac.source" value="1.4"/> + <property name="default.javac.target" value="1.4"/> + </target> + <target depends="-pre-init,-init-private,-init-libraries,-init-user" name="-init-project"> + <property file="nbproject/configs/${config}.properties"/> + <property file="nbproject/project.properties"/> + </target> + <target depends="-pre-init,-init-private,-init-libraries,-init-user,-init-project,-init-macrodef-property" name="-do-init"> + <available file="${manifest.file}" property="manifest.available"/> + <condition property="splashscreen.available"> + <and> + <not> + <equals arg1="${application.splash}" arg2="" trim="true"/> + </not> + <available file="${application.splash}"/> + </and> + </condition> + <condition property="main.class.available"> + <and> + <isset property="main.class"/> + <not> + <equals arg1="${main.class}" arg2="" trim="true"/> + </not> + </and> + </condition> + <condition property="manifest.available+main.class"> + <and> + <isset property="manifest.available"/> + <isset property="main.class.available"/> + </and> + </condition> + <condition property="do.archive"> + <not> + <istrue value="${jar.archive.disabled}"/> + </not> + </condition> + <condition property="do.mkdist"> + <and> + <isset property="do.archive"/> + <isset property="libs.CopyLibs.classpath"/> + <not> + <istrue value="${mkdist.disabled}"/> + </not> + </and> + </condition> + <condition property="manifest.available+main.class+mkdist.available"> + <and> + <istrue value="${manifest.available+main.class}"/> + <isset property="do.mkdist"/> + </and> + </condition> + <condition property="do.archive+manifest.available"> + <and> + <isset property="manifest.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+main.class.available"> + <and> + <isset property="main.class.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+splashscreen.available"> + <and> + <isset property="splashscreen.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+manifest.available+main.class"> + <and> + <istrue value="${manifest.available+main.class}"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="manifest.available-mkdist.available"> + <or> + <istrue value="${manifest.available}"/> + <isset property="do.mkdist"/> + </or> + </condition> + <condition property="manifest.available+main.class-mkdist.available"> + <or> + <istrue value="${manifest.available+main.class}"/> + <isset property="do.mkdist"/> + </or> + </condition> + <condition property="have.tests"> + <or> + <available file="${test.src.dir}"/> + </or> + </condition> + <condition property="have.sources"> + <or> + <available file="${src.dir}"/> + </or> + </condition> + <condition property="netbeans.home+have.tests"> + <and> + <isset property="netbeans.home"/> + <isset property="have.tests"/> + </and> + </condition> + <condition property="no.javadoc.preview"> + <and> + <isset property="javadoc.preview"/> + <isfalse value="${javadoc.preview}"/> + </and> + </condition> + <property name="run.jvmargs" value=""/> + <property name="javac.compilerargs" value=""/> + <property name="work.dir" value="${basedir}"/> + <condition property="no.deps"> + <and> + <istrue value="${no.dependencies}"/> + </and> + </condition> + <property name="javac.debug" value="true"/> + <property name="javadoc.preview" value="true"/> + <property name="application.args" value=""/> + <property name="source.encoding" value="${file.encoding}"/> + <property name="runtime.encoding" value="${source.encoding}"/> + <condition property="javadoc.encoding.used" value="${javadoc.encoding}"> + <and> + <isset property="javadoc.encoding"/> + <not> + <equals arg1="${javadoc.encoding}" arg2=""/> + </not> + </and> + </condition> + <property name="javadoc.encoding.used" value="${source.encoding}"/> + <property name="includes" value="**"/> + <property name="excludes" value=""/> + <property name="do.depend" value="false"/> + <condition property="do.depend.true"> + <istrue value="${do.depend}"/> + </condition> + <path id="endorsed.classpath.path" path="${endorsed.classpath}"/> + <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'"> + <length length="0" string="${endorsed.classpath}" when="greater"/> + </condition> + <condition else="false" property="jdkBug6558476"> + <and> + <matches pattern="1\.[56]" string="${java.specification.version}"/> + <not> + <os family="unix"/> + </not> + </and> + </condition> + <property name="javac.fork" value="${jdkBug6558476}"/> + <property name="jar.index" value="false"/> + <property name="jar.index.metainf" value="${jar.index}"/> + <property name="copylibs.rebase" value="true"/> + <available file="${meta.inf.dir}/persistence.xml" property="has.persistence.xml"/> + </target> + <target name="-post-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init,-init-private,-init-libraries,-init-user,-init-project,-do-init" name="-init-check"> + <fail unless="src.dir">Must set src.dir</fail> + <fail unless="test.src.dir">Must set test.src.dir</fail> + <fail unless="build.dir">Must set build.dir</fail> + <fail unless="dist.dir">Must set dist.dir</fail> + <fail unless="build.classes.dir">Must set build.classes.dir</fail> + <fail unless="dist.javadoc.dir">Must set dist.javadoc.dir</fail> + <fail unless="build.test.classes.dir">Must set build.test.classes.dir</fail> + <fail unless="build.test.results.dir">Must set build.test.results.dir</fail> + <fail unless="build.classes.excludes">Must set build.classes.excludes</fail> + <fail unless="dist.jar">Must set dist.jar</fail> + </target> + <target name="-init-macrodef-property"> + <macrodef name="property" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute name="name"/> + <attribute name="value"/> + <sequential> + <property name="@{name}" value="${@{value}}"/> + </sequential> + </macrodef> + </target> + <target depends="-init-ap-cmdline-properties" if="ap.supported.internal" name="-init-macrodef-javac-with-processors"> + <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <attribute default="${javac.processorpath}" name="processorpath"/> + <attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="${javac.debug}" name="debug"/> + <attribute default="${empty.dir}" name="sourcepath"/> + <attribute default="${empty.dir}" name="gensrcdir"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.dir}/empty" name="empty.dir"/> + <mkdir dir="${empty.dir}"/> + <mkdir dir="@{apgeneratedsrcdir}"/> + <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> + <src> + <dirset dir="@{gensrcdir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </src> + <classpath> + <path path="@{classpath}"/> + </classpath> + <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> + <compilerarg line="${javac.compilerargs}"/> + <compilerarg value="-processorpath"/> + <compilerarg path="@{processorpath}:${empty.dir}"/> + <compilerarg line="${ap.processors.internal}"/> + <compilerarg line="${annotation.processing.processor.options}"/> + <compilerarg value="-s"/> + <compilerarg path="@{apgeneratedsrcdir}"/> + <compilerarg line="${ap.proc.none.internal}"/> + <customize/> + </javac> + </sequential> + </macrodef> + </target> + <target depends="-init-ap-cmdline-properties" name="-init-macrodef-javac-without-processors" unless="ap.supported.internal"> + <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <attribute default="${javac.processorpath}" name="processorpath"/> + <attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="${javac.debug}" name="debug"/> + <attribute default="${empty.dir}" name="sourcepath"/> + <attribute default="${empty.dir}" name="gensrcdir"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.dir}/empty" name="empty.dir"/> + <mkdir dir="${empty.dir}"/> + <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> + <src> + <dirset dir="@{gensrcdir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </src> + <classpath> + <path path="@{classpath}"/> + </classpath> + <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> + <compilerarg line="${javac.compilerargs}"/> + <customize/> + </javac> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-javac-with-processors,-init-macrodef-javac-without-processors" name="-init-macrodef-javac"> + <macrodef name="depend" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <sequential> + <depend cache="${build.dir}/depcache" destdir="@{destdir}" excludes="${excludes}" includes="${includes}" srcdir="@{srcdir}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </depend> + </sequential> + </macrodef> + <macrodef name="force-recompile" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${build.classes.dir}" name="destdir"/> + <sequential> + <fail unless="javac.includes">Must set javac.includes</fail> + <pathconvert pathsep="${line.separator}" property="javac.includes.binary"> + <path> + <filelist dir="@{destdir}" files="${javac.includes}"/> + </path> + <globmapper from="*.java" to="*.class"/> + </pathconvert> + <tempfile deleteonexit="true" property="javac.includesfile.binary"/> + <echo file="${javac.includesfile.binary}" message="${javac.includes.binary}"/> + <delete> + <files includesfile="${javac.includesfile.binary}"/> + </delete> + <delete> + <fileset file="${javac.includesfile.binary}"/> + </delete> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-junit"> + <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <sequential> + <property name="junit.forkmode" value="perTest"/> + <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> + <batchtest todir="${build.test.results.dir}"> + <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> + <filename name="@{testincludes}"/> + </fileset> + </batchtest> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="-ea"/> + <jvmarg line="${run.jvmargs}"/> + </junit> + </sequential> + </macrodef> + </target> + <target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile, -profile-init-check" name="profile-init"/> + <target name="-profile-pre-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target name="-profile-post-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target name="-profile-init-macrodef-profile"> + <macrodef name="resolve"> + <attribute name="name"/> + <attribute name="value"/> + <sequential> + <property name="@{name}" value="${env.@{value}}"/> + </sequential> + </macrodef> + <macrodef name="profile"> + <attribute default="${main.class}" name="classname"/> + <element name="customize" optional="true"/> + <sequential> + <property environment="env"/> + <resolve name="profiler.current.path" value="${profiler.info.pathvar}"/> + <java classname="@{classname}" dir="${profiler.info.dir}" fork="true" jvm="${profiler.info.jvm}"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="${profiler.info.jvmargs.agent}"/> + <jvmarg line="${profiler.info.jvmargs}"/> + <env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/> + <arg line="${application.args}"/> + <classpath> + <path path="${run.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile" name="-profile-init-check"> + <fail unless="profiler.info.jvm">Must set JVM to use for profiling in profiler.info.jvm</fail> + <fail unless="profiler.info.jvmargs.agent">Must set profiler agent JVM arguments in profiler.info.jvmargs.agent</fail> + </target> + <target depends="-init-debug-args" name="-init-macrodef-nbjpda"> + <macrodef name="nbjpdastart" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="name"/> + <attribute default="${debug.classpath}" name="classpath"/> + <attribute default="" name="stopclassname"/> + <sequential> + <nbjpdastart addressproperty="jpda.address" name="@{name}" stopclassname="@{stopclassname}" transport="${debug-transport}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </nbjpdastart> + </sequential> + </macrodef> + <macrodef name="nbjpdareload" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${build.classes.dir}" name="dir"/> + <sequential> + <nbjpdareload> + <fileset dir="@{dir}" includes="${fix.classes}"> + <include name="${fix.includes}*.class"/> + </fileset> + </nbjpdareload> + </sequential> + </macrodef> + </target> + <target name="-init-debug-args"> + <property name="version-output" value="java version "${ant.java.version}"/> + <condition property="have-jdk-older-than-1.4"> + <or> + <contains string="${version-output}" substring="java version "1.0"/> + <contains string="${version-output}" substring="java version "1.1"/> + <contains string="${version-output}" substring="java version "1.2"/> + <contains string="${version-output}" substring="java version "1.3"/> + </or> + </condition> + <condition else="-Xdebug" property="debug-args-line" value="-Xdebug -Xnoagent -Djava.compiler=none"> + <istrue value="${have-jdk-older-than-1.4}"/> + </condition> + <condition else="dt_socket" property="debug-transport-by-os" value="dt_shmem"> + <os family="windows"/> + </condition> + <condition else="${debug-transport-by-os}" property="debug-transport" value="${debug.transport}"> + <isset property="debug.transport"/> + </condition> + </target> + <target depends="-init-debug-args" name="-init-macrodef-debug"> + <macrodef name="debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${debug.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${debug-args-line}"/> + <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-java"> + <macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${run.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-copylibs"> + <macrodef name="copylibs" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${manifest.file}" name="manifest"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}"/> + <manifest> + <attribute name="Class-Path" value="${jar.classpath}"/> + <customize/> + </manifest> + </copylibs> + </sequential> + </macrodef> + </target> + <target name="-init-presetdef-jar"> + <presetdef name="jar" uri="http://www.netbeans.org/ns/j2se-project/1"> + <jar compress="${jar.compress}" index="${jar.index}" jarfile="${dist.jar}"> + <j2seproject1:fileset dir="${build.classes.dir}"/> + </jar> + </presetdef> + </target> + <target name="-init-ap-cmdline-properties"> + <property name="annotation.processing.enabled" value="true"/> + <property name="annotation.processing.processors.list" value=""/> + <property name="annotation.processing.processor.options" value=""/> + <property name="annotation.processing.run.all.processors" value="true"/> + <property name="javac.processorpath" value="${javac.classpath}"/> + <property name="javac.test.processorpath" value="${javac.test.classpath}"/> + <condition property="ap.supported.internal" value="true"> + <not> + <matches pattern="1\.[0-5](\..*)?" string="${javac.source}"/> + </not> + </condition> + </target> + <target depends="-init-ap-cmdline-properties" if="ap.supported.internal" name="-init-ap-cmdline-supported"> + <condition else="" property="ap.processors.internal" value="-processor ${annotation.processing.processors.list}"> + <isfalse value="${annotation.processing.run.all.processors}"/> + </condition> + <condition else="" property="ap.proc.none.internal" value="-proc:none"> + <isfalse value="${annotation.processing.enabled}"/> + </condition> + </target> + <target depends="-init-ap-cmdline-properties,-init-ap-cmdline-supported" name="-init-ap-cmdline"> + <property name="ap.cmd.line.internal" value=""/> + </target> + <target depends="-pre-init,-init-private,-init-libraries,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-junit,-init-macrodef-nbjpda,-init-macrodef-debug,-init-macrodef-java,-init-presetdef-jar,-init-ap-cmdline" name="init"/> + <!-- + =================== + COMPILATION SECTION + =================== + --> + <target name="-deps-jar-init" unless="built-jar.properties"> + <property location="${build.dir}/built-jar.properties" name="built-jar.properties"/> + <delete file="${built-jar.properties}" quiet="true"/> + </target> + <target if="already.built.jar.${basedir}" name="-warn-already-built-jar"> + <echo level="warn" message="Cycle detected: Essentials2Compat was already built"/> + </target> + <target depends="init,-deps-jar-init" name="deps-jar" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-jar.properties}" verbose="false"/> + <property file="${built-jar.properties}" prefix="already.built.jar."/> + <antcall target="-warn-already-built-jar"/> + <propertyfile file="${built-jar.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-jar.properties}"/> + <param location="${project.Essentials}" name="call.subproject"/> + <param location="${project.Essentials}/build.xml" name="call.script"/> + <param name="call.target" value="jar"/> + <param name="transfer.built-jar.properties" value="${built-jar.properties}"/> + </antcall> + </target> + <target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/> + <target depends="init" name="-check-automatic-build"> + <available file="${build.classes.dir}/.netbeans_automatic_build" property="netbeans.automatic.build"/> + </target> + <target depends="init" if="netbeans.automatic.build" name="-clean-after-automatic-build"> + <antcall target="clean"/> + </target> + <target depends="init,deps-jar" name="-pre-pre-compile"> + <mkdir dir="${build.classes.dir}"/> + </target> + <target name="-pre-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-depend"> + <pathconvert property="build.generated.subdirs"> + <dirset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </pathconvert> + <j2seproject3:depend srcdir="${src.dir}:${build.generated.subdirs}"/> + </target> + <target depends="init,deps-jar,-pre-pre-compile,-pre-compile, -copy-persistence-xml,-compile-depend" if="have.sources" name="-do-compile"> + <j2seproject3:javac gensrcdir="${build.generated.sources.dir}"/> + <copy todir="${build.classes.dir}"> + <fileset dir="${src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target if="has.persistence.xml" name="-copy-persistence-xml"> + <mkdir dir="${build.classes.dir}/META-INF"/> + <copy todir="${build.classes.dir}/META-INF"> + <fileset dir="${meta.inf.dir}" includes="persistence.xml"/> + </copy> + </target> + <target name="-post-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile,-do-compile,-post-compile" description="Compile project." name="compile"/> + <target name="-pre-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-pre-pre-compile" name="-do-compile-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile/> + <j2seproject3:javac excludes="" gensrcdir="${build.generated.sources.dir}" includes="${javac.includes}" sourcepath="${src.dir}"/> + </target> + <target name="-post-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile-single,-do-compile-single,-post-compile-single" name="compile-single"/> + <!-- + ==================== + JAR BUILDING SECTION + ==================== + --> + <target depends="init" name="-pre-pre-jar"> + <dirname file="${dist.jar}" property="dist.jar.dir"/> + <mkdir dir="${dist.jar.dir}"/> + </target> + <target name="-pre-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive" name="-do-jar-without-manifest" unless="manifest.available-mkdist.available"> + <j2seproject1:jar/> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive+manifest.available" name="-do-jar-with-manifest" unless="manifest.available+main.class-mkdist.available"> + <j2seproject1:jar manifest="${manifest.file}"/> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive+manifest.available+main.class" name="-do-jar-with-mainclass" unless="manifest.available+main.class+mkdist.available"> + <j2seproject1:jar manifest="${manifest.file}"> + <j2seproject1:manifest> + <j2seproject1:attribute name="Main-Class" value="${main.class}"/> + </j2seproject1:manifest> + </j2seproject1:jar> + <echo level="info">To run this application from the command line without Ant, try:</echo> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <pathconvert property="run.classpath.with.dist.jar"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/> + </pathconvert> + <echo level="info">java -cp "${run.classpath.with.dist.jar}" ${main.class}</echo> + </target> + <target depends="init" if="do.archive" name="-do-jar-with-libraries-create-manifest" unless="manifest.available"> + <tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/> + <touch file="${tmp.manifest.file}" verbose="false"/> + </target> + <target depends="init" if="do.archive+manifest.available" name="-do-jar-with-libraries-copy-manifest"> + <tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/> + <copy file="${manifest.file}" tofile="${tmp.manifest.file}"/> + </target> + <target depends="init,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest" if="do.archive+main.class.available" name="-do-jar-with-libraries-set-main"> + <manifest file="${tmp.manifest.file}" mode="update"> + <attribute name="Main-Class" value="${main.class}"/> + </manifest> + </target> + <target depends="init,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest" if="do.archive+splashscreen.available" name="-do-jar-with-libraries-set-splashscreen"> + <basename file="${application.splash}" property="splashscreen.basename"/> + <mkdir dir="${build.classes.dir}/META-INF"/> + <copy failonerror="false" file="${application.splash}" todir="${build.classes.dir}/META-INF"/> + <manifest file="${tmp.manifest.file}" mode="update"> + <attribute name="SplashScreen-Image" value="META-INF/${splashscreen.basename}"/> + </manifest> + </target> + <target depends="init,-init-macrodef-copylibs,compile,-pre-pre-jar,-pre-jar,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest,-do-jar-with-libraries-set-main,-do-jar-with-libraries-set-splashscreen" if="do.mkdist" name="-do-jar-with-libraries-pack"> + <j2seproject3:copylibs manifest="${tmp.manifest.file}"/> + <echo level="info">To run this application from the command line without Ant, try:</echo> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <echo level="info">java -jar "${dist.jar.resolved}"</echo> + </target> + <target depends="-do-jar-with-libraries-pack" if="do.archive" name="-do-jar-with-libraries-delete-manifest"> + <delete> + <fileset file="${tmp.manifest.file}"/> + </delete> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest,-do-jar-with-libraries-set-main,-do-jar-with-libraries-set-splashscreen,-do-jar-with-libraries-pack,-do-jar-with-libraries-delete-manifest" name="-do-jar-with-libraries"/> + <target name="-post-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-jar,-do-jar-with-manifest,-do-jar-without-manifest,-do-jar-with-mainclass,-do-jar-with-libraries,-post-jar" description="Build JAR." name="jar"/> + <!-- + ================= + EXECUTION SECTION + ================= + --> + <target depends="init,compile" description="Run a main class." name="run"> + <j2seproject1:java> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject1:java> + </target> + <target name="-do-not-recompile"> + <property name="javac.includes.binary" value=""/> + </target> + <target depends="init,compile-single" name="run-single"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}"/> + </target> + <target depends="init,compile-test-single" name="run-test-with-main"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}" classpath="${run.test.classpath}"/> + </target> + <!-- + ================= + DEBUGGING SECTION + ================= + --> + <target depends="init" if="netbeans.home" name="-debug-start-debugger"> + <j2seproject1:nbjpdastart name="${debug.class}"/> + </target> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-main-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${debug.class}"/> + </target> + <target depends="init,compile" name="-debug-start-debuggee"> + <j2seproject3:debug> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile,-debug-start-debugger,-debug-start-debuggee" description="Debug project in IDE." if="netbeans.home" name="debug"/> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-stepinto"> + <j2seproject1:nbjpdastart stopclassname="${main.class}"/> + </target> + <target depends="init,compile,-debug-start-debugger-stepinto,-debug-start-debuggee" if="netbeans.home" name="debug-stepinto"/> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-single"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}"/> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-single" if="netbeans.home" name="debug-single"/> + <target depends="init,compile-test-single" if="netbeans.home" name="-debug-start-debuggee-main-test"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}" classpath="${debug.test.classpath}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-main-test,-debug-start-debuggee-main-test" if="netbeans.home" name="debug-test-with-main"/> + <target depends="init" name="-pre-debug-fix"> + <fail unless="fix.includes">Must set fix.includes</fail> + <property name="javac.includes" value="${fix.includes}.java"/> + </target> + <target depends="init,-pre-debug-fix,compile-single" if="netbeans.home" name="-do-debug-fix"> + <j2seproject1:nbjpdareload/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix" if="netbeans.home" name="debug-fix"/> + <!-- + ================= + PROFILING SECTION + ================= + --> + <target depends="profile-init,compile" description="Profile a project in the IDE." if="netbeans.home" name="profile"> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile/> + </target> + <target depends="profile-init,compile-single" description="Profile a selected class in the IDE." if="netbeans.home" name="profile-single"> + <fail unless="profile.class">Must select one file in the IDE or set profile.class</fail> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile classname="${profile.class}"/> + </target> + <!-- + ========================= + APPLET PROFILING SECTION + ========================= + --> + <target depends="profile-init,compile-single" if="netbeans.home" name="profile-applet"> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </profile> + </target> + <!-- + ========================= + TESTS PROFILING SECTION + ========================= + --> + <target depends="profile-init,compile-test-single" if="netbeans.home" name="profile-test-single"> + <nbprofiledirect> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + </nbprofiledirect> + <junit dir="${profiler.info.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" jvm="${profiler.info.jvm}" showoutput="true"> + <env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/> + <jvmarg value="${profiler.info.jvmargs.agent}"/> + <jvmarg line="${profiler.info.jvmargs}"/> + <test name="${profile.class}"/> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + </junit> + </target> + <!-- + =============== + JAVADOC SECTION + =============== + --> + <target depends="init" if="have.sources" name="-javadoc-build"> + <mkdir dir="${dist.javadoc.dir}"/> + <condition else="" property="javadoc.endorsed.classpath.cmd.line.arg" value="-J${endorsed.classpath.cmd.line.arg}"> + <and> + <isset property="endorsed.classpath.cmd.line.arg"/> + <not> + <equals arg1="${endorsed.classpath.cmd.line.arg}" arg2=""/> + </not> + </and> + </condition> + <javadoc additionalparam="${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}"> + <classpath> + <path path="${javac.classpath}"/> + </classpath> + <fileset dir="${src.dir}" excludes="*.java,${excludes}" includes="${includes}"> + <filename name="**/*.java"/> + </fileset> + <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="**/*.java"/> + <exclude name="*.java"/> + </fileset> + <arg line="${javadoc.endorsed.classpath.cmd.line.arg}"/> + </javadoc> + <copy todir="${dist.javadoc.dir}"> + <fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}"> + <filename name="**/doc-files/**"/> + </fileset> + <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="**/doc-files/**"/> + </fileset> + </copy> + </target> + <target depends="init,-javadoc-build" if="netbeans.home" name="-javadoc-browse" unless="no.javadoc.preview"> + <nbbrowse file="${dist.javadoc.dir}/index.html"/> + </target> + <target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/> + <!-- + ========================= + JUNIT COMPILATION SECTION + ========================= + --> + <target depends="init,compile" if="have.tests" name="-pre-pre-compile-test"> + <mkdir dir="${build.test.classes.dir}"/> + </target> + <target name="-pre-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-test-depend"> + <j2seproject3:depend classpath="${javac.test.classpath}" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> + </target> + <target depends="init,deps-jar,compile,-pre-pre-compile-test,-pre-compile-test,-compile-test-depend" if="have.tests" name="-do-compile-test"> + <j2seproject3:javac apgeneratedsrcdir="${build.test.classes.dir}" classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" processorpath="${javac.test.processorpath}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-do-compile-test,-post-compile-test" name="compile-test"/> + <target name="-pre-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,compile,-pre-pre-compile-test,-pre-compile-test-single" if="have.tests" name="-do-compile-test-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile destdir="${build.test.classes.dir}"/> + <j2seproject3:javac apgeneratedsrcdir="${build.test.classes.dir}" classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" excludes="" includes="${javac.includes}" processorpath="${javac.test.processorpath}" sourcepath="${test.src.dir}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single,-do-compile-test-single,-post-compile-test-single" name="compile-test-single"/> + <!-- + ======================= + JUNIT EXECUTION SECTION + ======================= + --> + <target depends="init" if="have.tests" name="-pre-test-run"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run"> + <j2seproject3:junit testincludes="**/*Test.java"/> + </target> + <target depends="init,compile-test,-pre-test-run,-do-test-run" if="have.tests" name="-post-test-run"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init" if="have.tests" name="test-report"/> + <target depends="init" if="netbeans.home+have.tests" name="-test-browse"/> + <target depends="init,compile-test,-pre-test-run,-do-test-run,test-report,-post-test-run,-test-browse" description="Run unit tests." name="test"/> + <target depends="init" if="have.tests" name="-pre-test-run-single"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single"> + <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> + <j2seproject3:junit excludes="" includes="${test.includes}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single" if="have.tests" name="-post-test-run-single"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single,-post-test-run-single" description="Run single unit test." name="test-single"/> + <!-- + ======================= + JUNIT DEBUGGING SECTION + ======================= + --> + <target depends="init,compile-test" if="have.tests" name="-debug-start-debuggee-test"> + <fail unless="test.class">Must select one file in the IDE or set test.class</fail> + <property location="${build.test.results.dir}/TEST-${test.class}.xml" name="test.report.file"/> + <delete file="${test.report.file}"/> + <mkdir dir="${build.test.results.dir}"/> + <j2seproject3:debug classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" classpath="${ant.home}/lib/ant.jar:${ant.home}/lib/ant-junit.jar:${debug.test.classpath}"> + <customize> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <arg value="${test.class}"/> + <arg value="showoutput=true"/> + <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"/> + <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.report.file}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-test" if="netbeans.home+have.tests" name="-debug-start-debugger-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${test.class}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test" name="debug-test"/> + <target depends="init,-pre-debug-fix,compile-test-single" if="netbeans.home" name="-do-debug-fix-test"> + <j2seproject1:nbjpdareload dir="${build.test.classes.dir}"/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix-test" if="netbeans.home" name="debug-fix-test"/> + <!-- + ========================= + APPLET EXECUTION SECTION + ========================= + --> + <target depends="init,compile-single" name="run-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject1:java classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject1:java> + </target> + <!-- + ========================= + APPLET DEBUGGING SECTION + ========================= + --> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject3:debug classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-applet" if="netbeans.home" name="debug-applet"/> + <!-- + =============== + CLEANUP SECTION + =============== + --> + <target name="-deps-clean-init" unless="built-clean.properties"> + <property location="${build.dir}/built-clean.properties" name="built-clean.properties"/> + <delete file="${built-clean.properties}" quiet="true"/> + </target> + <target if="already.built.clean.${basedir}" name="-warn-already-built-clean"> + <echo level="warn" message="Cycle detected: Essentials2Compat was already built"/> + </target> + <target depends="init,-deps-clean-init" name="deps-clean" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-clean.properties}" verbose="false"/> + <property file="${built-clean.properties}" prefix="already.built.clean."/> + <antcall target="-warn-already-built-clean"/> + <propertyfile file="${built-clean.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-clean.properties}"/> + <param location="${project.Essentials}" name="call.subproject"/> + <param location="${project.Essentials}/build.xml" name="call.script"/> + <param name="call.target" value="clean"/> + <param name="transfer.built-clean.properties" value="${built-clean.properties}"/> + </antcall> + </target> + <target depends="init" name="-do-clean"> + <delete dir="${build.dir}"/> + <delete dir="${dist.dir}" followsymlinks="false" includeemptydirs="true"/> + </target> + <target name="-post-clean"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-clean,-do-clean,-post-clean" description="Clean build products." name="clean"/> + <target name="-check-call-dep"> + <property file="${call.built.properties}" prefix="already.built."/> + <condition property="should.call.dep"> + <not> + <isset property="already.built.${call.subproject}"/> + </not> + </condition> + </target> + <target depends="-check-call-dep" if="should.call.dep" name="-maybe-call-dep"> + <ant antfile="${call.script}" inheritall="false" target="${call.target}"> + <propertyset> + <propertyref prefix="transfer."/> + <mapper from="transfer.*" to="*" type="glob"/> + </propertyset> + </ant> + </target> +</project> diff --git a/Essentials2Compat/nbproject/genfiles.properties b/Essentials2Compat/nbproject/genfiles.properties new file mode 100644 index 000000000..ab97b0ef6 --- /dev/null +++ b/Essentials2Compat/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=cfe919e8 +build.xml.script.CRC32=ec95d082 +build.xml.stylesheet.CRC32=28e38971@1.50.1.46 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=cfe919e8 +nbproject/build-impl.xml.script.CRC32=9b7e0383 +nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.1.46 diff --git a/Essentials2Compat/nbproject/project.properties b/Essentials2Compat/nbproject/project.properties new file mode 100644 index 000000000..99a18a932 --- /dev/null +++ b/Essentials2Compat/nbproject/project.properties @@ -0,0 +1,126 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=Essentials2Compat +application.vendor= +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=2 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=2 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=2 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=120 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAnnotationArgs=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineArrayInit=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAssignment=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineBinaryOp=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineCallArgs=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineDisjunctiveCatchTypes=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineFor=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineImplements=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineMethodParams=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineParenthesized=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTernaryOp=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineThrows=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTryResources=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesBeforeClass=2 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.classDeclBracePlacement=NEW_LINE +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs=false +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder=* +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width=4 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.methodDeclBracePlacement=NEW_LINE +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.otherBracePlacement=NEW_LINE +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeCatchOnNewLine=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeElseOnNewLine=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeFinallyOnNewLine=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeWhileOnNewLine=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.separateImportGroups=false +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab=4 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size=4 +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/Essentials2Compat.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.bukkit.jar=../lib/bukkit.jar +includes=** +jar.archive.disabled=${jnlp.enabled} +jar.compress=true +jar.index=${jnlp.enabled} +javac.classpath=\ + ${file.reference.bukkit.jar}:\ + ${reference.Essentials.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=no.codebase +jnlp.descriptor=application +jnlp.enabled=false +jnlp.mixed.code=default +jnlp.offline-allowed=false +jnlp.signed=false +jnlp.signing= +jnlp.signing.alias= +jnlp.signing.keystore= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +project.Essentials=../Essentials +reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/Essentials2Compat/nbproject/project.xml b/Essentials2Compat/nbproject/project.xml new file mode 100644 index 000000000..244dc59a9 --- /dev/null +++ b/Essentials2Compat/nbproject/project.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://www.netbeans.org/ns/project/1"> + <type>org.netbeans.modules.java.j2seproject</type> + <configuration> + <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> + <name>Essentials2Compat</name> + <source-roots> + <root id="src.dir"/> + </source-roots> + <test-roots> + <root id="test.src.dir"/> + </test-roots> + </data> + <libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1"> + <definitions>../lib/nblibraries.properties</definitions> + </libraries> + <references xmlns="http://www.netbeans.org/ns/ant-project-references/1"> + <reference> + <foreign-project>Essentials</foreign-project> + <artifact-type>jar</artifact-type> + <script>build.xml</script> + <target>jar</target> + <clean-target>clean</clean-target> + <id>jar</id> + </reference> + </references> + </configuration> +</project> diff --git a/Essentials2Compat/src/com/earth2me/essentials/Essentials.java b/Essentials2Compat/src/com/earth2me/essentials/Essentials.java new file mode 100644 index 000000000..dc612e8d6 --- /dev/null +++ b/Essentials2Compat/src/com/earth2me/essentials/Essentials.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + + +public class Essentials extends JavaPlugin +{ + @Override + public void onEnable() + { + Bukkit.getLogger().info("You can remove this compatibility plugin, when all plugins are updated to Essentials 3"); + //TODO: Update files to new 3.0 format + //TODO: Move Eco Api here + } + + @Override + public void onDisable() + { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsConf.java b/Essentials2Compat/src/com/earth2me/essentials/EssentialsConf.java index 35252532f..3a37f04b0 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsConf.java +++ b/Essentials2Compat/src/com/earth2me/essentials/EssentialsConf.java @@ -16,7 +16,7 @@ import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.util.config.Configuration; - +@Deprecated public class EssentialsConf extends Configuration { private static final Logger LOGGER = Logger.getLogger("Minecraft"); diff --git a/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java b/Essentials2Compat/src/com/earth2me/essentials/EssentialsUpgrade.java index ae444af2e..05a5d4797 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java +++ b/Essentials2Compat/src/com/earth2me/essentials/EssentialsUpgrade.java @@ -1,9 +1,10 @@ package com.earth2me.essentials; +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; 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; @@ -17,7 +18,7 @@ import org.bukkit.Material; import org.bukkit.World; import org.bukkit.inventory.ItemStack; - +@Deprecated public class EssentialsUpgrade { private final static Logger LOGGER = Logger.getLogger("Minecraft"); @@ -50,7 +51,7 @@ public class EssentialsUpgrade } final EssentialsConf conf = new EssentialsConf(configFile); conf.load(); - final Worth worth = new Worth(ess.getDataFolder()); + final Worth worth = new Worth(ess); boolean found = false; for (Material mat : Material.values()) { @@ -372,7 +373,7 @@ public class EssentialsUpgrade doneFile.save(); } - private void moveUsersDataToUserdataFolder() + /*private void moveUsersDataToUserdataFolder() { final File usersFile = new File(ess.getDataFolder(), "users.yml"); if (!usersFile.exists()) @@ -418,7 +419,7 @@ public class EssentialsUpgrade } } usersFile.renameTo(new File(usersFile.getAbsolutePath() + ".old")); - } + }*/ private void convertWarps() { @@ -561,7 +562,7 @@ public class EssentialsUpgrade } } - private void sanitizeAllUserFilenames() + /*private void sanitizeAllUserFilenames() { if (doneFile.getBoolean("sanitizeAllUserFilenames", false)) { @@ -604,7 +605,7 @@ public class EssentialsUpgrade } doneFile.setProperty("sanitizeAllUserFilenames", true); doneFile.save(); - } + }*/ private World getFakeWorld(final String name) { @@ -791,9 +792,10 @@ public class EssentialsUpgrade public void afterSettings() { - sanitizeAllUserFilenames(); + //TODO? + //sanitizeAllUserFilenames(); updateUsersToNewDefaultHome(); - moveUsersDataToUserdataFolder(); + //moveUsersDataToUserdataFolder(); convertWarps(); updateUsersPowerToolsFormat(); updateUsersHomesFormat(); diff --git a/Essentials2Compat/src/plugin.yml b/Essentials2Compat/src/plugin.yml new file mode 100644 index 000000000..e3d9afe83 --- /dev/null +++ b/Essentials2Compat/src/plugin.yml @@ -0,0 +1,6 @@ +name: Essentials +main: com.earth2me.essentials.Essentials +version: 2.9 +website: http://tiny.cc/EssentialsWiki +description: Compatibility plugin for older plugins +authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits] diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java b/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java index 38239abfe..bd6a9adab 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java @@ -1,25 +1,25 @@ package com.earth2me.essentials.chat; -import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; public class ChatStore { - private final User user; - private final String type; - private final Trade charge; + private final transient IUser user; + private final transient String type; + private final transient Trade charge; private long radius; - ChatStore(final IEssentials ess, final User user, final String type) + ChatStore(final IEssentials ess, final IUser user, final String type) { this.user = user; this.type = type; this.charge = new Trade(getLongType(), ess); } - public User getUser() + public IUser getUser() { return user; } @@ -34,7 +34,7 @@ public class ChatStore return type; } - public String getLongType() + public final String getLongType() { return type.length() > 0 ? "chat" : "chat-" + type; } @@ -44,7 +44,7 @@ public class ChatStore return radius; } - public void setRadius(long radius) + public void setRadius(final long radius) { this.radius = radius; } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java index 21a71f046..3035a75f0 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java @@ -1,10 +1,12 @@ package com.earth2me.essentials.chat; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.chat.listenerlevel.EssentialsChatPlayerListenerHighest; +import com.earth2me.essentials.chat.listenerlevel.EssentialsChatPlayerListenerLowest; +import com.earth2me.essentials.chat.listenerlevel.EssentialsChatPlayerListenerNormal; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.ConcurrentSkipListMap; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.event.Event.Priority; @@ -17,7 +19,6 @@ import org.bukkit.plugin.java.JavaPlugin; public class EssentialsChat extends JavaPlugin { private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private transient Map<String, IEssentialsChatListener> chatListener; @Override public void onEnable() @@ -34,35 +35,23 @@ public class EssentialsChat extends JavaPlugin return; } - chatListener = new ConcurrentSkipListMap<String, IEssentialsChatListener>(); - final Map<PlayerChatEvent, ChatStore> chatStore = new HashMap<PlayerChatEvent, ChatStore>(); + final Map<PlayerChatEvent, String> charges = new HashMap<PlayerChatEvent, String>(); - final EssentialsChatPlayerListenerLowest playerListenerLowest = new EssentialsChatPlayerListenerLowest(getServer(), ess, chatListener, chatStore); - final EssentialsChatPlayerListenerNormal playerListenerNormal = new EssentialsChatPlayerListenerNormal(getServer(), ess, chatListener, chatStore); - final EssentialsChatPlayerListenerHighest playerListenerHighest = new EssentialsChatPlayerListenerHighest(getServer(), ess, chatListener, chatStore); - pluginManager.registerEvents(playerListenerLowest, this); - pluginManager.registerEvents(playerListenerNormal, this); - pluginManager.registerEvents(playerListenerHighest, this); + final EssentialsChatPlayerListenerLowest playerListenerLowest = new EssentialsChatPlayerListenerLowest(getServer(), ess); + final EssentialsChatPlayerListenerNormal playerListenerNormal = new EssentialsChatPlayerListenerNormal(getServer(), ess, charges); + final EssentialsChatPlayerListenerHighest playerListenerHighest = new EssentialsChatPlayerListenerHighest(getServer(), ess, charges); + final EssentialsLocalChatEventListener localChatListener = new EssentialsLocalChatEventListener(getServer(), ess); + pluginManager.registerEvent(Type.PLAYER_CHAT, playerListenerLowest, Priority.Lowest, this); + pluginManager.registerEvent(Type.PLAYER_CHAT, playerListenerNormal, Priority.Normal, this); + pluginManager.registerEvent(Type.PLAYER_CHAT, playerListenerHighest, Priority.Highest, this); + pluginManager.registerEvent(Type.CUSTOM_EVENT, localChatListener, Priority.Highest, this); + LOGGER.info(_("loadinfo", this.getDescription().getName(), this.getDescription().getVersion(), "essentials team")); } @Override public void onDisable() { - if (chatListener != null) - { - chatListener.clear(); - } - } - - public void addEssentialsChatListener(final String plugin, final IEssentialsChatListener listener) - { - chatListener.put(plugin, listener); - } - - public IEssentialsChatListener removeEssentialsChatListener(final String plugin) - { - return chatListener.remove(plugin); } } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java index ddf928725..d55cfe9cb 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java @@ -2,156 +2,180 @@ package com.earth2me.essentials.chat; 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.api.IEssentials; +import com.earth2me.essentials.api.ISettings; +import com.earth2me.essentials.api.IUser; +import java.util.Locale; import java.util.Map; import java.util.logging.Logger; -import org.bukkit.Location; import org.bukkit.Server; -import org.bukkit.World; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChatEvent; +import org.bukkit.event.player.PlayerListener; //TODO: Translate the local/spy tags -public abstract class EssentialsChatPlayer implements Listener +public abstract class EssentialsChatPlayer extends PlayerListener { protected transient IEssentials ess; protected final static Logger logger = Logger.getLogger("Minecraft"); - protected final transient Map<String, IEssentialsChatListener> listeners; - protected final transient Server server; - protected final transient Map<PlayerChatEvent, ChatStore> chatStorage; - - public EssentialsChatPlayer(final Server server, - final IEssentials ess, - final Map<String, IEssentialsChatListener> listeners, - final Map<PlayerChatEvent, ChatStore> chatStorage) + protected final transient Server server; + + public EssentialsChatPlayer(final Server server, final IEssentials ess) { this.ess = ess; - this.listeners = listeners; this.server = server; - this.chatStorage = chatStorage; } + @Override public void onPlayerChat(final PlayerChatEvent event) { } public boolean isAborted(final PlayerChatEvent event) { + return isAborted(event, "chat"); + } + + public boolean isAborted(final PlayerChatEvent event, final String command) + { if (event.isCancelled()) { return true; } - for (IEssentialsChatListener listener : listeners.values()) + + final IUser user = ess.getUser(event.getPlayer()); + if (!isAffordableFor(user, command)) { - if (listener.shouldHandleThisChat(event)) - { - return true; - } + event.setCancelled(true); + return true; } return false; } + + protected void chargeChat (final PlayerChatEvent event, final Map<PlayerChatEvent, String> charges) { + + final IUser user = ess.getUser(event.getPlayer()); + + String charge = charges.remove(event); + if (charge == null) + { + charge = "chat"; + } - public String getChatType(final String message) - { - switch (message.charAt(0)) + try { - case '!': - return "shout"; - case '?': - return "question"; - default: - return ""; + charge(user, charge); + } + catch (ChargeException e) + { + ess.getCommandHandler().showCommandError(user, charge, e); + event.setCancelled(true); } } - public ChatStore getChatStore(final PlayerChatEvent event) - { - return chatStorage.get(event); - } - - public void setChatStore(final PlayerChatEvent event, final ChatStore chatStore) + protected void charge(final CommandSender sender, final String command) throws ChargeException { - chatStorage.put(event, chatStore); + if (sender instanceof Player) + { + final Trade charge = new Trade(command, ess); + charge.charge(ess.getUser((Player)sender)); + } } - public ChatStore delChatStore(final PlayerChatEvent event) + protected boolean isAffordableFor(final CommandSender sender, final String command) { - return chatStorage.remove(event); - } + if (sender instanceof Player) + { + try + { + final Trade charge = new Trade(command, ess); + charge.isAffordableFor(ess.getUser((Player)sender)); + } + catch (ChargeException e) + { + return false; + } + } + else + { + return false; + } - protected void charge(final User user, final Trade charge) throws ChargeException - { - charge.charge(user); + return true; } - protected boolean charge(final PlayerChatEvent event, final ChatStore chatStore) + protected void formatChat(final PlayerChatEvent event) { - try + final IUser user = ess.getUser(event.getPlayer()); + if (user.isAuthorized("essentials.chat.color")) { - charge(chatStore.getUser(), chatStore.getCharge()); + event.setMessage(event.getMessage().replaceAll("&([0-9a-f])", "\u00a7$1")); } - catch (ChargeException e) + String format = ess.getGroups().getChatFormat(user); + event.setFormat(format.replace('&', '\u00a7').replace("\u00a7\u00a7", "&").replace("{DISPLAYNAME}", "%1$s").replace("{GROUP}", user.getGroup()).replace("{MESSAGE}", "%2$s").replace("{WORLDNAME}", user.getWorld().getName()).replace("{SHORTWORLDNAME}", user.getWorld().getName().substring(0, 1).toUpperCase(Locale.ENGLISH))); + } + + protected String getChatType(final String message) + { + switch (message.charAt(0)) { - ess.showError(chatStore.getUser(), e, chatStore.getLongType()); - event.setCancelled(true); - return false; + case '!': + return "shout"; + case '?': + return "question"; + //case '@': + // return "admin"; + default: + return ""; } - return true; } - protected void sendLocalChat(final PlayerChatEvent event, final ChatStore chatStore) + protected void handleLocalChat(final Map<PlayerChatEvent, String> charges, final PlayerChatEvent event) { - event.setCancelled(true); - final User sender = chatStore.getUser(); - logger.info(_("localFormat", sender.getName(), event.getMessage())); - final Location loc = sender.getLocation(); - final World world = loc.getWorld(); - - if (charge(event, chatStore) == false) - { - return; + long radius = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try { + radius = settings.getData().getChat().getLocalRadius(); + } finally { + settings.unlock(); } + radius *= radius; + + final IUser user = ess.getUser(event.getPlayer()); + final String chatType = getChatType(event.getMessage()); + final StringBuilder command = new StringBuilder(); + command.append("chat"); - for (Player onlinePlayer : server.getOnlinePlayers()) + if (event.getMessage().length() > 0 && chatType.length() > 0) { - String type = _("chatTypeLocal"); - final User onlineUser = ess.getUser(onlinePlayer); - //TODO: remove reference to op - if (onlineUser.isIgnoredPlayer(sender.getName()) && !sender.isOp()) - { - continue; - } - if (!onlineUser.equals(sender)) - { - final Location playerLoc = onlineUser.getLocation(); - if (playerLoc.getWorld() != world) - { - continue; - } - final double delta = playerLoc.distanceSquared(loc); - - if (delta > chatStore.getRadius()) - { - if (onlineUser.isAuthorized("essentials.chat.spy")) - { - type = type.concat(_("chatTypeSpy")); - } - else - { - continue; - } - } - } + command.append("-").append(chatType); + final StringBuilder permission = new StringBuilder(); + permission.append("essentials.chat.").append(chatType); + + final StringBuilder format = new StringBuilder(); + format.append(chatType).append("Format"); + + final StringBuilder errorMsg = new StringBuilder(); + errorMsg.append("notAllowedTo").append(chatType.substring(0, 1).toUpperCase(Locale.ENGLISH)).append(chatType.substring(1)); - String message = String.format(event.getFormat(), type.concat(sender.getDisplayName()), event.getMessage()); - for (IEssentialsChatListener listener : listeners.values()) + if (user.isAuthorized(permission.toString())) { - message = listener.modifyMessage(event, onlinePlayer, message); + event.setMessage(event.getMessage().substring(1)); + event.setFormat(_(format.toString(), event.getFormat())); + charges.put(event, command.toString()); + return; } - onlineUser.sendMessage(message); + + user.sendMessage(_(errorMsg.toString())); + event.setCancelled(true); + return; } + + event.setCancelled(true); + final EssentialsLocalChatEvent localChat = new EssentialsLocalChatEvent(event, radius); + ess.getServer().getPluginManager().callEvent(localChat); } } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java deleted file mode 100644 index e8f785228..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.earth2me.essentials.chat; - -import com.earth2me.essentials.IEssentials; -import java.util.Map; -import org.bukkit.Server; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerChatEvent; - - -public class EssentialsChatPlayerListenerHighest extends EssentialsChatPlayer -{ - public EssentialsChatPlayerListenerHighest(final Server server, - final IEssentials ess, - final Map<String, IEssentialsChatListener> listeners, - final Map<PlayerChatEvent, ChatStore> chatStorage) - { - super(server, ess, listeners, chatStorage); - } - - @EventHandler(priority = EventPriority.HIGHEST) - @Override - public void onPlayerChat(final PlayerChatEvent event) - { - final ChatStore chatStore = delChatStore(event); - if (isAborted(event)) - { - return; - } - - /** - * This file should handle charging the user for the action before returning control back - */ - charge(event, chatStore); - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java deleted file mode 100644 index 5a8cde62d..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.earth2me.essentials.chat; - -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; -import com.earth2me.essentials.Util; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Server; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerChatEvent; - - -public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer -{ - public EssentialsChatPlayerListenerLowest(final Server server, - final IEssentials ess, - final Map<String, IEssentialsChatListener> listeners, - final Map<PlayerChatEvent, ChatStore> chatStorage) - { - super(server, ess, listeners, chatStorage); - } - - @EventHandler(priority = EventPriority.LOWEST) - @Override - public void onPlayerChat(final PlayerChatEvent event) - { - if (isAborted(event)) - { - return; - } - - final User user = ess.getUser(event.getPlayer()); - final ChatStore chatStore = new ChatStore(ess, user, getChatType(event.getMessage())); - setChatStore(event, chatStore); - - /** - * This listener should apply the general chat formatting only...then return control back the event handler - */ - if (user.isAuthorized("essentials.chat.color")) - { - event.setMessage(Util.replaceColor(event.getMessage())); - } - else - { - event.setMessage(Util.stripColor(event.getMessage())); - } - String group = user.getGroup(); - String world = user.getWorld().getName(); - event.setFormat(ess.getSettings().getChatFormat(group).format(new Object[] {group, world, world.substring(0, 1).toUpperCase(Locale.ENGLISH)})); - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java deleted file mode 100644 index fdaccdc8d..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.earth2me.essentials.chat; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Server; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerChatEvent; - - -public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer -{ - public EssentialsChatPlayerListenerNormal(final Server server, - final IEssentials ess, - final Map<String, IEssentialsChatListener> listeners, - final Map<PlayerChatEvent, ChatStore> chatStorage) - { - super(server, ess, listeners, chatStorage); - } - - @EventHandler(priority = EventPriority.NORMAL) - @Override - public void onPlayerChat(final PlayerChatEvent event) - { - if (isAborted(event)) - { - return; - } - - /** - * This file should handle detection of the local chat features... if local chat is enabled, we need to handle - * it here - */ - long radius = ess.getSettings().getChatRadius(); - if (radius < 1) - { - return; - } - radius *= radius; - - final ChatStore chatStore = getChatStore(event); - final User user = chatStore.getUser(); - chatStore.setRadius(radius); - - if (event.getMessage().length() > 1 && chatStore.getType().length() > 0) - { - final StringBuilder permission = new StringBuilder(); - permission.append("essentials.chat.").append(chatStore.getType()); - - if (user.isAuthorized(permission.toString())) - { - final StringBuilder format = new StringBuilder(); - format.append(chatStore.getType()).append("Format"); - event.setMessage(event.getMessage().substring(1)); - event.setFormat(_(format.toString(), event.getFormat())); - return; - } - - final StringBuilder errorMsg = new StringBuilder(); - errorMsg.append("notAllowedTo").append(chatStore.getType().substring(0, 1).toUpperCase(Locale.ENGLISH)).append(chatStore.getType().substring(1)); - - user.sendMessage(_(errorMsg.toString())); - event.setCancelled(true); - return; - } - - sendLocalChat(event, chatStore); - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEvent.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEvent.java new file mode 100644 index 000000000..fe605b89a --- /dev/null +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEvent.java @@ -0,0 +1,100 @@ +package com.earth2me.essentials.chat; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.player.PlayerChatEvent; + + +public class EssentialsLocalChatEvent extends Event implements Cancellable +{ + private Player player; + private String message; + private String format = "<%1$s> %2$s"; + private long radius; + private boolean cancelled = false; + private PlayerChatEvent parentEvent = null; + + public EssentialsLocalChatEvent(final Player player, final String message, final String format, final long radius) + { + super("EssLocalChat"); + this.player = player; + this.message = message; + this.format = format; + this.radius = radius; + } + + public EssentialsLocalChatEvent(final PlayerChatEvent event, final long radius) + { + this(event.getPlayer(), event.getMessage(), event.getFormat(), radius); + this.parentEvent = event; + } + + @Override + public boolean isCancelled() + { + return cancelled; + } + + @Override + public void setCancelled(final boolean cancel) + { + this.cancelled = cancel; + } + + public String getMessage() + { + return message; + } + + public void setMessage(final String message) + { + this.message = message; + } + + public void setPlayer(final Player player) + { + this.player = player; + } + + public Player getPlayer() + { + return player; + } + + public String getFormat() + { + return format; + } + + public void setFormat(final String format) + { + // Oh for a better way to do this! + try + { + String.format(format, player, message); + } + catch (RuntimeException ex) + { + ex.fillInStackTrace(); + throw ex; + } + + this.format = format; + } + + public long getRadius() + { + return radius; + } + + public void setRadius(final long radius) + { + this.radius = radius; + } + + public PlayerChatEvent getParentEvent() + { + return parentEvent; + } +}
\ No newline at end of file diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEventListener.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEventListener.java new file mode 100644 index 000000000..135bfa81f --- /dev/null +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEventListener.java @@ -0,0 +1,77 @@ +package com.earth2me.essentials.chat; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.CustomEventListener; +import org.bukkit.event.Event; +import org.bukkit.event.Listener; + +public class EssentialsLocalChatEventListener extends CustomEventListener implements Listener { + + + protected transient IEssentials ess; + protected final transient Server server; + + public EssentialsLocalChatEventListener(final Server server, final IEssentials ess) + { + this.ess = ess; + this.server = server; + } + + public void onLocalChat(final EssentialsLocalChatEvent event) { + final Player sender = event.getPlayer(); + if (event.getRadius() < 1) + { + return; + } + event.setCancelled(true); + final Location loc = sender.getLocation(); + final World world = loc.getWorld(); + + for (Player onlinePlayer : server.getOnlinePlayers()) + { + String type = "[L]"; + final IUser user = ess.getUser(onlinePlayer); + //TODO: remove reference to op + if (user.isIgnoringPlayer(sender.getName()) && !sender.isOp()) + { + continue; + } + if (!user.equals(sender)) + { + final Location playerLoc = user.getLocation(); + if (playerLoc.getWorld() != world) + { + continue; + } + final double delta = playerLoc.distanceSquared(loc); + + if (delta > event.getRadius()) + { + if (user.isAuthorized("essentials.chat.spy")) + { + type = type.concat("[Spy]"); + } + else + { + continue; + } + } + } + + final String message = String.format(event.getFormat(), type.concat(sender.getDisplayName()), event.getMessage()); + user.sendMessage(message); + } + } + + @Override + public void onCustomEvent(final Event event) { + if (event instanceof EssentialsLocalChatEvent) { + onLocalChat((EssentialsLocalChatEvent) event); + } + } +}
\ No newline at end of file diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/IEssentialsChatListener.java b/EssentialsChat/src/com/earth2me/essentials/chat/IEssentialsChatListener.java deleted file mode 100644 index 5c9c5c219..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/IEssentialsChatListener.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.chat; - -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerChatEvent; - - -public interface IEssentialsChatListener -{ - boolean shouldHandleThisChat(PlayerChatEvent event); - - String modifyMessage(PlayerChatEvent event, Player target, String message); -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java new file mode 100644 index 000000000..7868f2295 --- /dev/null +++ b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.chat.listenerlevel; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.chat.EssentialsChatPlayer; +import java.util.Map; +import org.bukkit.Server; +import org.bukkit.event.player.PlayerChatEvent; + + +public class EssentialsChatPlayerListenerHighest extends EssentialsChatPlayer +{ + private final transient Map<PlayerChatEvent, String> charges; + + public EssentialsChatPlayerListenerHighest(final Server server, + final IEssentials ess, + final Map<PlayerChatEvent, String> charges) + { + super(server, ess); + this.charges = charges; + } + + @Override + public void onPlayerChat(final PlayerChatEvent event) + { + if (isAborted(event)) + { + return; + } + + chargeChat(event, charges); + } +} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java new file mode 100644 index 000000000..37394c3e6 --- /dev/null +++ b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java @@ -0,0 +1,26 @@ +package com.earth2me.essentials.chat.listenerlevel; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.chat.EssentialsChatPlayer; +import org.bukkit.Server; +import org.bukkit.event.player.PlayerChatEvent; + + +public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer +{ + public EssentialsChatPlayerListenerLowest(final Server server, final IEssentials ess) + { + super(server, ess); + } + + @Override + public void onPlayerChat(final PlayerChatEvent event) + { + if (isAborted(event)) + { + return; + } + + formatChat(event); + } +}
\ No newline at end of file diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java new file mode 100644 index 000000000..c1a9968ef --- /dev/null +++ b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.chat.listenerlevel; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.chat.EssentialsChatPlayer; +import java.util.Map; +import org.bukkit.Server; +import org.bukkit.event.player.PlayerChatEvent; + + +public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer +{ + private final transient Map<PlayerChatEvent, String> charges; + + public EssentialsChatPlayerListenerNormal(final Server server, + final IEssentials ess, + final Map<PlayerChatEvent, String> charges) + { + super(server, ess); + this.charges = charges; + } + + @Override + public void onPlayerChat(final PlayerChatEvent event) + { + if (isAborted(event)) + { + return; + } + + handleLocalChat(charges, event); + } +} diff --git a/EssentialsChat/src/plugin.yml b/EssentialsChat/src/plugin.yml index cc129f825..f6885521c 100644 --- a/EssentialsChat/src/plugin.yml +++ b/EssentialsChat/src/plugin.yml @@ -3,7 +3,7 @@ name: EssentialsChat main: com.earth2me.essentials.chat.EssentialsChat # Note to developers: This next line cannot change, or the automatic versioning system will break. version: TeamCity -website: http://www.earth2me.net:8001/ +website: http://tiny.cc/EssentialsWiki description: Provides chat control features for Essentials. Requires Permissions. authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits, Okamosy] depend: [Essentials] diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/ConfigHolder.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/ConfigHolder.java new file mode 100644 index 000000000..e2d82d644 --- /dev/null +++ b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/ConfigHolder.java @@ -0,0 +1,27 @@ +package com.earth2me.essentials.geoip; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.settings.geoip.GeoIP; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; +import org.bukkit.plugin.Plugin; + +public class ConfigHolder extends AsyncStorageObjectHolder<GeoIP> +{ + private final transient Plugin geoip; + + public ConfigHolder(final IEssentials ess, final Plugin geoip) + { + super(ess, GeoIP.class); + this.geoip = geoip; + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(geoip.getDataFolder(), "config.yml"); + } + +} diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java index eb401c6db..2fa8b0adf 100644 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java +++ b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java @@ -1,7 +1,7 @@ package com.earth2me.essentials.geoip; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.api.IEssentials; import java.util.logging.Level; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -31,9 +31,9 @@ public class EssentialsGeoIP extends JavaPlugin this.setEnabled(false); return; } - final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(getDataFolder(), ess); + final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(this, ess); pm.registerEvents(playerListener, this); - + ess.addReloadListener(playerListener); getLogger().log(Level.INFO, "This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com/."); } diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java index 0018d09b4..19cc06dc4 100644 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java +++ b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java @@ -1,10 +1,9 @@ package com.earth2me.essentials.geoip; -import com.earth2me.essentials.EssentialsConf; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IConf; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IReload; +import com.earth2me.essentials.api.IUser; import com.maxmind.geoip.Location; import com.maxmind.geoip.LookupService; import com.maxmind.geoip.regionName; @@ -21,157 +20,205 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.Plugin; -public class EssentialsGeoIPPlayerListener implements Listener, IConf +public class EssentialsGeoIPPlayerListener implements Listener, IReload { - LookupService ls = null; - private static final Logger logger = Logger.getLogger("Minecraft"); - File databaseFile; - File dataFolder; - EssentialsConf config; + private transient LookupService ls = null; + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private transient File databaseFile; + private final transient ConfigHolder config; private final transient IEssentials ess; + private final transient Plugin geoip; - public EssentialsGeoIPPlayerListener(File dataFolder, IEssentials ess) + public EssentialsGeoIPPlayerListener(final Plugin geoip, final IEssentials ess) { + super(); this.ess = ess; - this.dataFolder = dataFolder; - this.config = new EssentialsConf(new File(dataFolder, "config.yml")); - config.setTemplateName("/config.yml", EssentialsGeoIP.class); - reloadConfig(); + this.geoip = geoip; + this.config = new ConfigHolder(ess, geoip); + onReload(); } @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(PlayerJoinEvent event) + public void onPlayerJoin(final PlayerJoinEvent event) { - User u = ess.getUser(event.getPlayer()); + final IUser u = ess.getUser(event.getPlayer()); if (u.isAuthorized("essentials.geoip.hide")) { return; } - InetAddress address = event.getPlayer().getAddress().getAddress(); - StringBuilder sb = new StringBuilder(); - if (config.getBoolean("database.show-cities", false)) + config.acquireReadLock(); + try { - Location loc = ls.getLocation(address); - if (loc == null) + final InetAddress address = event.getPlayer().getAddress().getAddress(); + final StringBuilder builder = new StringBuilder(); + if (config.getData().getDatabase().isShowCities()) { - return; + final Location loc = ls.getLocation(address); + if (loc == null) + { + return; + } + if (loc.city != null) + { + builder.append(loc.city).append(", "); + } + final String region = regionName.regionNameByCode(loc.countryCode, loc.region); + if (region != null) + { + builder.append(region).append(", "); + } + builder.append(loc.countryName); } - if (loc.city != null) + else { - sb.append(loc.city).append(", "); + builder.append(ls.getCountry(address).getName()); } - String region = regionName.regionNameByCode(loc.countryCode, loc.region); - if (region != null) + if (config.getData().isShowOnWhois()) { - sb.append(region).append(", "); + u.acquireWriteLock(); + try + { + u.getData().setGeolocation(builder.toString()); + } + finally + { + u.unlock(); + } } - sb.append(loc.countryName); - } - else - { - sb.append(ls.getCountry(address).getName()); - } - if (config.getBoolean("show-on-whois", true)) - { - u.setGeoLocation(sb.toString()); - } - if (config.getBoolean("show-on-login", true) && !u.isHidden()) - { - for (Player player : event.getPlayer().getServer().getOnlinePlayers()) + if (config.getData().isShowOnLogin() && !u.isHidden()) { - User user = ess.getUser(player); - if (user.isAuthorized("essentials.geoip.show")) + for (Player player : event.getPlayer().getServer().getOnlinePlayers()) { - user.sendMessage(_("geoipJoinFormat", u.getDisplayName(), sb.toString())); + final IUser user = ess.getUser(player); + if (user.isAuthorized("essentials.geoip.show")) + { + user.sendMessage(_("geoipJoinFormat", user.getDisplayName(), builder.toString())); + } } } } + finally + { + config.unlock(); + } } @Override - public final void reloadConfig() + public final void onReload() { - config.load(); - - if (config.getBoolean("database.show-cities", false)) - { - databaseFile = new File(dataFolder, "GeoIPCity.dat"); - } - else - { - databaseFile = new File(dataFolder, "GeoIP.dat"); - } - if (!databaseFile.exists()) + config.onReload(); + config.acquireReadLock(); + try { - if (config.getBoolean("database.download-if-missing", true)) + if (config.getData().getDatabase().isShowCities()) { - downloadDatabase(); + databaseFile = new File(geoip.getDataFolder(), "GeoIPCity.dat"); } else { - logger.log(Level.SEVERE, _("cantFindGeoIpDB")); - return; + databaseFile = new File(geoip.getDataFolder(), "GeoIP.dat"); + } + if (!databaseFile.exists()) + { + if (config.getData().getDatabase().isDownloadIfMissing()) + { + if (config.getData().getDatabase().isShowCities()) + { + downloadDatabase(config.getData().getDatabase().getDownloadUrlCity()); + } + else + { + downloadDatabase(config.getData().getDatabase().getDownloadUrl()); + } + } + else + { + LOGGER.log(Level.SEVERE, _("cantFindGeoIpDB")); + return; + } + } + try + { + ls = new LookupService(databaseFile); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, _("cantReadGeoIpDB"), ex); } } - try - { - ls = new LookupService(databaseFile); - } - catch (IOException ex) + finally { - logger.log(Level.SEVERE, _("cantReadGeoIpDB"), ex); + config.unlock(); } } - private void downloadDatabase() + private void downloadDatabase(final String url) { + if (url == null || url.isEmpty()) + { + LOGGER.log(Level.SEVERE, _("geoIpUrlEmpty")); + return; + } + InputStream input = null; + OutputStream output = null; try { - String url; - if (config.getBoolean("database.show-cities", false)) - { - url = config.getString("database.download-url-city"); - } - else - { - url = config.getString("database.download-url"); - } - if (url == null || url.isEmpty()) - { - logger.log(Level.SEVERE, _("geoIpUrlEmpty")); - return; - } - logger.log(Level.INFO, _("downloadingGeoIp")); - URL downloadUrl = new URL(url); - URLConnection conn = downloadUrl.openConnection(); + LOGGER.log(Level.INFO, _("downloadingGeoIp")); + final URL downloadUrl = new URL(url); + final URLConnection conn = downloadUrl.openConnection(); conn.setConnectTimeout(10000); conn.connect(); - InputStream input = conn.getInputStream(); + input = conn.getInputStream(); if (url.endsWith(".gz")) { input = new GZIPInputStream(input); } - OutputStream output = new FileOutputStream(databaseFile); - byte[] buffer = new byte[2048]; + output = new FileOutputStream(databaseFile); + final byte[] buffer = new byte[2048]; int length = input.read(buffer); while (length >= 0) { output.write(buffer, 0, length); length = input.read(buffer); } - output.close(); input.close(); + output.close(); } catch (MalformedURLException ex) { - logger.log(Level.SEVERE, _("geoIpUrlInvalid"), ex); - return; + LOGGER.log(Level.SEVERE, _("geoIpUrlInvalid"), ex); } catch (IOException ex) { - logger.log(Level.SEVERE, _("connectionFailed"), ex); + LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); + } + finally + { + if (output != null) + { + try + { + output.close(); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); + } + } + if (input != null) + { + try + { + input.close(); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); + } + } } } } diff --git a/EssentialsGeoIP/src/plugin.yml b/EssentialsGeoIP/src/plugin.yml index 92fdc9963..ebdc3a97f 100644 --- a/EssentialsGeoIP/src/plugin.yml +++ b/EssentialsGeoIP/src/plugin.yml @@ -3,7 +3,7 @@ name: EssentialsGeoIP main: com.earth2me.essentials.geoip.EssentialsGeoIP # Note to developers: This next line cannot change, or the automatic versioning system will break. version: TeamCity -website: http://www.earth2me.net:8001/ +website: http://tiny.cc/EssentialsWiki description: Shows the country or city of a user on login and /whois. authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology] depend: [Essentials]
\ No newline at end of file diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/BlockBreakPermissions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/BlockBreakPermissions.java new file mode 100644 index 000000000..74ebe38dc --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/BlockBreakPermissions.java @@ -0,0 +1,43 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.api.IPermission; +import com.earth2me.essentials.perm.AbstractSuperpermsPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + +public class BlockBreakPermissions extends AbstractSuperpermsPermission{ + private static Map<Material,IPermission> permissions = new EnumMap<Material, IPermission>(Material.class); + private static final String base = "essentials.protect.blockbreak."; + private final String permission; + + public static IPermission getPermission(Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) { + perm = new BlockBreakPermissions(mat.toString().toLowerCase(Locale.ENGLISH)); + permissions.put(mat, perm); + } + return perm; + } + + private BlockBreakPermissions(String matName) + { + this.permission = base + matName; + } + + @Override + public String getPermission() + { + return this.permission; + } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } +} + diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/BlockPlacePermissions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/BlockPlacePermissions.java new file mode 100644 index 000000000..23ce7e053 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/BlockPlacePermissions.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.api.IPermission; +import com.earth2me.essentials.perm.AbstractSuperpermsPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + +public class BlockPlacePermissions extends AbstractSuperpermsPermission{ + private static Map<Material,IPermission> permissions = new EnumMap<Material, IPermission>(Material.class); + private static final String base = "essentials.protect.blockplace."; + private final String permission; + + public static IPermission getPermission(Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) { + perm = new BlockPlacePermissions(mat.toString().toLowerCase(Locale.ENGLISH)); + permissions.put(mat, perm); + } + return perm; + } + + private BlockPlacePermissions(String matName) + { + this.permission = base + matName; + } + + @Override + public String getPermission() + { + return this.permission; + } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java index 7503c334c..5988bd06f 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java @@ -1,13 +1,13 @@ package com.earth2me.essentials.protect; -import com.earth2me.essentials.IConf; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IReload; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.protect.data.ProtectedBlockMemory; import com.earth2me.essentials.protect.data.ProtectedBlockMySQL; import com.earth2me.essentials.protect.data.ProtectedBlockSQLite; import java.beans.PropertyVetoException; -import static com.earth2me.essentials.I18n._; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Location; @@ -29,8 +29,9 @@ public class EssentialsConnect } ess = (IEssentials)essPlugin; protect = (IProtect)essProtect; + protect.setSettings(new ProtectHolder(ess)); ProtectReloader pr = new ProtectReloader(); - pr.reloadConfig(); + pr.onReload(); ess.addReloadListener(pr); } @@ -43,7 +44,7 @@ public class EssentialsConnect return ess; } - public void alert(final User user, final String item, final String type) + public void alert(final IUser user, final String item, final String type) { final Location loc = user.getLocation(); final String warnMessage = _("alertFormat", user.getName(), type, item, @@ -52,7 +53,7 @@ public class EssentialsConnect LOGGER.log(Level.WARNING, warnMessage); for (Player p : ess.getServer().getOnlinePlayers()) { - final User alertUser = ess.getUser(p); + final IUser alertUser = ess.getUser(p); if (alertUser.isAuthorized("essentials.protect.alerts")) { alertUser.sendMessage(warnMessage); @@ -61,62 +62,68 @@ public class EssentialsConnect } - private class ProtectReloader implements IConf + private class ProtectReloader implements IReload { @Override - public void reloadConfig() + public void onReload() { if (protect.getStorage() != null) { protect.getStorage().onPluginDeactivation(); } - for (ProtectConfig protectConfig : ProtectConfig.values()) - { - if (protectConfig.isList()) - { - protect.getSettingsList().put(protectConfig, ess.getSettings().getProtectList(protectConfig.getConfigName())); - } - else if (protectConfig.isString()) - { - protect.getSettingsString().put(protectConfig, ess.getSettings().getProtectString(protectConfig.getConfigName())); - } - else - { - protect.getSettingsBoolean().put(protectConfig, ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), protectConfig.getDefaultValueBoolean())); - } - } + /* + * for (ProtectConfig protectConfig : ProtectConfig.values()) { if (protectConfig.isList()) { + * protect.getSettingsList().put(protectConfig, + * ess.getSettings().getProtectList(protectConfig.getConfigName())); } else if (protectConfig.isString()) { + * protect.getSettingsString().put(protectConfig, + * ess.getSettings().getProtectString(protectConfig.getConfigName())); } else { + * protect.getSettingsBoolean().put(protectConfig, + * ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), + * protectConfig.getDefaultValueBoolean())); } + * + * } + */ - if (protect.getSettingString(ProtectConfig.datatype).equalsIgnoreCase("mysql")) + ProtectHolder settings = protect.getSettings(); + settings.acquireReadLock(); + try { - try - { - protect.setStorage(new ProtectedBlockMySQL( - protect.getSettingString(ProtectConfig.mysqlDB), - protect.getSettingString(ProtectConfig.dbUsername), - protect.getSettingString(ProtectConfig.dbPassword))); - } - catch (PropertyVetoException ex) + if (settings.getData().getDbtype().equalsIgnoreCase("mysql")) { - LOGGER.log(Level.SEVERE, null, ex); + try + { + protect.setStorage(new ProtectedBlockMySQL( + settings.getData().getDburl(), + settings.getData().getDbuser(), + settings.getData().getDbpassword())); + } + catch (PropertyVetoException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } } - } - else - { - try + else { - protect.setStorage(new ProtectedBlockSQLite("jdbc:sqlite:plugins/Essentials/EssentialsProtect.db")); + try + { + protect.setStorage(new ProtectedBlockSQLite("jdbc:sqlite:plugins/Essentials/EssentialsProtect.db")); + } + catch (PropertyVetoException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } } - catch (PropertyVetoException ex) + /*if (protect.getSettingBool(ProtectConfig.memstore)) { - LOGGER.log(Level.SEVERE, null, ex); - } + protect.setStorage(new ProtectedBlockMemory(protect.getStorage(), protect)); + }*/ + } - if (protect.getSettingBool(ProtectConfig.memstore)) + finally { - protect.setStorage(new ProtectedBlockMemory(protect.getStorage(), protect)); + settings.unlock(); } - } } } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java index 983ba0f80..75a462888 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java @@ -1,9 +1,6 @@ package com.earth2me.essentials.protect; import com.earth2me.essentials.protect.data.IProtectedBlock; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogRecord; @@ -18,11 +15,12 @@ public class EssentialsProtect extends JavaPlugin implements IProtect { private static final Logger LOGGER = Logger.getLogger("Minecraft"); private static com.mchange.v2.log.MLogger C3P0logger; - private final transient Map<ProtectConfig, Boolean> settingsBoolean = new EnumMap<ProtectConfig, Boolean>(ProtectConfig.class); - private final transient Map<ProtectConfig, String> settingsString = new EnumMap<ProtectConfig, String>(ProtectConfig.class); - private final transient Map<ProtectConfig, List<Integer>> settingsList = new EnumMap<ProtectConfig, List<Integer>>(ProtectConfig.class); + //private final transient Map<ProtectConfig, Boolean> settingsBoolean = new EnumMap<ProtectConfig, Boolean>(ProtectConfig.class); + //private final transient Map<ProtectConfig, String> settingsString = new EnumMap<ProtectConfig, String>(ProtectConfig.class); + //private final transient Map<ProtectConfig, List<Integer>> settingsList = new EnumMap<ProtectConfig, List<Integer>>(ProtectConfig.class); private transient IProtectedBlock storage = null; private transient EssentialsConnect ess = null; + private transient ProtectHolder settings = null; @Override public void onLoad() @@ -72,12 +70,12 @@ public class EssentialsProtect extends JavaPlugin implements IProtect LOGGER.log(Level.SEVERE, "Essentials not installed or failed to load. Essenials Protect is in emergency mode now."); } - @Override + /*@Override public boolean checkProtectionItems(final ProtectConfig list, final int id) { final List<Integer> itemList = settingsList.get(list); return itemList != null && !itemList.isEmpty() && itemList.contains(id); - } + }*/ @Override public IProtectedBlock getStorage() @@ -96,7 +94,7 @@ public class EssentialsProtect extends JavaPlugin implements IProtect return ess; } - public Map<ProtectConfig, Boolean> getSettingsBoolean() + /*public Map<ProtectConfig, Boolean> getSettingsBoolean() { return settingsBoolean; } @@ -123,7 +121,7 @@ public class EssentialsProtect extends JavaPlugin implements IProtect { final String str = settingsString.get(protectConfig); return str == null ? protectConfig.getDefaultValueString() : str; - } + }*/ public void onDisable() { @@ -140,4 +138,14 @@ public class EssentialsProtect extends JavaPlugin implements IProtect { } } + + public ProtectHolder getSettings() + { + return settings; + } + + public void setSettings(final ProtectHolder settings) + { + this.settings = settings; + } } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java index 8e5e9cca8..cdd0c2543 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java @@ -1,8 +1,8 @@ package com.earth2me.essentials.protect; 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.IUser; import com.earth2me.essentials.protect.data.IProtectedBlock; import java.util.ArrayList; import java.util.List; @@ -34,66 +34,74 @@ public class EssentialsProtectBlockListener implements Listener return; } - final User user = ess.getUser(event.getPlayer()); - - if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild()) + final IUser user = ess.getUser(event.getPlayer()); + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setCancelled(true); - return; - } + if (!user.isAuthorized(Permissions.BUILD)) + { + event.setCancelled(true); + return; + } - final Block blockPlaced = event.getBlockPlaced(); - final int id = blockPlaced.getTypeId(); + final Block blockPlaced = event.getBlockPlaced(); + final int id = blockPlaced.getTypeId(); - if (prot.checkProtectionItems(ProtectConfig.blacklist_placement, id) && !user.isAuthorized("essentials.protect.exemptplacement")) - { - event.setCancelled(true); - return; - } + if (!user.isAuthorized(BlockPlacePermissions.getPermission(blockPlaced.getType()))) + { + event.setCancelled(true); + return; + } - if (!user.hasPermission("essentials.protect.alerts.notrigger") - && prot.checkProtectionItems(ProtectConfig.alert_on_placement, id)) - { - prot.getEssentialsConnect().alert(user, blockPlaced.getType().toString(), _("alertPlaced")); - } + if (!user.hasPermission("essentials.protect.alerts.notrigger") && + settings.getData().getAlertOnPlacement().contains(blockPlaced.getType())) + { + prot.getEssentialsConnect().alert(user, blockPlaced.getType().toString(), _("alertPlaced")); + } - final Block below = blockPlaced.getRelative(BlockFace.DOWN); - if ((below.getType() == Material.RAILS || below.getType() == Material.POWERED_RAIL || below.getType() == Material.DETECTOR_RAIL) - && prot.getSettingBool(ProtectConfig.prevent_block_on_rail) - && isProtected(below, user)) - { - event.setCancelled(true); - return; - } + final Block below = blockPlaced.getRelative(BlockFace.DOWN); + if ((below.getType() == Material.RAILS || below.getType() == Material.POWERED_RAIL || below.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isPreventBlockAboveRails() + && isProtected(below, user, settings)) + { + event.setCancelled(true); + return; + } - final List<Block> protect = new ArrayList<Block>(); - if ((blockPlaced.getType() == Material.RAILS || blockPlaced.getType() == Material.POWERED_RAIL || blockPlaced.getType() == Material.DETECTOR_RAIL) - && prot.getSettingBool(ProtectConfig.protect_rails) - && user.isAuthorized("essentials.protect")) - { - protect.add(blockPlaced); - if (prot.getSettingBool(ProtectConfig.protect_below_rails) - && !isProtected(blockPlaced.getRelative(BlockFace.DOWN), user)) + final List<Block> protect = new ArrayList<Block>(); + if ((blockPlaced.getType() == Material.RAILS || blockPlaced.getType() == Material.POWERED_RAIL || blockPlaced.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails() + && user.isAuthorized("essentials.protect")) + { + protect.add(blockPlaced); + if (settings.getData().getSignsAndRails().isBlockBelow() + && !isProtected(blockPlaced.getRelative(BlockFace.DOWN), user, settings)) + { + protect.add(blockPlaced.getRelative(BlockFace.DOWN)); + } + } + if ((blockPlaced.getType() == Material.SIGN_POST || blockPlaced.getType() == Material.WALL_SIGN) + && settings.getData().getSignsAndRails().isProtectSigns() + && user.isAuthorized("essentials.protect")) { - protect.add(blockPlaced.getRelative(BlockFace.DOWN)); + protect.add(blockPlaced); + if (settings.getData().getSignsAndRails().isBlockBelow() + && event.getBlockAgainst().getType() != Material.SIGN_POST + && event.getBlockAgainst().getType() != Material.WALL_SIGN + && !isProtected(event.getBlockAgainst(), user, settings)) + { + protect.add(event.getBlockAgainst()); + } } - } - if ((blockPlaced.getType() == Material.SIGN_POST || blockPlaced.getType() == Material.WALL_SIGN) - && prot.getSettingBool(ProtectConfig.protect_signs) - && user.isAuthorized("essentials.protect")) - { - protect.add(blockPlaced); - if (prot.getSettingBool(ProtectConfig.protect_against_signs) - && event.getBlockAgainst().getType() != Material.SIGN_POST - && event.getBlockAgainst().getType() != Material.WALL_SIGN - && !isProtected(event.getBlockAgainst(), user)) + for (Block block : protect) { - protect.add(event.getBlockAgainst()); + prot.getStorage().protectBlock(block, user.getName()); } } - for (Block block : protect) + finally { - prot.getStorage().protectBlock(block, user.getName()); + settings.unlock(); } } @@ -104,47 +112,56 @@ public class EssentialsProtectBlockListener implements Listener { return; } - final Block block = event.getBlock(); - if ((block.getType() == Material.RAILS || block.getType() == Material.POWERED_RAIL || block.getType() == Material.DETECTOR_RAIL) - && prot.getSettingBool(ProtectConfig.protect_rails)) - { - event.setCancelled(true); - return; - } - if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) - && prot.getSettingBool(ProtectConfig.protect_signs)) - { - event.setCancelled(true); - return; - } - if (event.getBlock().getType() == Material.OBSIDIAN - || event.getBlock().getRelative(BlockFace.DOWN).getType() == Material.OBSIDIAN) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_portal_creation)); - return; - } + final Block block = event.getBlock(); + if ((block.getType() == Material.RAILS || block.getType() == Material.POWERED_RAIL || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) + && settings.getData().getSignsAndRails().isProtectSigns()) + { + event.setCancelled(true); + return; + } + if (event.getBlock().getType() == Material.OBSIDIAN + || event.getBlock().getRelative(BlockFace.DOWN).getType() == Material.OBSIDIAN) + { + event.setCancelled(settings.getData().getPrevent().isPortalCreation()); + return; + } - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD)) - { - event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_fire_spread)); - return; - } + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD)) + { + event.setCancelled(settings.getData().getPrevent().isFirespread()); + return; + } - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL)) - { - event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_flint_fire)); - return; - } + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL) && event.getPlayer() != null) + { + event.setCancelled(ess.getUser(event.getPlayer()).isAuthorized(Permissions.USEFLINTSTEEL)); + return; + } - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LAVA)) - { - event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lava_fire_spread)); - return; + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LAVA)) + { + event.setCancelled(settings.getData().getPrevent().isLavaFirespread()); + return; + } + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LIGHTNING)) + { + event.setCancelled(settings.getData().getPrevent().isLightningFirespread()); + return; + } } - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LIGHTNING)) + finally { - event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lightning_fire_spread)); - return; + settings.unlock(); } } @@ -155,37 +172,45 @@ public class EssentialsProtectBlockListener implements Listener { return; } - final Block toBlock = event.getToBlock(); - if ((toBlock.getType() == Material.RAILS || toBlock.getType() == Material.POWERED_RAIL || toBlock.getType() == Material.DETECTOR_RAIL) - && prot.getSettingBool(ProtectConfig.protect_rails)) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setCancelled(true); - return; - } - if ((toBlock.getType() == Material.WALL_SIGN || toBlock.getType() == Material.SIGN_POST) - && prot.getSettingBool(ProtectConfig.protect_signs)) - { - event.setCancelled(true); - return; - } + final Block toBlock = event.getToBlock(); + if ((toBlock.getType() == Material.RAILS || toBlock.getType() == Material.POWERED_RAIL || toBlock.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if ((toBlock.getType() == Material.WALL_SIGN || toBlock.getType() == Material.SIGN_POST) + && settings.getData().getSignsAndRails().isProtectSigns()) + { + event.setCancelled(true); + return; + } - final Block block = event.getBlock(); - if (block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER) - { - event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_flow)); - return; - } + final Block block = event.getBlock(); + if (block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER) + { + event.setCancelled(settings.getData().getPrevent().isWaterFlow()); + return; + } - if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA) - { - event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lava_flow)); - return; + if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA) + { + event.setCancelled(settings.getData().getPrevent().isLavaFlow()); + return; + } + // TODO: Test if this still works + /* + * if (block.getType() == Material.AIR) { + * event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_bucket_flow)); return; } + */ } - - if (block.getType() == Material.AIR) + finally { - event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_bucket_flow)); - return; + settings.unlock(); } } @@ -196,22 +221,32 @@ public class EssentialsProtectBlockListener implements Listener { return; } - final Block block = event.getBlock(); - if ((block.getType() == Material.RAILS || block.getType() == Material.POWERED_RAIL || block.getType() == Material.DETECTOR_RAIL) && prot.getSettingBool(ProtectConfig.protect_rails)) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setCancelled(true); - return; - } - if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) - && prot.getSettingBool(ProtectConfig.protect_signs)) - { - event.setCancelled(true); - return; + final Block block = event.getBlock(); + if ((block.getType() == Material.RAILS || block.getType() == Material.POWERED_RAIL || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) + && settings.getData().getSignsAndRails().isProtectSigns()) + { + event.setCancelled(true); + return; + } + if (settings.getData().getPrevent().isFirespread()) + { + event.setCancelled(true); + return; + } } - if (prot.getSettingBool(ProtectConfig.prevent_fire_spread)) + finally { - event.setCancelled(true); - return; + settings.unlock(); } } private final static BlockFace[] faces = new BlockFace[] @@ -232,9 +267,9 @@ public class EssentialsProtectBlockListener implements Listener { return; } - final User user = ess.getUser(event.getPlayer()); + final IUser user = ess.getUser(event.getPlayer()); - if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild()) + if (!user.isAuthorized(Permissions.BUILD)) { event.setCancelled(true); return; @@ -242,30 +277,41 @@ public class EssentialsProtectBlockListener implements Listener final Block block = event.getBlock(); final int typeId = block.getTypeId(); - if (prot.checkProtectionItems(ProtectConfig.blacklist_break, typeId) - && !user.isAuthorized("essentials.protect.exemptbreak")) + if (!user.isAuthorized(BlockBreakPermissions.getPermission(block.getType()))) { event.setCancelled(true); return; } - final Material type = block.getType(); - - if (!user.hasPermission("essentials.protect.alerts.notrigger") - && prot.checkProtectionItems(ProtectConfig.alert_on_break, typeId)) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - prot.getEssentialsConnect().alert(user, type.toString(), _("alertBroke")); - } - final IProtectedBlock storage = prot.getStorage(); + final Material type = block.getType(); - if (user.isAuthorized("essentials.protect.admin")) - { - if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) + if (!user.hasPermission("essentials.protect.alerts.notrigger") && settings.getData().getAlertOnBreak().contains(type)) + { + prot.getEssentialsConnect().alert(user, type.toString(), _("alertBroke")); + } + final IProtectedBlock storage = prot.getStorage(); + + if (user.isAuthorized("essentials.protect.admin")) { - storage.unprotectBlock(block); - if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.SIGN_POST) + if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) { - final Block below = block.getRelative(BlockFace.DOWN); - storage.unprotectBlock(below); + storage.unprotectBlock(block); + if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.SIGN_POST) + { + final Block below = block.getRelative(BlockFace.DOWN); + storage.unprotectBlock(below); + } + else + { + for (BlockFace blockFace : faces) + { + final Block against = block.getRelative(blockFace); + storage.unprotectBlock(against); + } + } } else { @@ -278,30 +324,30 @@ public class EssentialsProtectBlockListener implements Listener } else { - for (BlockFace blockFace : faces) + + final boolean isProtected = isProtected(block, user, settings); + if (isProtected) { - final Block against = block.getRelative(blockFace); - storage.unprotectBlock(against); + event.setCancelled(true); } - } - } - else - { - - final boolean isProtected = isProtected(block, user); - if (isProtected) - { - event.setCancelled(true); - } - else - { - if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) + else { - storage.unprotectBlock(block); - if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.SIGN_POST) + if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) { - final Block below = block.getRelative(BlockFace.DOWN); - storage.unprotectBlock(below); + storage.unprotectBlock(block); + if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.SIGN_POST) + { + final Block below = block.getRelative(BlockFace.DOWN); + storage.unprotectBlock(below); + } + else + { + for (BlockFace blockFace : faces) + { + final Block against = block.getRelative(blockFace); + storage.unprotectBlock(against); + } + } } else { @@ -312,28 +358,89 @@ public class EssentialsProtectBlockListener implements Listener } } } - else + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onBlockPistonExtend(final BlockPistonExtendEvent event) + { + if (event.isCancelled()) + { + return; + } + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + for (Block block : event.getBlocks()) + { + if (settings.getData().getPrevent().getPistonPush().contains(block.getType())) + { + event.setCancelled(true); + return; + } + if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS + || block.getType() == Material.RAILS + || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL + || block.getType() == Material.POWERED_RAIL + || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL + || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if (settings.getData().getSignsAndRails().isProtectSigns()) { for (BlockFace blockFace : faces) { - final Block against = block.getRelative(blockFace); - storage.unprotectBlock(against); + if (blockFace == BlockFace.DOWN) + { + continue; + } + final Block sign = block.getRelative(blockFace); + if ((blockFace == BlockFace.UP || blockFace == BlockFace.SELF) + && sign.getType() == Material.SIGN_POST) + { + event.setCancelled(true); + return; + } + if ((blockFace == BlockFace.NORTH || blockFace == BlockFace.EAST + || blockFace == BlockFace.SOUTH || blockFace == BlockFace.WEST + || blockFace == BlockFace.SELF) + && sign.getType() == Material.WALL_SIGN) + { + event.setCancelled(true); + return; + } } } } } + finally + { + settings.unlock(); + } } @EventHandler(priority = EventPriority.HIGHEST) - public void onBlockPistonExtend(BlockPistonExtendEvent event) + public void onBlockPistonRetract(final BlockPistonRetractEvent event) { - if (event.isCancelled()) + if (event.isCancelled() || !event.isSticky()) { return; } - for (Block block : event.getBlocks()) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - if (prot.checkProtectionItems(ProtectConfig.blacklist_piston, block.getTypeId())) + final Block block = event.getRetractLocation().getBlock(); + if (settings.getData().getPrevent().getPistonPush().contains(block.getType())) { event.setCancelled(true); return; @@ -344,12 +451,12 @@ public class EssentialsProtectBlockListener implements Listener || block.getType() == Material.POWERED_RAIL || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL || block.getType() == Material.DETECTOR_RAIL) - && prot.getSettingBool(ProtectConfig.protect_rails)) + && settings.getData().getSignsAndRails().isProtectRails()) { event.setCancelled(true); return; } - if (prot.getSettingBool(ProtectConfig.protect_signs)) + if (settings.getData().getSignsAndRails().isProtectSigns()) { for (BlockFace blockFace : faces) { @@ -375,70 +482,23 @@ public class EssentialsProtectBlockListener implements Listener } } } - } - @EventHandler(priority = EventPriority.HIGHEST) - public void onBlockPistonRetract(BlockPistonRetractEvent event) - { - if (event.isCancelled() || !event.isSticky()) - { - return; - } - final Block block = event.getRetractLocation().getBlock(); - if (prot.checkProtectionItems(ProtectConfig.blacklist_piston, block.getTypeId())) + finally { - event.setCancelled(true); - return; - } - if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS - || block.getType() == Material.RAILS - || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL - || block.getType() == Material.POWERED_RAIL - || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL - || block.getType() == Material.DETECTOR_RAIL) - && prot.getSettingBool(ProtectConfig.protect_rails)) - { - event.setCancelled(true); - return; - } - if (prot.getSettingBool(ProtectConfig.protect_signs)) - { - for (BlockFace blockFace : faces) - { - if (blockFace == BlockFace.DOWN) - { - continue; - } - final Block sign = block.getRelative(blockFace); - if ((blockFace == BlockFace.UP || blockFace == BlockFace.SELF) - && sign.getType() == Material.SIGN_POST) - { - event.setCancelled(true); - return; - } - if ((blockFace == BlockFace.NORTH || blockFace == BlockFace.EAST - || blockFace == BlockFace.SOUTH || blockFace == BlockFace.WEST - || blockFace == BlockFace.SELF) - && sign.getType() == Material.WALL_SIGN) - { - event.setCancelled(true); - return; - } - } + settings.unlock(); } } - private boolean isProtected(final Block block, final User user) + private boolean isProtected(final Block block, final IUser user, final ProtectHolder settings) { final Material type = block.getType(); - if (prot.getSettingBool(ProtectConfig.protect_signs)) + if (settings.getData().getSignsAndRails().isProtectSigns()) { if (type == Material.WALL_SIGN || type == Material.SIGN_POST) { return prot.getStorage().isProtected(block, user.getName()); } - if (prot.getSettingBool(ProtectConfig.protect_against_signs)) - { + final Block up = block.getRelative(BlockFace.UP); if (up != null && up.getType() == Material.SIGN_POST) { @@ -463,15 +523,15 @@ public class EssentialsProtectBlockListener implements Listener } } } - } + } - if (prot.getSettingBool(ProtectConfig.protect_rails)) + if (settings.getData().getSignsAndRails().isProtectRails()) { if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) { return prot.getStorage().isProtected(block, user.getName()); } - if (prot.getSettingBool(ProtectConfig.protect_below_rails)) + if (settings.getData().getSignsAndRails().isBlockBelow()) { final Block up = block.getRelative(BlockFace.UP); if (up != null && (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL)) diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java index 40167ec41..bba267d41 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java @@ -1,9 +1,8 @@ package com.earth2me.essentials.protect; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.craftbukkit.FakeExplosion; -import java.util.Locale; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; @@ -23,6 +22,7 @@ public class EssentialsProtectEntityListener implements Listener public EssentialsProtectEntityListener(final IProtect prot) { + super(); this.prot = prot; this.ess = prot.getEssentialsConnect().getEssentials(); } @@ -34,233 +34,219 @@ public class EssentialsProtectEntityListener implements Listener { return; } - final Entity target = event.getEntity(); - - if (target instanceof Villager && prot.getSettingBool(ProtectConfig.prevent_villager_death)) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setCancelled(true); - return; - } - - final User user = ess.getUser(target); - if (event instanceof EntityDamageByBlockEvent) - { - final DamageCause cause = event.getCause(); + final Entity target = event.getEntity(); - if (prot.getSettingBool(ProtectConfig.disable_contactdmg) - && cause == DamageCause.CONTACT - && !(target instanceof Player - && user.isAuthorized("essentials.protect.damage.contact") - && !user.isAuthorized("essentials.protect.damage.disable"))) + if (target instanceof Villager && settings.getData().getPrevent().isVillagerDeath()) { event.setCancelled(true); return; } - if (prot.getSettingBool(ProtectConfig.disable_lavadmg) - && cause == DamageCause.LAVA - && !(target instanceof Player - && user.isAuthorized("essentials.protect.damage.lava") - && !user.isAuthorized("essentials.protect.damage.disable"))) + + final IUser user = target instanceof Player ? ess.getUser((Player)target) : null; + if (target instanceof Player && event instanceof EntityDamageByBlockEvent) { - event.setCancelled(true); - return; + final DamageCause cause = event.getCause(); + + if (cause == DamageCause.CONTACT + && (user.isAuthorized(Permissions.PREVENTDAMAGE_CONTACT) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } + if (cause == DamageCause.LAVA + && (user.isAuthorized(Permissions.PREVENTDAMAGE_LAVADAMAGE) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } + if (cause == DamageCause.BLOCK_EXPLOSION + && (user.isAuthorized(Permissions.PREVENTDAMAGE_TNT) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } } - if (prot.getSettingBool(ProtectConfig.prevent_tnt_explosion) - && cause == DamageCause.BLOCK_EXPLOSION - && !(target instanceof Player - && user.isAuthorized("essentials.protect.damage.tnt") - && !user.isAuthorized("essentials.protect.damage.disable"))) + + if (target instanceof Player && event instanceof EntityDamageByEntityEvent) { - event.setCancelled(true); - return; - } - } + final EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event; + final Entity eAttack = edEvent.getDamager(); + final IUser attacker = eAttack instanceof Player ? ess.getUser((Player)eAttack) : null; - if (event instanceof EntityDamageByEntityEvent) - { - final EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event; - final Entity eAttack = edEvent.getDamager(); - final User attacker = ess.getUser(eAttack); + // PVP Settings + if (target instanceof Player && eAttack instanceof Player + && (!user.isAuthorized(Permissions.PVP) || !attacker.isAuthorized(Permissions.PVP))) + { + event.setCancelled(true); + return; + } - // PVP Settings - if (target instanceof Player && eAttack instanceof Player - && prot.getSettingBool(ProtectConfig.disable_pvp) - && (!user.isAuthorized("essentials.protect.pvp") || !attacker.isAuthorized("essentials.protect.pvp"))) - { - event.setCancelled(true); - return; - } + //Creeper explode prevention + if (eAttack instanceof Creeper && settings.getData().getPrevent().isCreeperExplosion() + || (user.isAuthorized(Permissions.PREVENTDAMAGE_CREEPER) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } - //Creeper explode prevention - if (eAttack instanceof Creeper && prot.getSettingBool(ProtectConfig.prevent_creeper_explosion) - && !(target instanceof Player - && user.isAuthorized("essentials.protect.damage.creeper") - && !user.isAuthorized("essentials.protect.damage.disable"))) - { - event.setCancelled(true); - return; - } + if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) + && (user.isAuthorized(Permissions.PREVENTDAMAGE_FIREBALL) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } - if (eAttack instanceof Creeper && prot.getSettingBool(ProtectConfig.prevent_creeper_playerdmg) - && !(target instanceof Player - && user.isAuthorized("essentials.protect.damage.creeper") - && !user.isAuthorized("essentials.protect.damage.disable"))) - { - event.setCancelled(true); - return; - } + if (eAttack instanceof TNTPrimed + && (user.isAuthorized(Permissions.PREVENTDAMAGE_TNT) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } - if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) - && prot.getSettingBool(ProtectConfig.prevent_fireball_playerdmg) - && !(target instanceof Player - && user.isAuthorized("essentials.protect.damage.fireball") - && !user.isAuthorized("essentials.protect.damage.disable"))) - { - event.setCancelled(true); - return; + if (edEvent.getDamager() instanceof Projectile + && ((user.isAuthorized(Permissions.PREVENTDAMAGE_PROJECTILES) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE)) + || (((Projectile)edEvent.getDamager()).getShooter() instanceof Player + && (!user.isAuthorized(Permissions.PVP) + || !ess.getUser((Player)((Projectile)edEvent.getDamager()).getShooter()).isAuthorized(Permissions.PVP))))) + { + event.setCancelled(true); + return; + } } - if (eAttack instanceof TNTPrimed && prot.getSettingBool(ProtectConfig.prevent_tnt_playerdmg) - && !(target instanceof Player - && user.isAuthorized("essentials.protect.damage.tnt") - && !user.isAuthorized("essentials.protect.damage.disable"))) + final DamageCause cause = event.getCause(); + if (target instanceof Player) { - event.setCancelled(true); - return; - } + if (cause == DamageCause.FALL + && (user.isAuthorized(Permissions.PREVENTDAMAGE_FALL) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } - if (edEvent.getDamager() instanceof Projectile - && target instanceof Player - && ((prot.getSettingBool(ProtectConfig.disable_projectiles) - && !(user.isAuthorized("essentials.protect.damage.projectiles") - && !user.isAuthorized("essentials.protect.damage.disable"))) - || (((Projectile)edEvent.getDamager()).getShooter() instanceof Player - && prot.getSettingBool(ProtectConfig.disable_pvp) - && (!user.isAuthorized("essentials.protect.pvp") - || !ess.getUser(((Projectile)edEvent.getDamager()).getShooter()).isAuthorized("essentials.protect.pvp"))))) - { - event.setCancelled(true); - return; + if (cause == DamageCause.SUFFOCATION + && (user.isAuthorized(Permissions.PREVENTDAMAGE_SUFFOCATION) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } + if ((cause == DamageCause.FIRE + || cause == DamageCause.FIRE_TICK) + && (user.isAuthorized(Permissions.PREVENTDAMAGE_FIRE) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } + if (cause == DamageCause.DROWNING + && (user.isAuthorized(Permissions.PREVENTDAMAGE_DROWNING) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } + if (cause == DamageCause.LIGHTNING + && (user.isAuthorized(Permissions.PREVENTDAMAGE_LIGHTNING) + && !user.isAuthorized(Permissions.PREVENTDAMAGE_NONE))) + { + event.setCancelled(true); + return; + } } } + finally + { + settings.unlock(); + } + } - final DamageCause cause = event.getCause(); - if (target instanceof Player) + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityExplode(final EntityExplodeEvent event) + { + if (event.isCancelled()) { - if (cause == DamageCause.FALL - && prot.getSettingBool(ProtectConfig.disable_fall) - && !(user.isAuthorized("essentials.protect.damage.fall") - && !user.isAuthorized("essentials.protect.damage.disable"))) - { - event.setCancelled(true); - return; - } + return; + } + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final int maxHeight = settings.getData().getCreeperMaxHeight(); - if (cause == DamageCause.SUFFOCATION - && prot.getSettingBool(ProtectConfig.disable_suffocate) - && !(user.isAuthorized("essentials.protect.damage.suffocation") - && !user.isAuthorized("essentials.protect.damage.disable"))) + if (event.getEntity() instanceof EnderDragon + && settings.getData().getPrevent().isEnderdragonBlockdamage()) { event.setCancelled(true); return; } - if ((cause == DamageCause.FIRE - || cause == DamageCause.FIRE_TICK) - && prot.getSettingBool(ProtectConfig.disable_firedmg) - && !(user.isAuthorized("essentials.protect.damage.fire") - && !user.isAuthorized("essentials.protect.damage.disable"))) + else if (event.getEntity() instanceof Creeper + && (settings.getData().getPrevent().isCreeperExplosion() + || settings.getData().getPrevent().isCreeperBlockdamage() + || (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight))) { + //Nicccccccccce plaaacccccccccce.. + FakeExplosion.createExplosion(event, ess.getServer(), ess.getServer().getOnlinePlayers()); event.setCancelled(true); return; } - if (cause == DamageCause.DROWNING - && prot.getSettingBool(ProtectConfig.disable_drown) - && !(user.isAuthorized("essentials.protect.damage.drowning") - && !user.isAuthorized("essentials.protect.damage.disable"))) + else if (event.getEntity() instanceof TNTPrimed + && settings.getData().getPrevent().isTntExplosion()) { event.setCancelled(true); return; } - if (cause == DamageCause.LIGHTNING - && prot.getSettingBool(ProtectConfig.disable_lightning) - && !(user.isAuthorized("essentials.protect.damage.lightning") - && !user.isAuthorized("essentials.protect.damage.disable"))) + else if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) + && settings.getData().getPrevent().isFireballExplosion()) { event.setCancelled(true); return; } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityExplode(final EntityExplodeEvent event) - { - if (event.isCancelled()) - { - return; - } - final int maxHeight = ess.getSettings().getProtectCreeperMaxHeight(); + // This code will prevent explosions near protected rails, signs or protected chests + // TODO: Use protect db instead of this code - if (event.getEntity() instanceof EnderDragon - && prot.getSettingBool(ProtectConfig.prevent_enderdragon_blockdmg)) - { - if (prot.getSettingBool(ProtectConfig.enderdragon_fakeexplosions)) + for (Block block : event.blockList()) { - FakeExplosion.createExplosion(event, ess.getServer(), ess.getServer().getOnlinePlayers()); + if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS + || block.getType() == Material.RAILS + || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL + || block.getType() == Material.POWERED_RAIL + || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL + || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if ((block.getType() == Material.WALL_SIGN + || block.getRelative(BlockFace.NORTH).getType() == Material.WALL_SIGN + || block.getRelative(BlockFace.EAST).getType() == Material.WALL_SIGN + || block.getRelative(BlockFace.SOUTH).getType() == Material.WALL_SIGN + || block.getRelative(BlockFace.WEST).getType() == Material.WALL_SIGN + || block.getType() == Material.SIGN_POST + || block.getRelative(BlockFace.UP).getType() == Material.SIGN_POST) + && settings.getData().getSignsAndRails().isProtectSigns()) + { + event.setCancelled(true); + return; + } } - event.setCancelled(true); - return; - } - else if (event.getEntity() instanceof Creeper - && (prot.getSettingBool(ProtectConfig.prevent_creeper_explosion) - || prot.getSettingBool(ProtectConfig.prevent_creeper_blockdmg) - || (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight))) - { - //Nicccccccccce plaaacccccccccce.. - FakeExplosion.createExplosion(event, ess.getServer(), ess.getServer().getOnlinePlayers()); - event.setCancelled(true); - return; - } - else if (event.getEntity() instanceof TNTPrimed - && prot.getSettingBool(ProtectConfig.prevent_tnt_explosion)) - { - event.setCancelled(true); - return; } - else if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) - && prot.getSettingBool(ProtectConfig.prevent_fireball_explosion)) + finally { - event.setCancelled(true); - return; - } - // This code will prevent explosions near protected rails, signs or protected chests - // TODO: Use protect db instead of this code - - for (Block block : event.blockList()) - { - if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS - || block.getType() == Material.RAILS - || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL - || block.getType() == Material.POWERED_RAIL - || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL - || block.getType() == Material.DETECTOR_RAIL) - && prot.getSettingBool(ProtectConfig.protect_rails)) - { - event.setCancelled(true); - return; - } - if ((block.getType() == Material.WALL_SIGN - || block.getRelative(BlockFace.NORTH).getType() == Material.WALL_SIGN - || block.getRelative(BlockFace.EAST).getType() == Material.WALL_SIGN - || block.getRelative(BlockFace.SOUTH).getType() == Material.WALL_SIGN - || block.getRelative(BlockFace.WEST).getType() == Material.WALL_SIGN - || block.getType() == Material.SIGN_POST - || block.getRelative(BlockFace.UP).getType() == Material.SIGN_POST) - && prot.getSettingBool(ProtectConfig.protect_signs)) - { - event.setCancelled(true); - return; - } + settings.unlock(); } } @@ -280,37 +266,37 @@ public class EssentialsProtectEntityListener implements Listener { return; } - final String creatureName = creature.toString().toLowerCase(Locale.ENGLISH); - if (creatureName == null || creatureName.isEmpty()) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - return; + final Boolean prevent = settings.getData().getPrevent().getSpawn().get(creature); + if (prevent != null && prevent) + { + event.setCancelled(true); + } } - if (ess.getSettings().getProtectPreventSpawn(creatureName)) + finally { - event.setCancelled(true); + settings.unlock(); } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityTarget(final EntityTargetEvent event) { - if (event.isCancelled()) + if (event.isCancelled() || !(event.getTarget() instanceof Player)) { return; } - if (!(event.getTarget() instanceof Player)) - { - return; - } - final User user = ess.getUser(event.getTarget()); + final IUser user = ess.getUser((Player)event.getTarget()); if ((event.getReason() == TargetReason.CLOSEST_PLAYER || event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY || event.getReason() == TargetReason.PIG_ZOMBIE_TARGET || event.getReason() == TargetReason.RANDOM_TARGET || event.getReason() == TargetReason.TARGET_ATTACKED_OWNER || event.getReason() == TargetReason.OWNER_ATTACKED_TARGET) - && prot.getSettingBool(ProtectConfig.prevent_entitytarget) - && !user.isAuthorized("essentials.protect.entitytarget.bypass")) + && user.isAuthorized(Permissions.ENTITYTARGET)) { event.setCancelled(true); return; @@ -318,26 +304,43 @@ public class EssentialsProtectEntityListener implements Listener } @EventHandler(priority = EventPriority.HIGHEST) - public void onExplosionPrime(ExplosionPrimeEvent event) + public void onExplosionPrime(final ExplosionPrimeEvent event) { - if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) - && prot.getSettingBool(ProtectConfig.prevent_fireball_fire)) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setFire(false); + if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) + && settings.getData().getPrevent().isFireballFire()) + { + event.setFire(false); + } + } + finally + { + settings.unlock(); } } @EventHandler(priority = EventPriority.HIGHEST) - public void onEndermanPickup(EndermanPickupEvent event) + public void onEndermanPickup(final EndermanPickupEvent event) { if (event.isCancelled()) { return; } - if (prot.getSettingBool(ProtectConfig.prevent_enderman_pickup)) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setCancelled(true); - return; + if (settings.getData().getPrevent().isEndermanPickup()) + { + event.setCancelled(true); + } + } + finally + { + settings.unlock(); } } } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java index 6e515e56d..7fe1ea33f 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java @@ -1,8 +1,8 @@ package com.earth2me.essentials.protect; 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.IUser; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; @@ -28,65 +28,73 @@ public class EssentialsProtectPlayerListener implements Listener public void onPlayerInteract(final PlayerInteractEvent event) { // Do not return if cancelled, because the interact event has 2 cancelled states. - final User user = ess.getUser(event.getPlayer()); + final IUser user = ess.getUser(event.getPlayer()); - if (event.hasItem() - && (event.getItem().getType() == Material.WATER_BUCKET - || event.getItem().getType() == Material.LAVA_BUCKET) - && prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild()) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - if (ess.getSettings().warnOnBuildDisallow()) + if (event.hasItem() + && (event.getItem().getType() == Material.WATER_BUCKET + || event.getItem().getType() == Material.LAVA_BUCKET) + && !user.isAuthorized(Permissions.BUILD)) { - user.sendMessage(_("buildAlert")); + if (settings.getData().isWarnOnBuildDisallow()) + { + user.sendMessage(_("buildAlert")); + } + event.setCancelled(true); + return; } - event.setCancelled(true); - return; - } - if (prot.getSettingBool(ProtectConfig.disable_use) && !user.canBuild()) - { - if (ess.getSettings().warnOnBuildDisallow()) + if (!user.isAuthorized(Permissions.INTERACT)) { - user.sendMessage(_("buildAlert")); + if (settings.getData().isWarnOnBuildDisallow()) + { + user.sendMessage(_("buildAlert")); + } + event.setCancelled(true); + return; } - event.setCancelled(true); - return; - } - final ItemStack item = event.getItem(); - if (item != null - && prot.checkProtectionItems(ProtectConfig.blacklist_usage, item.getTypeId()) - && !user.isAuthorized("essentials.protect.exemptusage")) - { - event.setCancelled(true); - return; - } + final ItemStack item = event.getItem(); + if (item != null + && !user.isAuthorized(ItemUsePermissions.getPermission(item.getType()))) + { + event.setCancelled(true); + return; + } - if (user.isAuthorized("essentials.protect.ownerinfo") && event.getAction() == Action.RIGHT_CLICK_BLOCK) - { - final StringBuilder stringBuilder = new StringBuilder(); - boolean first = true; - final Block blockClicked = event.getClickedBlock(); - for (String owner : prot.getStorage().getOwners(blockClicked)) + if (user.isAuthorized("essentials.protect.ownerinfo") && event.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (!first) + final StringBuilder stringBuilder = new StringBuilder(); + boolean first = true; + final Block blockClicked = event.getClickedBlock(); + for (String owner : prot.getStorage().getOwners(blockClicked)) + { + if (!first) + { + stringBuilder.append(", "); + } + first = false; + stringBuilder.append(owner); + } + final String ownerNames = stringBuilder.toString(); + if (ownerNames != null && !ownerNames.isEmpty()) { - stringBuilder.append(", "); + user.sendMessage(_("protectionOwner", ownerNames)); } - first = false; - stringBuilder.append(owner); } - final String ownerNames = stringBuilder.toString(); - if (ownerNames != null && !ownerNames.isEmpty()) + if (item != null + && !user.hasPermission("essentials.protect.alerts.notrigger") + && settings.getData().getAlertOnUse().contains(item.getType())) { - user.sendMessage(_("protectionOwner", ownerNames)); + prot.getEssentialsConnect().alert(user, item.getType().toString(), _("alertUsed")); } } - if (item != null - && !user.hasPermission("essentials.protect.alerts.notrigger") - && prot.checkProtectionItems(ProtectConfig.alert_on_use, item.getTypeId())) + finally { - prot.getEssentialsConnect().alert(user, item.getType().toString(), _("alertUsed")); + settings.unlock(); } } } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java index 1b8dd19ff..babebac71 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java @@ -20,33 +20,59 @@ public class EssentialsProtectWeatherListener implements Listener @EventHandler(priority = EventPriority.HIGHEST) public void onWeatherChange(final WeatherChangeEvent event) { - if (!event.isCancelled() - && prot.getSettingBool(ProtectConfig.disable_weather_storm) - && event.toWeatherState()) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setCancelled(true); + if (!event.isCancelled() + && settings.getData().isDisableStorm() + && event.toWeatherState()) + { + event.setCancelled(true); + } + } + finally + { + settings.unlock(); } - } @EventHandler(priority = EventPriority.HIGHEST) public void onLightningStrike(final LightningStrikeEvent event) { - if (!event.isCancelled() - && prot.getSettingBool(ProtectConfig.disable_weather_lightning)) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try { - event.setCancelled(true); + if (!event.isCancelled() + && settings.getData().isDisableLighting()) + { + event.setCancelled(true); + } + } + finally + { + settings.unlock(); } } @EventHandler(priority = EventPriority.HIGHEST) public void onThunderChange(final ThunderChangeEvent event) { - if (!event.isCancelled() - && prot.getSettingBool(ProtectConfig.disable_weather_thunder) - && event.toThunderState()) + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + if (!event.isCancelled() + && settings.getData().isDisableThunder() + && event.toThunderState()) + { + event.setCancelled(true); + } + } + finally { - event.setCancelled(true); + settings.unlock(); } } } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java index afcb6e8ce..d25661bf8 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java @@ -1,28 +1,24 @@ package com.earth2me.essentials.protect; import com.earth2me.essentials.protect.data.IProtectedBlock; -import java.util.List; -import java.util.Map; import org.bukkit.plugin.Plugin; public interface IProtect extends Plugin { - boolean checkProtectionItems(final ProtectConfig list, final int id); - - boolean getSettingBool(final ProtectConfig protectConfig); - - String getSettingString(final ProtectConfig protectConfig); - +// boolean checkProtectionItems(final ProtectConfig list, final int id); +// boolean getSettingBool(final ProtectConfig protectConfig); +// String getSettingString(final ProtectConfig protectConfig); IProtectedBlock getStorage(); void setStorage(IProtectedBlock pb); EssentialsConnect getEssentialsConnect(); - Map<ProtectConfig, Boolean> getSettingsBoolean(); - - Map<ProtectConfig, String> getSettingsString(); +// Map<ProtectConfig, Boolean> getSettingsBoolean(); +// Map<ProtectConfig, String> getSettingsString(); +// Map<ProtectConfig, List<Integer>> getSettingsList(); + ProtectHolder getSettings(); - Map<ProtectConfig, List<Integer>> getSettingsList(); + void setSettings(ProtectHolder settings); } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/ItemUsePermissions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/ItemUsePermissions.java new file mode 100644 index 000000000..258a93761 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/ItemUsePermissions.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.api.IPermission; +import com.earth2me.essentials.perm.AbstractSuperpermsPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + +public class ItemUsePermissions extends AbstractSuperpermsPermission{ + private static Map<Material,IPermission> permissions = new EnumMap<Material, IPermission>(Material.class); + private static final String base = "essentials.protect.itemuse."; + private final String permission; + + public static IPermission getPermission(Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) { + perm = new ItemUsePermissions(mat.toString().toLowerCase(Locale.ENGLISH)); + permissions.put(mat, perm); + } + return perm; + } + + private ItemUsePermissions(String matName) + { + this.permission = base + matName; + } + + @Override + public String getPermission() + { + return this.permission; + } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/Permissions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/Permissions.java new file mode 100644 index 000000000..61ac1b295 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/Permissions.java @@ -0,0 +1,69 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IPermission; +import java.util.Locale; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public enum Permissions implements IPermission +{ + BUILD(PermissionDefault.TRUE), + INTERACT(PermissionDefault.TRUE), + USEFLINTSTEEL(PermissionDefault.TRUE), + PVP(PermissionDefault.TRUE), + ENTITYTARGET(PermissionDefault.TRUE), + PREVENTDAMAGE_FALL(PermissionDefault.FALSE), + PREVENTDAMAGE_CREEPER(PermissionDefault.FALSE), + PREVENTDAMAGE_CONTACT(PermissionDefault.FALSE), + PREVENTDAMAGE_FIREBALL(PermissionDefault.FALSE), + PREVENTDAMAGE_PROJECTILES(PermissionDefault.FALSE), + PREVENTDAMAGE_LAVADAMAGE(PermissionDefault.FALSE), + PREVENTDAMAGE_TNT(PermissionDefault.FALSE), + PREVENTDAMAGE_SUFFOCATION(PermissionDefault.FALSE), + PREVENTDAMAGE_FIRE(PermissionDefault.FALSE), + PREVENTDAMAGE_DROWNING(PermissionDefault.FALSE), + PREVENTDAMAGE_LIGHTNING(PermissionDefault.FALSE), + PREVENTDAMAGE_NONE(PermissionDefault.FALSE); + private static final String base = "essentials.protect."; + 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; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java index bee8d0f4d..feeeb19df 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java @@ -1,7 +1,7 @@ package com.earth2me.essentials.protect; -public enum ProtectConfig +/*public enum ProtectConfig { datatype("protect.datatype", "sqlite"), mysqlDB("protect.mysqlDb", "jdbc:mysql://localhost:3306/minecraft"), @@ -87,7 +87,7 @@ public enum ProtectConfig /** * @return the configName - */ + *//* public String getConfigName() { return configName; @@ -95,7 +95,7 @@ public enum ProtectConfig /** * @return the default value String - */ + *//* public String getDefaultValueString() { return defValueString; @@ -103,7 +103,7 @@ public enum ProtectConfig /** * @return the default value boolean - */ + *//* public boolean getDefaultValueBoolean() { return defValueBoolean; @@ -118,4 +118,4 @@ public enum ProtectConfig { return isList; } -} +}*/ diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectHolder.java b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectHolder.java new file mode 100644 index 000000000..2e2451397 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectHolder.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.settings.protect.Protect; +import com.earth2me.essentials.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; + + +public class ProtectHolder extends AsyncStorageObjectHolder<Protect> +{ + public ProtectHolder(IEssentials ess) + { + super(ess, Protect.class); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.getDataFolder(), "protect.yml"); + } +} diff --git a/EssentialsProtect/src/plugin.yml b/EssentialsProtect/src/plugin.yml index 6407c45ee..bbe628e67 100644 --- a/EssentialsProtect/src/plugin.yml +++ b/EssentialsProtect/src/plugin.yml @@ -3,7 +3,7 @@ name: EssentialsProtect main: com.earth2me.essentials.protect.EssentialsProtect # Note to developers: This next line cannot change, or the automatic versioning system will break. version: TeamCity -website: http://www.earth2me.net:8001/ +website: http://tiny.cc/EssentialsWiki description: Provides protection for various parts of the world. authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits] softdepend: [Essentials]
\ No newline at end of file diff --git a/EssentialsSigns/build.xml b/EssentialsSigns/build.xml new file mode 100644 index 000000000..220f99e55 --- /dev/null +++ b/EssentialsSigns/build.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- You may freely edit this file. See commented blocks below for --> +<!-- some examples of how to customize the build. --> +<!-- (If you delete it and reopen the project it will be recreated.) --> +<!-- By default, only the Clean and Build commands use this build script. --> +<!-- Commands such as Run, Debug, and Test only use this build script if --> +<!-- the Compile on Save feature is turned off for the project. --> +<!-- You can turn off the Compile on Save (or Deploy on Save) setting --> +<!-- in the project's Project Properties dialog box.--> +<project name="EssentialsSigns" default="default" basedir="."> + <description>Builds, tests, and runs the project EssentialsSigns.</description> + <import file="nbproject/build-impl.xml"/> + <!-- + + There exist several targets which are by default empty and which can be + used for execution of your tasks. These targets are usually executed + before and after some main targets. They are: + + -pre-init: called before initialization of project properties + -post-init: called after initialization of project properties + -pre-compile: called before javac compilation + -post-compile: called after javac compilation + -pre-compile-single: called before javac compilation of single file + -post-compile-single: called after javac compilation of single file + -pre-compile-test: called before javac compilation of JUnit tests + -post-compile-test: called after javac compilation of JUnit tests + -pre-compile-test-single: called before javac compilation of single JUnit test + -post-compile-test-single: called after javac compilation of single JUunit test + -pre-jar: called before JAR building + -post-jar: called after JAR building + -post-clean: called after cleaning build products + + (Targets beginning with '-' are not intended to be called on their own.) + + Example of inserting an obfuscator after compilation could look like this: + + <target name="-post-compile"> + <obfuscate> + <fileset dir="${build.classes.dir}"/> + </obfuscate> + </target> + + For list of available properties check the imported + nbproject/build-impl.xml file. + + + Another way to customize the build is by overriding existing main targets. + The targets of interest are: + + -init-macrodef-javac: defines macro for javac compilation + -init-macrodef-junit: defines macro for junit execution + -init-macrodef-debug: defines macro for class debugging + -init-macrodef-java: defines macro for class execution + -do-jar-with-manifest: JAR building (if you are using a manifest) + -do-jar-without-manifest: JAR building (if you are not using a manifest) + run: execution of project + -javadoc-build: Javadoc generation + test-report: JUnit report generation + + An example of overriding the target for project execution could look like this: + + <target name="run" depends="EssentialsSigns-impl.jar"> + <exec dir="bin" executable="launcher.exe"> + <arg file="${dist.jar}"/> + </exec> + </target> + + Notice that the overridden target depends on the jar target and not only on + the compile target as the regular run target does. Again, for a list of available + properties which you can use, check the target you are overriding in the + nbproject/build-impl.xml file. + + --> +</project> diff --git a/EssentialsSigns/manifest.mf b/EssentialsSigns/manifest.mf new file mode 100644 index 000000000..328e8e5bc --- /dev/null +++ b/EssentialsSigns/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/EssentialsSigns/nbproject/build-impl.xml b/EssentialsSigns/nbproject/build-impl.xml new file mode 100644 index 000000000..cf7d96a61 --- /dev/null +++ b/EssentialsSigns/nbproject/build-impl.xml @@ -0,0 +1,1092 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +*** GENERATED FROM project.xml - DO NOT EDIT *** +*** EDIT ../build.xml INSTEAD *** + +For the purpose of easier reading the script +is divided into following sections: + + - initialization + - compilation + - jar + - execution + - debugging + - javadoc + - junit compilation + - junit execution + - junit debugging + - applet + - cleanup + + --> +<project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="EssentialsSigns-impl"> + <fail message="Please build using Ant 1.8.0 or higher."> + <condition> + <not> + <antversion atleast="1.8.0"/> + </not> + </condition> + </fail> + <target depends="test,jar,javadoc" description="Build and test whole project." name="default"/> + <!-- + ====================== + INITIALIZATION SECTION + ====================== + --> + <target name="-pre-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init" name="-init-private"> + <property file="nbproject/private/config.properties"/> + <property file="nbproject/private/configs/${config}.properties"/> + <property file="nbproject/private/private.properties"/> + </target> + <target name="-pre-init-libraries"> + <property location="../lib/nblibraries.properties" name="libraries.path"/> + <dirname file="${libraries.path}" property="libraries.dir.nativedirsep"/> + <pathconvert dirsep="/" property="libraries.dir"> + <path path="${libraries.dir.nativedirsep}"/> + </pathconvert> + <basename file="${libraries.path}" property="libraries.basename" suffix=".properties"/> + <available file="${libraries.dir}/${libraries.basename}-private.properties" property="private.properties.available"/> + </target> + <target depends="-pre-init-libraries" if="private.properties.available" name="-init-private-libraries"> + <loadproperties encoding="ISO-8859-1" srcfile="${libraries.dir}/${libraries.basename}-private.properties"> + <filterchain> + <replacestring from="$${base}" to="${libraries.dir}"/> + <escapeunicode/> + </filterchain> + </loadproperties> + </target> + <target depends="-pre-init,-init-private,-init-private-libraries" name="-init-libraries"> + <loadproperties encoding="ISO-8859-1" srcfile="${libraries.path}"> + <filterchain> + <replacestring from="$${base}" to="${libraries.dir}"/> + <escapeunicode/> + </filterchain> + </loadproperties> + </target> + <target depends="-pre-init,-init-private,-init-libraries" name="-init-user"> + <property file="${user.properties.file}"/> + <!-- The two properties below are usually overridden --> + <!-- by the active platform. Just a fallback. --> + <property name="default.javac.source" value="1.4"/> + <property name="default.javac.target" value="1.4"/> + </target> + <target depends="-pre-init,-init-private,-init-libraries,-init-user" name="-init-project"> + <property file="nbproject/configs/${config}.properties"/> + <property file="nbproject/project.properties"/> + </target> + <target depends="-pre-init,-init-private,-init-libraries,-init-user,-init-project,-init-macrodef-property" name="-do-init"> + <available file="${manifest.file}" property="manifest.available"/> + <condition property="splashscreen.available"> + <and> + <not> + <equals arg1="${application.splash}" arg2="" trim="true"/> + </not> + <available file="${application.splash}"/> + </and> + </condition> + <condition property="main.class.available"> + <and> + <isset property="main.class"/> + <not> + <equals arg1="${main.class}" arg2="" trim="true"/> + </not> + </and> + </condition> + <condition property="manifest.available+main.class"> + <and> + <isset property="manifest.available"/> + <isset property="main.class.available"/> + </and> + </condition> + <condition property="do.archive"> + <not> + <istrue value="${jar.archive.disabled}"/> + </not> + </condition> + <condition property="do.mkdist"> + <and> + <isset property="do.archive"/> + <isset property="libs.CopyLibs.classpath"/> + <not> + <istrue value="${mkdist.disabled}"/> + </not> + </and> + </condition> + <condition property="manifest.available+main.class+mkdist.available"> + <and> + <istrue value="${manifest.available+main.class}"/> + <isset property="do.mkdist"/> + </and> + </condition> + <condition property="do.archive+manifest.available"> + <and> + <isset property="manifest.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+main.class.available"> + <and> + <isset property="main.class.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+splashscreen.available"> + <and> + <isset property="splashscreen.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+manifest.available+main.class"> + <and> + <istrue value="${manifest.available+main.class}"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="manifest.available-mkdist.available"> + <or> + <istrue value="${manifest.available}"/> + <isset property="do.mkdist"/> + </or> + </condition> + <condition property="manifest.available+main.class-mkdist.available"> + <or> + <istrue value="${manifest.available+main.class}"/> + <isset property="do.mkdist"/> + </or> + </condition> + <condition property="have.tests"> + <or> + <available file="${test.src.dir}"/> + </or> + </condition> + <condition property="have.sources"> + <or> + <available file="${src.dir}"/> + </or> + </condition> + <condition property="netbeans.home+have.tests"> + <and> + <isset property="netbeans.home"/> + <isset property="have.tests"/> + </and> + </condition> + <condition property="no.javadoc.preview"> + <and> + <isset property="javadoc.preview"/> + <isfalse value="${javadoc.preview}"/> + </and> + </condition> + <property name="run.jvmargs" value=""/> + <property name="javac.compilerargs" value=""/> + <property name="work.dir" value="${basedir}"/> + <condition property="no.deps"> + <and> + <istrue value="${no.dependencies}"/> + </and> + </condition> + <property name="javac.debug" value="true"/> + <property name="javadoc.preview" value="true"/> + <property name="application.args" value=""/> + <property name="source.encoding" value="${file.encoding}"/> + <property name="runtime.encoding" value="${source.encoding}"/> + <condition property="javadoc.encoding.used" value="${javadoc.encoding}"> + <and> + <isset property="javadoc.encoding"/> + <not> + <equals arg1="${javadoc.encoding}" arg2=""/> + </not> + </and> + </condition> + <property name="javadoc.encoding.used" value="${source.encoding}"/> + <property name="includes" value="**"/> + <property name="excludes" value=""/> + <property name="do.depend" value="false"/> + <condition property="do.depend.true"> + <istrue value="${do.depend}"/> + </condition> + <path id="endorsed.classpath.path" path="${endorsed.classpath}"/> + <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'"> + <length length="0" string="${endorsed.classpath}" when="greater"/> + </condition> + <condition else="false" property="jdkBug6558476"> + <and> + <matches pattern="1\.[56]" string="${java.specification.version}"/> + <not> + <os family="unix"/> + </not> + </and> + </condition> + <property name="javac.fork" value="${jdkBug6558476}"/> + <property name="jar.index" value="false"/> + <property name="jar.index.metainf" value="${jar.index}"/> + <property name="copylibs.rebase" value="true"/> + <available file="${meta.inf.dir}/persistence.xml" property="has.persistence.xml"/> + </target> + <target name="-post-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init,-init-private,-init-libraries,-init-user,-init-project,-do-init" name="-init-check"> + <fail unless="src.dir">Must set src.dir</fail> + <fail unless="test.src.dir">Must set test.src.dir</fail> + <fail unless="build.dir">Must set build.dir</fail> + <fail unless="dist.dir">Must set dist.dir</fail> + <fail unless="build.classes.dir">Must set build.classes.dir</fail> + <fail unless="dist.javadoc.dir">Must set dist.javadoc.dir</fail> + <fail unless="build.test.classes.dir">Must set build.test.classes.dir</fail> + <fail unless="build.test.results.dir">Must set build.test.results.dir</fail> + <fail unless="build.classes.excludes">Must set build.classes.excludes</fail> + <fail unless="dist.jar">Must set dist.jar</fail> + </target> + <target name="-init-macrodef-property"> + <macrodef name="property" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute name="name"/> + <attribute name="value"/> + <sequential> + <property name="@{name}" value="${@{value}}"/> + </sequential> + </macrodef> + </target> + <target depends="-init-ap-cmdline-properties" if="ap.supported.internal" name="-init-macrodef-javac-with-processors"> + <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <attribute default="${javac.processorpath}" name="processorpath"/> + <attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="${javac.debug}" name="debug"/> + <attribute default="${empty.dir}" name="sourcepath"/> + <attribute default="${empty.dir}" name="gensrcdir"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.dir}/empty" name="empty.dir"/> + <mkdir dir="${empty.dir}"/> + <mkdir dir="@{apgeneratedsrcdir}"/> + <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> + <src> + <dirset dir="@{gensrcdir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </src> + <classpath> + <path path="@{classpath}"/> + </classpath> + <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> + <compilerarg line="${javac.compilerargs}"/> + <compilerarg value="-processorpath"/> + <compilerarg path="@{processorpath}:${empty.dir}"/> + <compilerarg line="${ap.processors.internal}"/> + <compilerarg line="${annotation.processing.processor.options}"/> + <compilerarg value="-s"/> + <compilerarg path="@{apgeneratedsrcdir}"/> + <compilerarg line="${ap.proc.none.internal}"/> + <customize/> + </javac> + </sequential> + </macrodef> + </target> + <target depends="-init-ap-cmdline-properties" name="-init-macrodef-javac-without-processors" unless="ap.supported.internal"> + <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <attribute default="${javac.processorpath}" name="processorpath"/> + <attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="${javac.debug}" name="debug"/> + <attribute default="${empty.dir}" name="sourcepath"/> + <attribute default="${empty.dir}" name="gensrcdir"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.dir}/empty" name="empty.dir"/> + <mkdir dir="${empty.dir}"/> + <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> + <src> + <dirset dir="@{gensrcdir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </src> + <classpath> + <path path="@{classpath}"/> + </classpath> + <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> + <compilerarg line="${javac.compilerargs}"/> + <customize/> + </javac> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-javac-with-processors,-init-macrodef-javac-without-processors" name="-init-macrodef-javac"> + <macrodef name="depend" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <sequential> + <depend cache="${build.dir}/depcache" destdir="@{destdir}" excludes="${excludes}" includes="${includes}" srcdir="@{srcdir}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </depend> + </sequential> + </macrodef> + <macrodef name="force-recompile" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${build.classes.dir}" name="destdir"/> + <sequential> + <fail unless="javac.includes">Must set javac.includes</fail> + <pathconvert pathsep="${line.separator}" property="javac.includes.binary"> + <path> + <filelist dir="@{destdir}" files="${javac.includes}"/> + </path> + <globmapper from="*.java" to="*.class"/> + </pathconvert> + <tempfile deleteonexit="true" property="javac.includesfile.binary"/> + <echo file="${javac.includesfile.binary}" message="${javac.includes.binary}"/> + <delete> + <files includesfile="${javac.includesfile.binary}"/> + </delete> + <delete> + <fileset file="${javac.includesfile.binary}"/> + </delete> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-junit"> + <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <sequential> + <property name="junit.forkmode" value="perTest"/> + <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> + <batchtest todir="${build.test.results.dir}"> + <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> + <filename name="@{testincludes}"/> + </fileset> + </batchtest> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="-ea"/> + <jvmarg line="${run.jvmargs}"/> + </junit> + </sequential> + </macrodef> + </target> + <target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile, -profile-init-check" name="profile-init"/> + <target name="-profile-pre-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target name="-profile-post-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target name="-profile-init-macrodef-profile"> + <macrodef name="resolve"> + <attribute name="name"/> + <attribute name="value"/> + <sequential> + <property name="@{name}" value="${env.@{value}}"/> + </sequential> + </macrodef> + <macrodef name="profile"> + <attribute default="${main.class}" name="classname"/> + <element name="customize" optional="true"/> + <sequential> + <property environment="env"/> + <resolve name="profiler.current.path" value="${profiler.info.pathvar}"/> + <java classname="@{classname}" dir="${profiler.info.dir}" fork="true" jvm="${profiler.info.jvm}"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="${profiler.info.jvmargs.agent}"/> + <jvmarg line="${profiler.info.jvmargs}"/> + <env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/> + <arg line="${application.args}"/> + <classpath> + <path path="${run.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile" name="-profile-init-check"> + <fail unless="profiler.info.jvm">Must set JVM to use for profiling in profiler.info.jvm</fail> + <fail unless="profiler.info.jvmargs.agent">Must set profiler agent JVM arguments in profiler.info.jvmargs.agent</fail> + </target> + <target depends="-init-debug-args" name="-init-macrodef-nbjpda"> + <macrodef name="nbjpdastart" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="name"/> + <attribute default="${debug.classpath}" name="classpath"/> + <attribute default="" name="stopclassname"/> + <sequential> + <nbjpdastart addressproperty="jpda.address" name="@{name}" stopclassname="@{stopclassname}" transport="${debug-transport}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </nbjpdastart> + </sequential> + </macrodef> + <macrodef name="nbjpdareload" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${build.classes.dir}" name="dir"/> + <sequential> + <nbjpdareload> + <fileset dir="@{dir}" includes="${fix.classes}"> + <include name="${fix.includes}*.class"/> + </fileset> + </nbjpdareload> + </sequential> + </macrodef> + </target> + <target name="-init-debug-args"> + <property name="version-output" value="java version "${ant.java.version}"/> + <condition property="have-jdk-older-than-1.4"> + <or> + <contains string="${version-output}" substring="java version "1.0"/> + <contains string="${version-output}" substring="java version "1.1"/> + <contains string="${version-output}" substring="java version "1.2"/> + <contains string="${version-output}" substring="java version "1.3"/> + </or> + </condition> + <condition else="-Xdebug" property="debug-args-line" value="-Xdebug -Xnoagent -Djava.compiler=none"> + <istrue value="${have-jdk-older-than-1.4}"/> + </condition> + <condition else="dt_socket" property="debug-transport-by-os" value="dt_shmem"> + <os family="windows"/> + </condition> + <condition else="${debug-transport-by-os}" property="debug-transport" value="${debug.transport}"> + <isset property="debug.transport"/> + </condition> + </target> + <target depends="-init-debug-args" name="-init-macrodef-debug"> + <macrodef name="debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${debug.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${debug-args-line}"/> + <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-java"> + <macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${run.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-copylibs"> + <macrodef name="copylibs" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${manifest.file}" name="manifest"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}"/> + <manifest> + <attribute name="Class-Path" value="${jar.classpath}"/> + <customize/> + </manifest> + </copylibs> + </sequential> + </macrodef> + </target> + <target name="-init-presetdef-jar"> + <presetdef name="jar" uri="http://www.netbeans.org/ns/j2se-project/1"> + <jar compress="${jar.compress}" index="${jar.index}" jarfile="${dist.jar}"> + <j2seproject1:fileset dir="${build.classes.dir}"/> + </jar> + </presetdef> + </target> + <target name="-init-ap-cmdline-properties"> + <property name="annotation.processing.enabled" value="true"/> + <property name="annotation.processing.processors.list" value=""/> + <property name="annotation.processing.processor.options" value=""/> + <property name="annotation.processing.run.all.processors" value="true"/> + <property name="javac.processorpath" value="${javac.classpath}"/> + <property name="javac.test.processorpath" value="${javac.test.classpath}"/> + <condition property="ap.supported.internal" value="true"> + <not> + <matches pattern="1\.[0-5](\..*)?" string="${javac.source}"/> + </not> + </condition> + </target> + <target depends="-init-ap-cmdline-properties" if="ap.supported.internal" name="-init-ap-cmdline-supported"> + <condition else="" property="ap.processors.internal" value="-processor ${annotation.processing.processors.list}"> + <isfalse value="${annotation.processing.run.all.processors}"/> + </condition> + <condition else="" property="ap.proc.none.internal" value="-proc:none"> + <isfalse value="${annotation.processing.enabled}"/> + </condition> + </target> + <target depends="-init-ap-cmdline-properties,-init-ap-cmdline-supported" name="-init-ap-cmdline"> + <property name="ap.cmd.line.internal" value=""/> + </target> + <target depends="-pre-init,-init-private,-init-libraries,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-junit,-init-macrodef-nbjpda,-init-macrodef-debug,-init-macrodef-java,-init-presetdef-jar,-init-ap-cmdline" name="init"/> + <!-- + =================== + COMPILATION SECTION + =================== + --> + <target name="-deps-jar-init" unless="built-jar.properties"> + <property location="${build.dir}/built-jar.properties" name="built-jar.properties"/> + <delete file="${built-jar.properties}" quiet="true"/> + </target> + <target if="already.built.jar.${basedir}" name="-warn-already-built-jar"> + <echo level="warn" message="Cycle detected: EssentialsSigns was already built"/> + </target> + <target depends="init,-deps-jar-init" name="deps-jar" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-jar.properties}" verbose="false"/> + <property file="${built-jar.properties}" prefix="already.built.jar."/> + <antcall target="-warn-already-built-jar"/> + <propertyfile file="${built-jar.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-jar.properties}"/> + <param location="${project.Essentials}" name="call.subproject"/> + <param location="${project.Essentials}/build.xml" name="call.script"/> + <param name="call.target" value="jar"/> + <param name="transfer.built-jar.properties" value="${built-jar.properties}"/> + </antcall> + </target> + <target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/> + <target depends="init" name="-check-automatic-build"> + <available file="${build.classes.dir}/.netbeans_automatic_build" property="netbeans.automatic.build"/> + </target> + <target depends="init" if="netbeans.automatic.build" name="-clean-after-automatic-build"> + <antcall target="clean"/> + </target> + <target depends="init,deps-jar" name="-pre-pre-compile"> + <mkdir dir="${build.classes.dir}"/> + </target> + <target name="-pre-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-depend"> + <pathconvert property="build.generated.subdirs"> + <dirset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </pathconvert> + <j2seproject3:depend srcdir="${src.dir}:${build.generated.subdirs}"/> + </target> + <target depends="init,deps-jar,-pre-pre-compile,-pre-compile, -copy-persistence-xml,-compile-depend" if="have.sources" name="-do-compile"> + <j2seproject3:javac gensrcdir="${build.generated.sources.dir}"/> + <copy todir="${build.classes.dir}"> + <fileset dir="${src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target if="has.persistence.xml" name="-copy-persistence-xml"> + <mkdir dir="${build.classes.dir}/META-INF"/> + <copy todir="${build.classes.dir}/META-INF"> + <fileset dir="${meta.inf.dir}" includes="persistence.xml"/> + </copy> + </target> + <target name="-post-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile,-do-compile,-post-compile" description="Compile project." name="compile"/> + <target name="-pre-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-pre-pre-compile" name="-do-compile-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile/> + <j2seproject3:javac excludes="" gensrcdir="${build.generated.sources.dir}" includes="${javac.includes}" sourcepath="${src.dir}"/> + </target> + <target name="-post-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile-single,-do-compile-single,-post-compile-single" name="compile-single"/> + <!-- + ==================== + JAR BUILDING SECTION + ==================== + --> + <target depends="init" name="-pre-pre-jar"> + <dirname file="${dist.jar}" property="dist.jar.dir"/> + <mkdir dir="${dist.jar.dir}"/> + </target> + <target name="-pre-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive" name="-do-jar-without-manifest" unless="manifest.available-mkdist.available"> + <j2seproject1:jar/> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive+manifest.available" name="-do-jar-with-manifest" unless="manifest.available+main.class-mkdist.available"> + <j2seproject1:jar manifest="${manifest.file}"/> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive+manifest.available+main.class" name="-do-jar-with-mainclass" unless="manifest.available+main.class+mkdist.available"> + <j2seproject1:jar manifest="${manifest.file}"> + <j2seproject1:manifest> + <j2seproject1:attribute name="Main-Class" value="${main.class}"/> + </j2seproject1:manifest> + </j2seproject1:jar> + <echo level="info">To run this application from the command line without Ant, try:</echo> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <pathconvert property="run.classpath.with.dist.jar"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/> + </pathconvert> + <echo level="info">java -cp "${run.classpath.with.dist.jar}" ${main.class}</echo> + </target> + <target depends="init" if="do.archive" name="-do-jar-with-libraries-create-manifest" unless="manifest.available"> + <tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/> + <touch file="${tmp.manifest.file}" verbose="false"/> + </target> + <target depends="init" if="do.archive+manifest.available" name="-do-jar-with-libraries-copy-manifest"> + <tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/> + <copy file="${manifest.file}" tofile="${tmp.manifest.file}"/> + </target> + <target depends="init,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest" if="do.archive+main.class.available" name="-do-jar-with-libraries-set-main"> + <manifest file="${tmp.manifest.file}" mode="update"> + <attribute name="Main-Class" value="${main.class}"/> + </manifest> + </target> + <target depends="init,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest" if="do.archive+splashscreen.available" name="-do-jar-with-libraries-set-splashscreen"> + <basename file="${application.splash}" property="splashscreen.basename"/> + <mkdir dir="${build.classes.dir}/META-INF"/> + <copy failonerror="false" file="${application.splash}" todir="${build.classes.dir}/META-INF"/> + <manifest file="${tmp.manifest.file}" mode="update"> + <attribute name="SplashScreen-Image" value="META-INF/${splashscreen.basename}"/> + </manifest> + </target> + <target depends="init,-init-macrodef-copylibs,compile,-pre-pre-jar,-pre-jar,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest,-do-jar-with-libraries-set-main,-do-jar-with-libraries-set-splashscreen" if="do.mkdist" name="-do-jar-with-libraries-pack"> + <j2seproject3:copylibs manifest="${tmp.manifest.file}"/> + <echo level="info">To run this application from the command line without Ant, try:</echo> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <echo level="info">java -jar "${dist.jar.resolved}"</echo> + </target> + <target depends="-do-jar-with-libraries-pack" if="do.archive" name="-do-jar-with-libraries-delete-manifest"> + <delete> + <fileset file="${tmp.manifest.file}"/> + </delete> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest,-do-jar-with-libraries-set-main,-do-jar-with-libraries-set-splashscreen,-do-jar-with-libraries-pack,-do-jar-with-libraries-delete-manifest" name="-do-jar-with-libraries"/> + <target name="-post-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-jar,-do-jar-with-manifest,-do-jar-without-manifest,-do-jar-with-mainclass,-do-jar-with-libraries,-post-jar" description="Build JAR." name="jar"/> + <!-- + ================= + EXECUTION SECTION + ================= + --> + <target depends="init,compile" description="Run a main class." name="run"> + <j2seproject1:java> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject1:java> + </target> + <target name="-do-not-recompile"> + <property name="javac.includes.binary" value=""/> + </target> + <target depends="init,compile-single" name="run-single"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}"/> + </target> + <target depends="init,compile-test-single" name="run-test-with-main"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}" classpath="${run.test.classpath}"/> + </target> + <!-- + ================= + DEBUGGING SECTION + ================= + --> + <target depends="init" if="netbeans.home" name="-debug-start-debugger"> + <j2seproject1:nbjpdastart name="${debug.class}"/> + </target> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-main-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${debug.class}"/> + </target> + <target depends="init,compile" name="-debug-start-debuggee"> + <j2seproject3:debug> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile,-debug-start-debugger,-debug-start-debuggee" description="Debug project in IDE." if="netbeans.home" name="debug"/> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-stepinto"> + <j2seproject1:nbjpdastart stopclassname="${main.class}"/> + </target> + <target depends="init,compile,-debug-start-debugger-stepinto,-debug-start-debuggee" if="netbeans.home" name="debug-stepinto"/> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-single"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}"/> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-single" if="netbeans.home" name="debug-single"/> + <target depends="init,compile-test-single" if="netbeans.home" name="-debug-start-debuggee-main-test"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}" classpath="${debug.test.classpath}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-main-test,-debug-start-debuggee-main-test" if="netbeans.home" name="debug-test-with-main"/> + <target depends="init" name="-pre-debug-fix"> + <fail unless="fix.includes">Must set fix.includes</fail> + <property name="javac.includes" value="${fix.includes}.java"/> + </target> + <target depends="init,-pre-debug-fix,compile-single" if="netbeans.home" name="-do-debug-fix"> + <j2seproject1:nbjpdareload/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix" if="netbeans.home" name="debug-fix"/> + <!-- + ================= + PROFILING SECTION + ================= + --> + <target depends="profile-init,compile" description="Profile a project in the IDE." if="netbeans.home" name="profile"> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile/> + </target> + <target depends="profile-init,compile-single" description="Profile a selected class in the IDE." if="netbeans.home" name="profile-single"> + <fail unless="profile.class">Must select one file in the IDE or set profile.class</fail> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile classname="${profile.class}"/> + </target> + <!-- + ========================= + APPLET PROFILING SECTION + ========================= + --> + <target depends="profile-init,compile-single" if="netbeans.home" name="profile-applet"> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </profile> + </target> + <!-- + ========================= + TESTS PROFILING SECTION + ========================= + --> + <target depends="profile-init,compile-test-single" if="netbeans.home" name="profile-test-single"> + <nbprofiledirect> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + </nbprofiledirect> + <junit dir="${profiler.info.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" jvm="${profiler.info.jvm}" showoutput="true"> + <env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/> + <jvmarg value="${profiler.info.jvmargs.agent}"/> + <jvmarg line="${profiler.info.jvmargs}"/> + <test name="${profile.class}"/> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + </junit> + </target> + <!-- + =============== + JAVADOC SECTION + =============== + --> + <target depends="init" if="have.sources" name="-javadoc-build"> + <mkdir dir="${dist.javadoc.dir}"/> + <condition else="" property="javadoc.endorsed.classpath.cmd.line.arg" value="-J${endorsed.classpath.cmd.line.arg}"> + <and> + <isset property="endorsed.classpath.cmd.line.arg"/> + <not> + <equals arg1="${endorsed.classpath.cmd.line.arg}" arg2=""/> + </not> + </and> + </condition> + <javadoc additionalparam="${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}"> + <classpath> + <path path="${javac.classpath}"/> + </classpath> + <fileset dir="${src.dir}" excludes="*.java,${excludes}" includes="${includes}"> + <filename name="**/*.java"/> + </fileset> + <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="**/*.java"/> + <exclude name="*.java"/> + </fileset> + <arg line="${javadoc.endorsed.classpath.cmd.line.arg}"/> + </javadoc> + <copy todir="${dist.javadoc.dir}"> + <fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}"> + <filename name="**/doc-files/**"/> + </fileset> + <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="**/doc-files/**"/> + </fileset> + </copy> + </target> + <target depends="init,-javadoc-build" if="netbeans.home" name="-javadoc-browse" unless="no.javadoc.preview"> + <nbbrowse file="${dist.javadoc.dir}/index.html"/> + </target> + <target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/> + <!-- + ========================= + JUNIT COMPILATION SECTION + ========================= + --> + <target depends="init,compile" if="have.tests" name="-pre-pre-compile-test"> + <mkdir dir="${build.test.classes.dir}"/> + </target> + <target name="-pre-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-test-depend"> + <j2seproject3:depend classpath="${javac.test.classpath}" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> + </target> + <target depends="init,deps-jar,compile,-pre-pre-compile-test,-pre-compile-test,-compile-test-depend" if="have.tests" name="-do-compile-test"> + <j2seproject3:javac apgeneratedsrcdir="${build.test.classes.dir}" classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" processorpath="${javac.test.processorpath}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-do-compile-test,-post-compile-test" name="compile-test"/> + <target name="-pre-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,compile,-pre-pre-compile-test,-pre-compile-test-single" if="have.tests" name="-do-compile-test-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile destdir="${build.test.classes.dir}"/> + <j2seproject3:javac apgeneratedsrcdir="${build.test.classes.dir}" classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" excludes="" includes="${javac.includes}" processorpath="${javac.test.processorpath}" sourcepath="${test.src.dir}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single,-do-compile-test-single,-post-compile-test-single" name="compile-test-single"/> + <!-- + ======================= + JUNIT EXECUTION SECTION + ======================= + --> + <target depends="init" if="have.tests" name="-pre-test-run"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run"> + <j2seproject3:junit testincludes="**/*Test.java"/> + </target> + <target depends="init,compile-test,-pre-test-run,-do-test-run" if="have.tests" name="-post-test-run"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init" if="have.tests" name="test-report"/> + <target depends="init" if="netbeans.home+have.tests" name="-test-browse"/> + <target depends="init,compile-test,-pre-test-run,-do-test-run,test-report,-post-test-run,-test-browse" description="Run unit tests." name="test"/> + <target depends="init" if="have.tests" name="-pre-test-run-single"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single"> + <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> + <j2seproject3:junit excludes="" includes="${test.includes}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single" if="have.tests" name="-post-test-run-single"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single,-post-test-run-single" description="Run single unit test." name="test-single"/> + <!-- + ======================= + JUNIT DEBUGGING SECTION + ======================= + --> + <target depends="init,compile-test" if="have.tests" name="-debug-start-debuggee-test"> + <fail unless="test.class">Must select one file in the IDE or set test.class</fail> + <property location="${build.test.results.dir}/TEST-${test.class}.xml" name="test.report.file"/> + <delete file="${test.report.file}"/> + <mkdir dir="${build.test.results.dir}"/> + <j2seproject3:debug classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" classpath="${ant.home}/lib/ant.jar:${ant.home}/lib/ant-junit.jar:${debug.test.classpath}"> + <customize> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <arg value="${test.class}"/> + <arg value="showoutput=true"/> + <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"/> + <arg value="formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.report.file}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-test" if="netbeans.home+have.tests" name="-debug-start-debugger-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${test.class}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test" name="debug-test"/> + <target depends="init,-pre-debug-fix,compile-test-single" if="netbeans.home" name="-do-debug-fix-test"> + <j2seproject1:nbjpdareload dir="${build.test.classes.dir}"/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix-test" if="netbeans.home" name="debug-fix-test"/> + <!-- + ========================= + APPLET EXECUTION SECTION + ========================= + --> + <target depends="init,compile-single" name="run-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject1:java classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject1:java> + </target> + <!-- + ========================= + APPLET DEBUGGING SECTION + ========================= + --> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject3:debug classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-applet" if="netbeans.home" name="debug-applet"/> + <!-- + =============== + CLEANUP SECTION + =============== + --> + <target name="-deps-clean-init" unless="built-clean.properties"> + <property location="${build.dir}/built-clean.properties" name="built-clean.properties"/> + <delete file="${built-clean.properties}" quiet="true"/> + </target> + <target if="already.built.clean.${basedir}" name="-warn-already-built-clean"> + <echo level="warn" message="Cycle detected: EssentialsSigns was already built"/> + </target> + <target depends="init,-deps-clean-init" name="deps-clean" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-clean.properties}" verbose="false"/> + <property file="${built-clean.properties}" prefix="already.built.clean."/> + <antcall target="-warn-already-built-clean"/> + <propertyfile file="${built-clean.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-clean.properties}"/> + <param location="${project.Essentials}" name="call.subproject"/> + <param location="${project.Essentials}/build.xml" name="call.script"/> + <param name="call.target" value="clean"/> + <param name="transfer.built-clean.properties" value="${built-clean.properties}"/> + </antcall> + </target> + <target depends="init" name="-do-clean"> + <delete dir="${build.dir}"/> + <delete dir="${dist.dir}" followsymlinks="false" includeemptydirs="true"/> + </target> + <target name="-post-clean"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-clean,-do-clean,-post-clean" description="Clean build products." name="clean"/> + <target name="-check-call-dep"> + <property file="${call.built.properties}" prefix="already.built."/> + <condition property="should.call.dep"> + <not> + <isset property="already.built.${call.subproject}"/> + </not> + </condition> + </target> + <target depends="-check-call-dep" if="should.call.dep" name="-maybe-call-dep"> + <ant antfile="${call.script}" inheritall="false" target="${call.target}"> + <propertyset> + <propertyref prefix="transfer."/> + <mapper from="transfer.*" to="*" type="glob"/> + </propertyset> + </ant> + </target> +</project> diff --git a/EssentialsSigns/nbproject/genfiles.properties b/EssentialsSigns/nbproject/genfiles.properties new file mode 100644 index 000000000..3e6eceb64 --- /dev/null +++ b/EssentialsSigns/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=4bedf084 +build.xml.script.CRC32=560095e7 +build.xml.stylesheet.CRC32=28e38971@1.47.1.46 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=4bedf084 +nbproject/build-impl.xml.script.CRC32=5a15f942 +nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.1.46 diff --git a/EssentialsSigns/nbproject/project.properties b/EssentialsSigns/nbproject/project.properties new file mode 100644 index 000000000..a926ce71d --- /dev/null +++ b/EssentialsSigns/nbproject/project.properties @@ -0,0 +1,125 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=EssentialsSigns +application.vendor= +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=2 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=2 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=2 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=120 +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none +auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAnnotationArgs=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineArrayInit=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAssignment=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineBinaryOp=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineCallArgs=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineDisjunctiveCatchTypes=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineFor=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineImplements=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineMethodParams=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineParenthesized=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTernaryOp=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineThrows=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTryResources=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesBeforeClass=2 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.classDeclBracePlacement=NEW_LINE +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs=false +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder=* +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width=4 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.methodDeclBracePlacement=NEW_LINE +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.otherBracePlacement=NEW_LINE +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeCatchOnNewLine=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeElseOnNewLine=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeFinallyOnNewLine=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeWhileOnNewLine=true +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.separateImportGroups=false +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab=4 +auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size=4 +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/EssentialsSigns.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.bukkit.jar=../lib/bukkit.jar +includes=** +jar.archive.disabled=${jnlp.enabled} +jar.compress=false +jar.index=${jnlp.enabled} +javac.classpath=\ + ${file.reference.bukkit.jar}:\ + ${reference.Essentials.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=no.codebase +jnlp.descriptor=application +jnlp.enabled=false +jnlp.mixed.code=default +jnlp.offline-allowed=false +jnlp.signed=false +jnlp.signing= +jnlp.signing.alias= +jnlp.signing.keystore= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +project.Essentials=../Essentials +reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/EssentialsSigns/nbproject/project.xml b/EssentialsSigns/nbproject/project.xml new file mode 100644 index 000000000..ad4b7b064 --- /dev/null +++ b/EssentialsSigns/nbproject/project.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://www.netbeans.org/ns/project/1"> + <type>org.netbeans.modules.java.j2seproject</type> + <configuration> + <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> + <name>EssentialsSigns</name> + <source-roots> + <root id="src.dir"/> + </source-roots> + <test-roots> + <root id="test.src.dir"/> + </test-roots> + </data> + <libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1"> + <definitions>../lib/nblibraries.properties</definitions> + </libraries> + <references xmlns="http://www.netbeans.org/ns/ant-project-references/1"> + <reference> + <foreign-project>Essentials</foreign-project> + <artifact-type>jar</artifact-type> + <script>build.xml</script> + <target>jar</target> + <clean-target>clean</clean-target> + <id>jar</id> + </reference> + </references> + </configuration> +</project> diff --git a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java b/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSign.java index b0df73a42..abef8dd25 100644 --- a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSign.java @@ -1,7 +1,11 @@ package com.earth2me.essentials.signs; +import com.earth2me.essentials.ChargeException; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.*; +import com.earth2me.essentials.Trade; +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import java.util.HashSet; import java.util.Locale; import java.util.Set; @@ -27,7 +31,7 @@ public class EssentialsSign public final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess) { final ISign sign = new EventSign(event); - final User user = ess.getUser(event.getPlayer()); + final IUser user = ess.getUser(event.getPlayer()); if (!(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".create") || user.isAuthorized("essentials.signs.create." + signName.toLowerCase(Locale.ENGLISH)))) { @@ -47,11 +51,11 @@ public class EssentialsSign } catch (ChargeException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); } catch (SignException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); } // Return true, so the player sees the wrong sign. return true; @@ -67,7 +71,7 @@ public class EssentialsSign return _("signFormatTemplate", this.signName); } - private String getUsername(final User user) + private String getUsername(final IUser user) { return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length()); } @@ -75,7 +79,7 @@ public class EssentialsSign 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); + final IUser user = ess.getUser(player); try { return (user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".use") @@ -84,12 +88,12 @@ public class EssentialsSign } catch (ChargeException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user,signName, ex); return false; } catch (SignException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); return false; } } @@ -97,7 +101,7 @@ public class EssentialsSign 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); + final IUser user = ess.getUser(player); try { return (user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".break") @@ -106,72 +110,72 @@ public class EssentialsSign } catch (SignException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); return false; } } - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignCreate(final ISign sign, final IUser 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 + protected boolean onSignInteract(final ISign sign, final IUser 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 + protected boolean onSignBreak(final ISign sign, final IUser 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); + IUser user = ess.getUser(player); try { return onBlockPlace(block, user, getUsername(user), ess); } catch (ChargeException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); } catch (SignException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); } return false; } public final boolean onBlockInteract(final Block block, final Player player, final IEssentials ess) { - User user = ess.getUser(player); + IUser user = ess.getUser(player); try { return onBlockInteract(block, user, getUsername(user), ess); } catch (ChargeException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); } catch (SignException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); } return false; } public final boolean onBlockBreak(final Block block, final Player player, final IEssentials ess) { - User user = ess.getUser(player); + IUser user = ess.getUser(player); try { return onBlockBreak(block, user, getUsername(user), ess); } catch (SignException ex) { - ess.showError(user, ex, signName); + ess.getCommandHandler().showCommandError(user, signName, ex); } return false; } @@ -235,17 +239,17 @@ public class EssentialsSign return sign.getLine(0).matches("§1\\[.*\\]"); } - protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onBlockPlace(final Block block, final IUser 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 + protected boolean onBlockInteract(final Block block, final IUser 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 + protected boolean onBlockBreak(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException { return true; } @@ -271,7 +275,7 @@ public class EssentialsSign } protected final void validateTrade(final ISign sign, final int amountIndex, final int itemIndex, - final User player, final IEssentials ess) throws SignException + final IUser player, final IEssentials ess) throws SignException { if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) { @@ -287,7 +291,7 @@ public class EssentialsSign } protected final Trade getTrade(final ISign sign, final int amountIndex, final int itemIndex, - final User player, final IEssentials ess) throws SignException + final IUser player, final IEssentials ess) throws SignException { if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) { diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSignsPlugin.java b/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSignsPlugin.java new file mode 100644 index 000000000..d57daf319 --- /dev/null +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSignsPlugin.java @@ -0,0 +1,62 @@ +package com.earth2me.essentials.signs; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsSignsPlugin extends JavaPlugin +{ + private static final transient Logger LOGGER = Bukkit.getLogger(); + private transient IEssentials ess; + + public void onEnable() + { + final PluginManager pluginManager = getServer().getPluginManager(); + ess = (IEssentials)pluginManager.getPlugin("Essentials"); + if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) + { + LOGGER.log(Level.WARNING, _("versionMismatchAll")); + } + if (!ess.isEnabled()) + { + this.setEnabled(false); + return; + } + + final SignBlockListener signBlockListener = new SignBlockListener(ess); + pluginManager.registerEvent(Event.Type.SIGN_CHANGE, signBlockListener, Event.Priority.Highest, this); + pluginManager.registerEvent(Event.Type.BLOCK_PLACE, signBlockListener, Event.Priority.Low, this); + pluginManager.registerEvent(Event.Type.BLOCK_BREAK, signBlockListener, Event.Priority.Highest, this); + pluginManager.registerEvent(Event.Type.BLOCK_IGNITE, signBlockListener, Event.Priority.Low, this); + pluginManager.registerEvent(Event.Type.BLOCK_BURN, signBlockListener, Event.Priority.Low, this); + pluginManager.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, signBlockListener, Event.Priority.Low, this); + pluginManager.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, signBlockListener, Event.Priority.Low, this); + + final SignPlayerListener signPlayerListener = new SignPlayerListener(ess); + pluginManager.registerEvent(Event.Type.PLAYER_INTERACT, signPlayerListener, Event.Priority.Low, this); + + final SignEntityListener signEntityListener = new SignEntityListener(ess); + pluginManager.registerEvent(Event.Type.ENTITY_EXPLODE, signEntityListener, Event.Priority.Low, this); + pluginManager.registerEvent(Event.Type.ENDERMAN_PICKUP, signEntityListener, Event.Priority.Low, this); + //final SignBlockListener signBlockListener = new SignBlockListener(ess); + pluginManager.registerEvents(signBlockListener, this); + + //final SignPlayerListener signPlayerListener = new SignPlayerListener(ess); + pluginManager.registerEvents(signPlayerListener, this); + + //final SignEntityListener signEntityListener = new SignEntityListener(ess); + pluginManager.registerEvents(signEntityListener, this); + + LOGGER.info(_("loadinfo", this.getDescription().getName(), this.getDescription().getVersion(), "essentials team")); + } + + public void onDisable() + { + } +} diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBalance.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBalance.java index 0b7328ba5..2ef64003a 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignBalance.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBalance.java @@ -1,8 +1,8 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; public class SignBalance extends EssentialsSign @@ -13,7 +13,7 @@ public class SignBalance extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { player.sendMessage(_("balance", player.getMoney())); return true; diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBlockListener.java index 913de6358..a072cd038 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBlockListener.java @@ -1,7 +1,7 @@ package com.earth2me.essentials.signs; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Material; @@ -19,7 +19,7 @@ public class SignBlockListener implements Listener private final transient IEssentials ess; private final static Logger LOGGER = Logger.getLogger("Minecraft"); - public SignBlockListener(IEssentials ess) + public SignBlockListener(final IEssentials ess) { this.ess = ess; } @@ -27,7 +27,7 @@ public class SignBlockListener implements Listener @EventHandler(priority = EventPriority.HIGHEST) public void onBlockBreak(final BlockBreakEvent event) { - if (event.isCancelled() || ess.getSettings().areSignsDisabled()) + if (event.isCancelled()) { return; } @@ -79,11 +79,11 @@ public class SignBlockListener implements Listener @EventHandler(priority = EventPriority.HIGHEST) public void onSignChange(final SignChangeEvent event) { - if (event.isCancelled() || ess.getSettings().areSignsDisabled()) + if (event.isCancelled()) { return; } - User user = ess.getUser(event.getPlayer()); + IUser user = ess.getUser(event.getPlayer()); if (user.isAuthorized("essentials.signs.color")) { for (int i = 0; i < 4; i++) @@ -111,7 +111,7 @@ public class SignBlockListener implements Listener @EventHandler(priority = EventPriority.LOW) public void onBlockPlace(final BlockPlaceEvent event) { - if (event.isCancelled() || ess.getSettings().areSignsDisabled()) + if (event.isCancelled()) { return; } @@ -145,7 +145,7 @@ public class SignBlockListener implements Listener @EventHandler(priority = EventPriority.LOW) public void onBlockBurn(final BlockBurnEvent event) { - if (event.isCancelled() || ess.getSettings().areSignsDisabled()) + if (event.isCancelled()) { return; } @@ -174,7 +174,7 @@ public class SignBlockListener implements Listener @EventHandler(priority = EventPriority.LOW) public void onBlockIgnite(final BlockIgniteEvent event) { - if (event.isCancelled() || ess.getSettings().areSignsDisabled()) + if (event.isCancelled()) { return; } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBuy.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBuy.java index aa4e41426..e35e78b50 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignBuy.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBuy.java @@ -1,9 +1,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; public class SignBuy extends EssentialsSign @@ -14,7 +14,7 @@ public class SignBuy extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { validateTrade(sign, 1, 2, player, ess); validateTrade(sign, 3, ess); @@ -22,7 +22,7 @@ public class SignBuy extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(final ISign sign, final IUser 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); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignDisposal.java index f747ac07c..a6c64ca0b 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignDisposal.java @@ -1,7 +1,7 @@ package com.earth2me.essentials.signs; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.craftbukkit.ShowInventory; @@ -13,7 +13,7 @@ public class SignDisposal extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) { ShowInventory.showEmptyInventory(player.getBase()); return true; diff --git a/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignEnchant.java index 5907442d9..3800c50de 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignEnchant.java @@ -2,13 +2,11 @@ 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 com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import java.util.Locale; -import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; @@ -21,7 +19,7 @@ public class SignEnchant extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignCreate(final ISign sign, final IUser 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(":"); @@ -64,7 +62,7 @@ public class SignEnchant extends EssentialsSign } @Override - protected boolean onSignInteract(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(ISign sign, IUser 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; diff --git a/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignEntityListener.java index 281afdc98..2d3413559 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignEntityListener.java @@ -1,6 +1,6 @@ package com.earth2me.essentials.signs; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.api.IEssentials; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; @@ -47,7 +47,7 @@ public class SignEntityListener implements Listener @EventHandler(priority = EventPriority.LOW) public void onEndermanPickup(final EndermanPickupEvent event) { - if (event.isCancelled() || ess.getSettings().areSignsDisabled()) + if (event.isCancelled()) { return; } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignException.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignException.java index 9c9ab44a2..9c9ab44a2 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignException.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignException.java diff --git a/Essentials/src/com/earth2me/essentials/signs/SignFree.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignFree.java index 7af7dffd7..4e77a2ad7 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignFree.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignFree.java @@ -1,9 +1,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.craftbukkit.ShowInventory; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -17,14 +17,14 @@ public class SignFree extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser 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 + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { final ItemStack item = getItemStack(sign.getLine(1), 1, ess); if (item.getType() == Material.AIR) diff --git a/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignGameMode.java index 37a9fb1b8..0068cadf8 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignGameMode.java @@ -2,9 +2,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; import java.util.Locale; import org.bukkit.GameMode; @@ -17,14 +17,14 @@ public class SignGameMode extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser 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 + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException { final Trade charge = getTrade(sign, 1, ess); charge.isAffordableFor(player); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignHeal.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignHeal.java index be8b7ba1d..ba10f3586 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignHeal.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignHeal.java @@ -2,9 +2,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; public class SignHeal extends EssentialsSign @@ -15,14 +15,14 @@ public class SignHeal extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser 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 + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException { final Trade charge = getTrade(sign, 1, ess); charge.isAffordableFor(player); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignKit.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignKit.java index 32a169592..87f9bb118 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignKit.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignKit.java @@ -1,9 +1,11 @@ package com.earth2me.essentials.signs; -import com.earth2me.essentials.*; -import java.util.List; +import com.earth2me.essentials.ChargeException; +import com.earth2me.essentials.Trade; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; +import com.earth2me.essentials.settings.Kit; import java.util.Locale; -import java.util.Map; public class SignKit extends EssentialsSign @@ -14,7 +16,7 @@ public class SignKit extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { validateTrade(sign, 3, ess); @@ -29,7 +31,7 @@ public class SignKit extends EssentialsSign { try { - ess.getSettings().getKit(kitName); + ess.getKits().getKit(kitName); } catch (Exception ex) { @@ -45,7 +47,7 @@ public class SignKit extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(final ISign sign, final IUser 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); @@ -56,10 +58,9 @@ public class SignKit extends EssentialsSign charge.isAffordableFor(player); try { - final Object kit = ess.getSettings().getKit(kitName); - final Map<String, Object> els = (Map<String, Object>)kit; - final List<String> items = Kit.getItems(player, els); - Kit.expandItems(ess, player, items); + final Kit kit = ess.getKits().getKit(kitName); + ess.getKits().sendKit(player, kit); + charge.charge(player); } catch (Exception ex) diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignMail.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignMail.java new file mode 100644 index 000000000..7845c86a6 --- /dev/null +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignMail.java @@ -0,0 +1,41 @@ +package com.earth2me.essentials.signs; + +import static com.earth2me.essentials.I18n._; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; +import java.util.List; + + +public class SignMail extends EssentialsSign +{ + public SignMail() + { + super("Mail"); + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + final List<String> mail; + player.acquireReadLock(); + try + { + mail = player.getData().getMails(); + } + finally + { + player.unlock(); + } + if (mail == null || 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/EssentialsSigns/src/com/earth2me/essentials/signs/SignPlayerListener.java index f1ba79b0b..dd2219ef8 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignPlayerListener.java @@ -1,6 +1,6 @@ package com.earth2me.essentials.signs; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.api.IEssentials; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; @@ -23,7 +23,7 @@ public class SignPlayerListener implements Listener @EventHandler(priority = EventPriority.LOW) public void onPlayerInteract(final PlayerInteractEvent event) { - if (event.isCancelled() || ess.getSettings().areSignsDisabled()) + if (event.isCancelled()) { return; } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignProtection.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignProtection.java index f64b6f3f1..9dc68087e 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignProtection.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignProtection.java @@ -2,10 +2,10 @@ 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 com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import java.util.*; import org.bukkit.Location; import org.bukkit.Material; @@ -29,7 +29,7 @@ public class SignProtection extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException { sign.setLine(3, "§4" + username); if (hasAdjacentBlock(sign.getBlock())) @@ -47,7 +47,7 @@ public class SignProtection extends EssentialsSign } @Override - protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignBreak(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { final SignProtectionState state = checkProtectionSign(sign, player, username); return state == SignProtectionState.OWNER; @@ -73,7 +73,7 @@ public class SignProtection extends EssentialsSign return false; } - private void checkIfSignsAreBroken(final Block block, final User player, final String username, final IEssentials ess) + private void checkIfSignsAreBroken(final Block block, final IUser 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()) @@ -91,14 +91,14 @@ public class SignProtection extends EssentialsSign } } - private Map<Location, SignProtectionState> getConnectedSigns(final Block block, final User user, final String username, boolean secure) + private Map<Location, SignProtectionState> getConnectedSigns(final Block block, final IUser 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) + private void getConnectedSigns(final Block block, final Map<Location, SignProtectionState> signs, final IUser user, final String username, final int depth) { final Block[] faces = getAdjacentBlocks(block); for (Block b : faces) @@ -124,7 +124,7 @@ public class SignProtection extends EssentialsSign NOT_ALLOWED, ALLOWED, NOSIGN, OWNER } - private SignProtectionState checkProtectionSign(final Block block, final User user, final String username) + private SignProtectionState checkProtectionSign(final Block block, final IUser user, final String username) { if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) { @@ -137,7 +137,7 @@ public class SignProtection extends EssentialsSign return SignProtectionState.NOSIGN; } - private SignProtectionState checkProtectionSign(final ISign sign, final User user, final String username) + private SignProtectionState checkProtectionSign(final ISign sign, final IUser user, final String username) { if (user == null || username == null) { @@ -179,7 +179,7 @@ public class SignProtection extends EssentialsSign }; } - public SignProtectionState isBlockProtected(final Block block, final User user, final String username, boolean secure) + public SignProtectionState isBlockProtected(final Block block, final IUser user, final String username, boolean secure) { final Map<Location, SignProtectionState> signs = getConnectedSigns(block, user, username, secure); SignProtectionState retstate = SignProtectionState.NOSIGN; @@ -247,7 +247,7 @@ public class SignProtection extends EssentialsSign } @Override - protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onBlockPlace(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException { for (Block adjBlock : getAdjacentBlocks(block)) { @@ -265,7 +265,7 @@ public class SignProtection extends EssentialsSign } @Override - protected boolean onBlockInteract(final Block block, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onBlockInteract(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException { final SignProtectionState state = isBlockProtected(block, player, username, false); @@ -286,7 +286,7 @@ public class SignProtection extends EssentialsSign } @Override - protected boolean onBlockBreak(final Block block, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onBlockBreak(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException { final SignProtectionState state = isBlockProtected(block, player, username, false); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignSell.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignSell.java index 442a503c2..4e16be23d 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignSell.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignSell.java @@ -1,9 +1,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; public class SignSell extends EssentialsSign @@ -14,7 +14,7 @@ public class SignSell extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { validateTrade(sign, 1, 2, player, ess); validateTrade(sign, 3, ess); @@ -22,7 +22,7 @@ public class SignSell extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(final ISign sign, final IUser 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); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignSpawnmob.java index 7c4cfcd54..4c6d1238a 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignSpawnmob.java @@ -1,9 +1,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.commands.Commandspawnmob; @@ -15,27 +15,29 @@ public class SignSpawnmob extends EssentialsSign } @Override - protected boolean onSignCreate(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException + protected boolean onSignCreate(ISign sign, IUser player, String username, IEssentials ess) throws SignException, ChargeException { validateInteger(sign, 1); validateTrade(sign, 3, ess); return true; } + + //TODO: This should call a method not a command @Override - protected boolean onSignInteract(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(ISign sign, IUser 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); + Commandspawnmob command = new Commandspawnmob(); + command.init(ess, "spawnmob"); String[] args = new String[] { sign.getLine(2), sign.getLine(1) }; try { - command.run(ess.getServer(), player, "spawnmob", args); + command.run(player, "spawnmob", args); } catch (Exception ex) { diff --git a/Essentials/src/com/earth2me/essentials/signs/SignTime.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignTime.java index 99c579ff4..8480a1d83 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignTime.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignTime.java @@ -2,9 +2,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; public class SignTime extends EssentialsSign @@ -15,7 +15,7 @@ public class SignTime extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { validateTrade(sign, 2, ess); final String timeString = sign.getLine(1); @@ -33,7 +33,7 @@ public class SignTime extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException { final Trade charge = getTrade(sign, 2, ess); charge.isAffordableFor(player); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignTrade.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignTrade.java index 943a14a83..796d9fdd6 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignTrade.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignTrade.java @@ -1,7 +1,11 @@ package com.earth2me.essentials.signs; +import com.earth2me.essentials.ChargeException; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.*; +import com.earth2me.essentials.Trade; +import com.earth2me.essentials.Util; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import org.bukkit.inventory.ItemStack; //TODO: Sell Enchantment on Trade signs? @@ -14,7 +18,7 @@ public class SignTrade extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException { validateTrade(sign, 1, false, ess); validateTrade(sign, 2, true, ess); @@ -27,7 +31,7 @@ public class SignTrade extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException { if (sign.getLine(3).substring(2).equalsIgnoreCase(username)) { @@ -66,7 +70,7 @@ public class SignTrade extends EssentialsSign return true; } - private Trade rechargeSign(final ISign sign, final IEssentials ess, final User player) throws SignException, ChargeException + private Trade rechargeSign(final ISign sign, final IEssentials ess, final IUser player) throws SignException, ChargeException { final Trade trade = getTrade(sign, 2, false, false, ess); if (trade.getItemStack() != null && player.getItemInHand() != null @@ -90,7 +94,7 @@ public class SignTrade extends EssentialsSign } @Override - protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignBreak(final ISign sign, final IUser 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")) diff --git a/Essentials/src/com/earth2me/essentials/signs/SignWarp.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignWarp.java index 76e8e730b..70a4f53c1 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignWarp.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignWarp.java @@ -1,9 +1,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; @@ -15,7 +15,7 @@ public class SignWarp extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { validateTrade(sign, 3, ess); final String warpName = sign.getLine(1); @@ -45,14 +45,13 @@ public class SignWarp extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(final ISign sign, final IUser 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)))) + + if ((!group.isEmpty() && ("§2Everyone".equals(group) || player.inGroup(group))) + || (group.isEmpty() && player.isAuthorized("essentials.warp." + warpName))) { final Trade charge = getTrade(sign, 3, ess); try diff --git a/Essentials/src/com/earth2me/essentials/signs/SignWeather.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignWeather.java index 559fcc2e3..bc019b0cd 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignWeather.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/SignWeather.java @@ -2,9 +2,9 @@ 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.api.IEssentials; +import com.earth2me.essentials.api.IUser; public class SignWeather extends EssentialsSign @@ -15,7 +15,7 @@ public class SignWeather extends EssentialsSign } @Override - protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException { validateTrade(sign, 2, ess); final String timeString = sign.getLine(1); @@ -33,7 +33,7 @@ public class SignWeather extends EssentialsSign } @Override - protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException { final Trade charge = getTrade(sign, 2, ess); charge.isAffordableFor(player); diff --git a/Essentials/src/com/earth2me/essentials/signs/Signs.java b/EssentialsSigns/src/com/earth2me/essentials/signs/Signs.java index e29d45ad4..e29d45ad4 100644 --- a/Essentials/src/com/earth2me/essentials/signs/Signs.java +++ b/EssentialsSigns/src/com/earth2me/essentials/signs/Signs.java diff --git a/EssentialsSigns/src/plugin.yml b/EssentialsSigns/src/plugin.yml new file mode 100644 index 000000000..515742d25 --- /dev/null +++ b/EssentialsSigns/src/plugin.yml @@ -0,0 +1,9 @@ +# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) +name: EssentialsSigns +main: com.earth2me.essentials.signs.EssentialsSignsPlugin +# Note to developers: This next line cannot change, or the automatic versioning system will break. +version: TeamCity +website: http://tiny.cc/EssentialsWiki +description: Provides signs, utilizing Essentials. +authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits] +depend: [Essentials]
\ No newline at end of file diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java index c6c89a20d..d0383bd4a 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java @@ -1,20 +1,14 @@ package com.earth2me.essentials.spawn; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.commands.EssentialsCommand; -import org.bukkit.Server; public class Commandsetspawn extends EssentialsCommand { - public Commandsetspawn() - { - super("setspawn"); - } - @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 String group = args.length > 0 ? getFinalArg(args, 0) : "default"; ((SpawnStorage)module).setSpawn(user.getLocation(), group); diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java index 6335d6c69..07532653c 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java @@ -2,30 +2,24 @@ package com.earth2me.essentials.spawn; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.Trade; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.commands.EssentialsCommand; import com.earth2me.essentials.commands.NotEnoughArgumentsException; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandspawn extends EssentialsCommand { - public Commandspawn() - { - super("spawn"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final Trade charge = new Trade(this.getName(), ess); + 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 && user.isAuthorized("essentials.spawn.others")) { - final User otherUser = getPlayer(server, args, 0); + final IUser otherUser = getPlayer(args, 0); respawn(otherUser, null); if (!otherUser.equals(user)) { @@ -34,27 +28,28 @@ public class Commandspawn extends EssentialsCommand } } else - { + { respawn(user, null); } } @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); respawn(user, null); user.sendMessage(_("teleportAtoB", user.getDisplayName(), "spawn")); sender.sendMessage(_("teleporting")); } - - private void respawn (final User user, final Trade charge) throws Exception { + + private void respawn(final IUser user, final Trade charge) throws Exception + { final SpawnStorage spawns = (SpawnStorage)this.module; final Location spawn = spawns.getSpawn(user.getGroup()); - user.getTeleport().teleport(spawn, charge, TeleportCause.COMMAND); + user.getTeleport().teleport(spawn, charge, TeleportCause.COMMAND); } } diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java index f0c5ee466..1d73ee4c1 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java @@ -1,7 +1,9 @@ package com.earth2me.essentials.spawn; +import com.earth2me.essentials.EssentialsCommandHandler; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; +import com.earth2me.essentials.api.ICommandHandler; +import com.earth2me.essentials.api.IEssentials; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; @@ -22,6 +24,7 @@ public class EssentialsSpawn extends JavaPlugin private static final Logger LOGGER = Bukkit.getLogger(); private transient IEssentials ess; private transient SpawnStorage spawns; + private transient ICommandHandler commandHandler; public void onEnable() { @@ -40,8 +43,10 @@ public class EssentialsSpawn extends JavaPlugin spawns = new SpawnStorage(ess); ess.addReloadListener(spawns); + commandHandler = new EssentialsCommandHandler(EssentialsSpawn.class.getClassLoader(), "com.earth2me.essentials.spawn.Command", "essentials.", spawns, ess); + final EssentialsSpawnPlayerListener playerListener = new EssentialsSpawnPlayerListener(ess, spawns); - pluginManager.registerEvent(PlayerRespawnEvent.class, playerListener, ess.getSettings().getRespawnPriority(), new EventExecutor() + pluginManager.registerEvent(PlayerRespawnEvent.class, playerListener, spawns.getRespawnPriority(), new EventExecutor() { @Override public void execute(final Listener ll, final Event event) throws EventException @@ -49,7 +54,7 @@ public class EssentialsSpawn extends JavaPlugin ((EssentialsSpawnPlayerListener)ll).onPlayerRespawn((PlayerRespawnEvent)event); } }, this); - pluginManager.registerEvent(PlayerJoinEvent.class, playerListener, ess.getSettings().getRespawnPriority(), new EventExecutor() + pluginManager.registerEvent(PlayerJoinEvent.class, playerListener, spawns.getRespawnPriority(), new EventExecutor() { @Override public void execute(final Listener ll, final Event event) throws EventException @@ -67,6 +72,6 @@ public class EssentialsSpawn extends JavaPlugin public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) { - return ess.onCommandEssentials(sender, command, commandLabel, args, EssentialsSpawn.class.getClassLoader(), "com.earth2me.essentials.spawn.Command", "essentials.", spawns); + return commandHandler.handleCommand(sender, command, commandLabel, args); } } diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java index 2814714a2..21bd0d499 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java @@ -1,10 +1,10 @@ package com.earth2me.essentials.spawn; 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 java.util.logging.Level; -import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.event.Listener; @@ -17,7 +17,6 @@ public class EssentialsSpawnPlayerListener implements Listener { private final transient IEssentials ess; private final transient SpawnStorage spawns; - private static final Logger LOGGER = Bukkit.getLogger(); public EssentialsSpawnPlayerListener(final IEssentials ess, final SpawnStorage spawns) { @@ -27,10 +26,21 @@ public class EssentialsSpawnPlayerListener implements Listener } public void onPlayerRespawn(final PlayerRespawnEvent event) - { - final User user = ess.getUser(event.getPlayer()); + { + final IUser user = ess.getUser(event.getPlayer()); - if (ess.getSettings().getRespawnAtHome()) + 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 = user.getHome(user.getLocation()); if (home == null) @@ -52,32 +62,30 @@ public class EssentialsSpawnPlayerListener implements Listener public void onPlayerJoin(final PlayerJoinEvent event) { - final User user = ess.getUser(event.getPlayer()); + final IUser user = ess.getUser(event.getPlayer()); if (user.hasPlayedBefore()) { - LOGGER.log(Level.FINE, "Old player join"); return; - } - if (!"none".equalsIgnoreCase(ess.getSettings().getNewbieSpawn())) + } + + if (spawns.getNewbieSpawn() != null) { ess.scheduleSyncDelayedTask(new NewPlayerTeleport(user), 1L); } - if (ess.getSettings().getAnnounceNewPlayers()) + if (spawns.getAnnounceNewPlayers()) { - ess.broadcastMessage(user, ess.getSettings().getAnnounceNewPlayerFormat(user)); + ess.broadcastMessage(user, spawns.getAnnounceNewPlayerFormat(user)); } - - LOGGER.log(Level.FINE, "New player join"); } private class NewPlayerTeleport implements Runnable { - private final transient User user; + private final transient IUser user; - public NewPlayerTeleport(final User user) + public NewPlayerTeleport(final IUser user) { this.user = user; } @@ -87,7 +95,7 @@ public class EssentialsSpawnPlayerListener implements Listener { try { - Location spawn = spawns.getSpawn(ess.getSettings().getNewbieSpawn()); + final Location spawn = spawns.getNewbieSpawn(); if (spawn != null) { user.getTeleport().now(spawn, false, TeleportCause.PLUGIN); diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/SpawnStorage.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/SpawnStorage.java index 088ee9052..13eb1f7df 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/SpawnStorage.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/SpawnStorage.java @@ -1,7 +1,8 @@ package com.earth2me.essentials.spawn; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.IEssentialsModule; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IEssentialsModule; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.settings.Spawns; import com.earth2me.essentials.storage.AsyncStorageObjectHolder; import java.io.File; @@ -10,6 +11,8 @@ import java.util.Locale; import java.util.Map; import org.bukkit.Location; import org.bukkit.World; +import org.bukkit.event.Event.Priority; +import org.bukkit.event.EventPriority; public class SpawnStorage extends AsyncStorageObjectHolder<Spawns> implements IEssentialsModule @@ -17,7 +20,7 @@ public class SpawnStorage extends AsyncStorageObjectHolder<Spawns> implements IE public SpawnStorage(final IEssentials ess) { super(ess, Spawns.class); - reloadConfig(); + onReload(); } @Override @@ -87,4 +90,58 @@ public class SpawnStorage extends AsyncStorageObjectHolder<Spawns> implements IE } 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}", user.getGroup()).replace("{USERNAME}", user.getName()).replace("{ADDRESS}", user.getAddress().toString()); + } finally { + unlock(); + } + } } diff --git a/EssentialsSpawn/src/plugin.yml b/EssentialsSpawn/src/plugin.yml index a91031fbe..c1cd00280 100644 --- a/EssentialsSpawn/src/plugin.yml +++ b/EssentialsSpawn/src/plugin.yml @@ -3,7 +3,7 @@ name: EssentialsSpawn main: com.earth2me.essentials.spawn.EssentialsSpawn # Note to developers: This next line cannot change, or the automatic versioning system will break. version: TeamCity -website: http://www.earth2me.net:8001/ +website: http://tiny.cc/EssentialsWiki description: Provides spawn control commands, utilizing Essentials. authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits] depend: [Essentials] diff --git a/EssentialsUpdate/src/plugin.yml b/EssentialsUpdate/src/plugin.yml index b8dbe8e25..45c821265 100644 --- a/EssentialsUpdate/src/plugin.yml +++ b/EssentialsUpdate/src/plugin.yml @@ -4,6 +4,7 @@ main: com.earth2me.essentials.update.EssentialsUpdate # Note to developers: This next line cannot change, or the automatic versioning system will break. version: TeamCity description: This plugin allows to install or update all Essentials plugins +website: http://tiny.cc/EssentialsWiki authors: [snowleo] commands: essentialsupdate: diff --git a/EssentialsXMPP/nbproject/build-impl.xml b/EssentialsXMPP/nbproject/build-impl.xml index 3293bd709..239c397bf 100644 --- a/EssentialsXMPP/nbproject/build-impl.xml +++ b/EssentialsXMPP/nbproject/build-impl.xml @@ -610,6 +610,13 @@ is divided into following sections: <param name="call.target" value="jar"/> <param name="transfer.built-jar.properties" value="${built-jar.properties}"/> </antcall> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-jar.properties}"/> + <param location="${project.Essentials2Compat}" name="call.subproject"/> + <param location="${project.Essentials2Compat}/build.xml" name="call.script"/> + <param name="call.target" value="jar"/> + <param name="transfer.built-jar.properties" value="${built-jar.properties}"/> + </antcall> </target> <target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/> <target depends="init" name="-check-automatic-build"> @@ -1063,6 +1070,13 @@ is divided into following sections: <param name="call.target" value="clean"/> <param name="transfer.built-clean.properties" value="${built-clean.properties}"/> </antcall> + <antcall target="-maybe-call-dep"> + <param name="call.built.properties" value="${built-clean.properties}"/> + <param location="${project.Essentials2Compat}" name="call.subproject"/> + <param location="${project.Essentials2Compat}/build.xml" name="call.script"/> + <param name="call.target" value="clean"/> + <param name="transfer.built-clean.properties" value="${built-clean.properties}"/> + </antcall> </target> <target depends="init" name="-do-clean"> <delete dir="${build.dir}"/> diff --git a/EssentialsXMPP/nbproject/genfiles.properties b/EssentialsXMPP/nbproject/genfiles.properties index ae2a6f962..bb9779474 100644 --- a/EssentialsXMPP/nbproject/genfiles.properties +++ b/EssentialsXMPP/nbproject/genfiles.properties @@ -3,6 +3,6 @@ build.xml.script.CRC32=db2fb22f build.xml.stylesheet.CRC32=28e38971@1.42.1.45 # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=1012a5dd -nbproject/build-impl.xml.script.CRC32=8cccbe45 +nbproject/build-impl.xml.data.CRC32=6a299da6 +nbproject/build-impl.xml.script.CRC32=a83e8167 nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.1.46 diff --git a/EssentialsXMPP/nbproject/project.properties b/EssentialsXMPP/nbproject/project.properties index 66d780451..dd7aa95e3 100644 --- a/EssentialsXMPP/nbproject/project.properties +++ b/EssentialsXMPP/nbproject/project.properties @@ -72,7 +72,8 @@ jar.index=${jnlp.enabled} javac.classpath=\ ${reference.Essentials.jar}:\ ${file.reference.smack-3.2.1.jar}:\ - ${file.reference.bukkit.jar} + ${file.reference.bukkit.jar}:\ + ${reference.Essentials2Compat.jar} # Space-separated list of extra javac options javac.compilerargs=-Xlint:unchecked javac.deprecation=false @@ -112,7 +113,9 @@ meta.inf.dir=${src.dir}/META-INF mkdist.disabled=true platform.active=default_platform project.Essentials=../Essentials +project.Essentials2Compat=../Essentials2Compat reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar +reference.Essentials2Compat.jar=${project.Essentials2Compat}/dist/Essentials2Compat.jar run.classpath=\ ${javac.classpath}:\ ${build.classes.dir} diff --git a/EssentialsXMPP/nbproject/project.xml b/EssentialsXMPP/nbproject/project.xml index 5c9eee1dd..e5ee6cd11 100644 --- a/EssentialsXMPP/nbproject/project.xml +++ b/EssentialsXMPP/nbproject/project.xml @@ -23,6 +23,14 @@ <clean-target>clean</clean-target> <id>jar</id> </reference> + <reference> + <foreign-project>Essentials2Compat</foreign-project> + <artifact-type>jar</artifact-type> + <script>build.xml</script> + <target>jar</target> + <clean-target>clean</clean-target> + <id>jar</id> + </reference> </references> </configuration> </project> diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java index e0bf9827c..4fe9283df 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java @@ -1,20 +1,14 @@ package com.earth2me.essentials.xmpp; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IUser; import com.earth2me.essentials.commands.EssentialsCommand; import com.earth2me.essentials.commands.NotEnoughArgumentsException; -import org.bukkit.Server; public class Commandsetxmpp extends EssentialsCommand { - public Commandsetxmpp() - { - super("setxmpp"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws NotEnoughArgumentsException + protected void run(final IUser user, final String commandLabel, final String[] args) throws NotEnoughArgumentsException { if (args.length < 1) { diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java index e7dd01670..23bd34170 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java @@ -3,20 +3,14 @@ package com.earth2me.essentials.xmpp; import com.earth2me.essentials.Console; import com.earth2me.essentials.commands.EssentialsCommand; import com.earth2me.essentials.commands.NotEnoughArgumentsException; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandxmpp extends EssentialsCommand { - public Commandxmpp() - { - super("xmpp"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException { if (args.length < 2) { @@ -31,7 +25,7 @@ public class Commandxmpp extends EssentialsCommand else { final String message = getFinalArg(args, 1); - final String senderName = sender instanceof Player ? ess.getUser(sender).getDisplayName() : Console.NAME; + final String senderName = sender instanceof Player ? ess.getUser((Player)sender).getDisplayName() : Console.NAME; sender.sendMessage("[" + senderName + ">" + address + "] " + message); if (!EssentialsXMPP.getInstance().sendMessage(address, "[" + senderName + "] " + message)) { diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java index 4f276c3b9..5da4d8f93 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java @@ -3,20 +3,14 @@ package com.earth2me.essentials.xmpp; import com.earth2me.essentials.commands.EssentialsCommand; import com.earth2me.essentials.commands.NotEnoughArgumentsException; import java.util.List; -import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Commandxmppspy extends EssentialsCommand { - public Commandxmppspy() - { - super("xmppspy"); - } - @Override - protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException { if (args.length < 1) { diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java index b5c011e55..01e1ce131 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java @@ -1,8 +1,10 @@ package com.earth2me.essentials.xmpp; +import com.earth2me.essentials.EssentialsCommandHandler; import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.IUser; +import com.earth2me.essentials.api.ICommandHandler; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import java.util.List; import java.util.Locale; import java.util.logging.Level; @@ -21,6 +23,7 @@ public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP private transient UserManager users; private transient XMPPManager xmpp; private transient IEssentials ess; + private transient ICommandHandler commandHandler; public static IEssentialsXMPP getInstance() { @@ -52,6 +55,8 @@ public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP ess.addReloadListener(users); ess.addReloadListener(xmpp); + + commandHandler = new EssentialsCommandHandler(EssentialsXMPP.class.getClassLoader(), "com.earth2me.essentials.xmpp.Command", "essentials.", ess); } @Override @@ -67,7 +72,7 @@ public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP @Override public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) { - return ess.onCommandEssentials(sender, command, commandLabel, args, EssentialsXMPP.class.getClassLoader(), "com.earth2me.essentials.xmpp.Command", "essentials.", null); + return commandHandler.handleCommand(sender, command, commandLabel, args); } @Override diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java index 1fa5a243c..b6daf8114 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java @@ -1,7 +1,7 @@ package com.earth2me.essentials.xmpp; -import com.earth2me.essentials.IEssentials; -import com.earth2me.essentials.User; +import com.earth2me.essentials.api.IEssentials; +import com.earth2me.essentials.api.IUser; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -23,21 +23,21 @@ class EssentialsXMPPPlayerListener implements Listener @EventHandler(priority= EventPriority.MONITOR) public void onPlayerJoin(final PlayerJoinEvent event) { - final User user = ess.getUser(event.getPlayer()); + final IUser user = ess.getUser(event.getPlayer()); sendMessageToSpyUsers("Player " + user.getDisplayName() + " joined the game"); } @EventHandler(priority= EventPriority.MONITOR) public void onPlayerChat(final PlayerChatEvent event) { - final User user = ess.getUser(event.getPlayer()); + final IUser user = ess.getUser(event.getPlayer()); sendMessageToSpyUsers(String.format(event.getFormat(), user.getDisplayName(), event.getMessage())); } @EventHandler(priority= EventPriority.MONITOR) public void onPlayerQuit(final PlayerQuitEvent event) { - final User user = ess.getUser(event.getPlayer()); + final IUser user = ess.getUser(event.getPlayer()); sendMessageToSpyUsers("Player " + user.getDisplayName() + " left the game"); } diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java index 0635ca131..83851d055 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java @@ -1,6 +1,6 @@ package com.earth2me.essentials.xmpp; -import com.earth2me.essentials.IUser; +import com.earth2me.essentials.api.IUser; import java.util.List; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java index 85ef50949..c8df2fcb3 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java @@ -1,12 +1,12 @@ package com.earth2me.essentials.xmpp; import com.earth2me.essentials.EssentialsConf; -import com.earth2me.essentials.IConf; +import com.earth2me.essentials.api.IReload; import java.io.File; import java.util.*; -public class UserManager implements IConf +public class UserManager implements IReload { private final transient EssentialsConf users; private final transient List<String> spyusers = new ArrayList<String>(); @@ -16,7 +16,7 @@ public class UserManager implements IConf public UserManager(final File folder) { users = new EssentialsConf(new File(folder, "users.yml")); - reloadConfig(); + onReload(); } public final boolean isSpy(final String username) @@ -65,11 +65,11 @@ public class UserManager implements IConf userdata.put(SPY, spy); users.setProperty(username, userdata); users.save(); - reloadConfig(); + onReload(); } @Override - public final void reloadConfig() + public final void onReload() { users.load(); spyusers.clear(); diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java index 72bdb113d..eb321ca81 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java @@ -1,9 +1,8 @@ package com.earth2me.essentials.xmpp; -import com.earth2me.essentials.Console; import com.earth2me.essentials.EssentialsConf; -import com.earth2me.essentials.IConf; -import com.earth2me.essentials.IUser; +import com.earth2me.essentials.api.IReload; +import com.earth2me.essentials.api.IUser; import java.io.File; import java.util.*; import java.util.logging.Handler; @@ -18,7 +17,7 @@ import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.util.StringUtils; -public class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IConf +public class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IReload { private static final Logger LOGGER = Logger.getLogger("Minecraft"); private final transient EssentialsConf config; @@ -39,7 +38,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager this.parent = parent; config = new EssentialsConf(new File(parent.getDataFolder(), "config.yml")); config.setTemplateName("/config.yml", EssentialsXMPP.class); - reloadConfig(); + onReload(); } public boolean sendMessage(final String address, final String message) @@ -166,7 +165,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager } @Override - public final void reloadConfig() + public final void onReload() { LOGGER.removeHandler(this); config.load(); @@ -355,7 +354,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager { try { - parent.getServer().dispatchCommand(Console.getCommandSender(parent.getServer()), message.substring(1)); + parent.getServer().dispatchCommand(parent.getServer().getConsoleSender(), message.substring(1)); } catch (Exception ex) { diff --git a/EssentialsXMPP/src/plugin.yml b/EssentialsXMPP/src/plugin.yml index a193ba95f..e152024fd 100644 --- a/EssentialsXMPP/src/plugin.yml +++ b/EssentialsXMPP/src/plugin.yml @@ -3,7 +3,7 @@ name: EssentialsXMPP main: com.earth2me.essentials.xmpp.EssentialsXMPP # Note to developers: This next line cannot change, or the automatic versioning system will break. version: TeamCity -website: http://www.earth2me.net:8001/ +website: http://tiny.cc/EssentialsWiki description: Provides xmpp communication. authors: - snowleo @@ -2,7 +2,7 @@ <project default="collect"> <target name="setversion"> <replace dir="." includes="**/src/plugin.yml" token="version: TeamCity" value="version: ${build.number}"/> - <replace dir="." includes="**/src/plugin.yml" token="version: GMBuildVer" value="version: ${GMVer} (${build.number})"/> + <replace dir="." includes="**/src/plugin.yml" token="version: GMBuildVer" value="version: ${GMVer} (${build.number})"/> <replace dir="." includes="**/src/messages*.properties" token="version: TeamCity" value="version: ${build.number}"/> <replace dir="." includes="**/src/items.csv" token="version: TeamCity" value="version: ${build.number}"/> </target> @@ -14,11 +14,13 @@ <ant dir="Essentials" antfile="build.xml"/> </target> <target name="buildRest" depends="buildEss"> + <ant dir="Essentials2Compat" antfile="build.xml"/> <ant dir="EssentialsChat" antfile="build.xml"/> <ant dir="EssentialsSpawn" antfile="build.xml"/> <ant dir="EssentialsProtect" antfile="build.xml"/> <ant dir="EssentialsGeoIP" antfile="build.xml"/> <ant dir="EssentialsXMPP" antfile="build.xml"/> + <ant dir="EssentialsSigns" antfile="build.xml"/> </target> <target name="collect" depends="buildRest"> <mkdir dir="jars"/> |