This is a big refactoring of the user class and more.

Many commands have been cleaned.

File changes:
- all user data has been moved from users.yml to userdata folder
- all files in userdata folder are lower case
Both changes should be done automatically.

Class changes:
- Moved all user data functions to UserData class
- Moved all user teleport functions to Teleport class
- Moved the user list to Essentials class
- Less static functions for better testing
- EssentialsCommand now has ess Property (Essentials class)
- New NotEnoughArgumentsException, that will show command description and syntax

New commands:
- /seen, shows the last login or logout
- /tempban, temporarily ban someone
- /tjail and mute, temporarily option added

Other changes:
- ban reason is saved
- don't show "You have xxx mail" on login, if user doesn't have essentials.mail permission
-  time will be parsed: years, months (mo), weeks, days, hours, minutes (m), seconds, these can be shortened and combined, example: 2 days 5h 30m

git-svn-id: https://svn.java.net/svn/essentials~svn/trunk@1300 e251c2fe-e539-e718-e476-b85c1f46cddb
This commit is contained in:
snowleo 2011-05-01 21:07:30 +00:00
parent 03fd6249fc
commit 224c18348a
126 changed files with 3542 additions and 3145 deletions

View File

@ -79,7 +79,7 @@ reference.EssentialsGeoIP.jar=${project.EssentialsGeoIP}/dist/EssentialsGeoIP.ja
reference.EssentialsGroupBridge.jar=${project.EssentialsGroupBridge}/dist/EssentialsGroupBridge.jar
reference.EssentialsGroupManager.jar=${project.EssentialsGroupManager}/dist/EssentialsGroupManager.jar
reference.EssentialsiConomyBridge.jar=${project.EssentialsiConomyBridge}/dist/EssentialsiConomyBridge.jar
reference.EssentialsProtect.jar=${project.EssentialsProtect}/dist/original-EssentialsProtect.jar
reference.EssentialsProtect.jar=${project.EssentialsProtect}/dist/EssentialsProtect.jar
reference.EssentialsSpawn.jar=${project.EssentialsSpawn}/dist/EssentialsSpawn.jar
run.classpath=\
${javac.classpath}:\

View File

@ -26,7 +26,7 @@ public class Backup implements Runnable {
private void startTask() {
if (!running) {
long interval = Essentials.getSettings().getBackupInterval()*1200; // minutes -> ticks
long interval = Essentials.getStatic().getSettings().getBackupInterval()*1200; // minutes -> ticks
if (interval < 1200) {
return;
}
@ -38,7 +38,7 @@ public class Backup implements Runnable {
public void run() {
if (active) return;
active = true;
final String command = Essentials.getSettings().getBackupCommand();
final String command = Essentials.getStatic().getSettings().getBackupCommand();
if (command == null || "".equals(command)) {
return;
}

View File

@ -8,6 +8,7 @@ import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.command.PluginCommand;
@ -17,9 +18,6 @@ import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.plugin.*;
import org.bukkit.plugin.java.*;
import org.yaml.snakeyaml.*;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
public class Essentials extends JavaPlugin
@ -27,102 +25,96 @@ public class Essentials extends JavaPlugin
public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo and ceulemans.";
public static final int minBukkitBuildVersion = 733;
private static final Logger logger = Logger.getLogger("Minecraft");
private static final Yaml yaml = new Yaml(new SafeConstructor());
private static Map<String, Object> users;
private static Settings settings;
private static final Object usersLock = new Object();
public static Object permissions = null;
public final Map<User, User> tpcRequests = new HashMap<User, User>();
public final Map<User, Boolean> tpcHere = new HashMap<User, Boolean>();
public final List<User> away = new ArrayList<User>();
private Settings settings;
private EssentialsPlayerListener playerListener;
private EssentialsBlockListener blockListener;
private EssentialsEntityListener entityListener;
private JailPlayerListener jailPlayerListener;
private static Essentials staticThis = null;
public Spawn spawn;
private static Essentials instance = null;
private Spawn spawn;
private Jail jail;
private Warps warps;
private Worth worth;
private List<IConf> confList;
public ArrayList bans = new ArrayList();
public ArrayList bannedIps = new ArrayList();
public Backup backup;
private Backup backup;
private Map<String, User> users = new HashMap<String, User>();
private EssentialsTimer timer;
public Essentials() throws IOException
public Essentials()
{
}
public static void ensureEnabled(Server server)
{
PluginManager pm = server.getPluginManager();
Essentials ess = (Essentials)pm.getPlugin("Essentials");
if (!ess.isEnabled())
pm.enablePlugin(ess);
}
public static Essentials getStatic()
{
return staticThis;
return instance;
}
public static Settings getSettings()
public Settings getSettings()
{
return settings;
}
public void setupPermissions()
public void setupForTesting() throws IOException, InvalidDescriptionException
{
Plugin permPlugin = this.getServer().getPluginManager().getPlugin("Permissions");
if (permissions == null && permPlugin != null) permissions = permPlugin;
}
public Player getPlayer(String[] args, int pos)
throws IndexOutOfBoundsException, NoSuchFieldException
{
if (args.length <= pos) throw new IndexOutOfBoundsException("§cInvalid command syntax. Did you forget an argument?");
List<Player> matches = getServer().matchPlayer(args[0]);
if (matches.size() < 1) throw new NoSuchFieldException("§cNo matching players could be found.");
return matches.get(0);
File dataFolder = File.createTempFile("essentialstest", "");
dataFolder.delete();
dataFolder.mkdir();
logger.log(Level.INFO,"Using temp folder for testing:");
logger.log(Level.INFO,dataFolder.toString());
this.initialize(null, null, new PluginDescriptionFile(new FileReader(new File("src"+File.separator+"plugin.yml"))), dataFolder, null, null);
settings = new Settings(dataFolder);
}
public void setStatic()
{
staticThis = this;
instance = this;
}
@SuppressWarnings("LoggerStringConcat")
public void onEnable()
{
setStatic();
new EssentialsUpgrade(this.getDescription().getVersion(), this.getDataFolder());
EssentialsUpgrade upgrade = new EssentialsUpgrade(this.getDescription().getVersion(), this);
if (newWorldsLoaded) {
logger.log(Level.SEVERE, "New worlds have been loaded while upgrading files. Will reload the server.");
getServer().reload();
}
confList = new ArrayList<IConf>();
settings = new Settings(this.getDataFolder());
confList.add(settings);
this.spawn = new Spawn(getServer(), this.getDataFolder());
spawn = new Spawn(getServer(), this.getDataFolder());
confList.add(spawn);
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
worth = new Worth(this.getDataFolder());
confList.add(worth);
reload();
this.backup = new Backup();
backup = new Backup();
PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins()) {
if (plugin.getDescription().getName().startsWith("Essentials")) {
if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion())) {
logger.log(Level.WARNING, "Version mismatch! Please update "+plugin.getDescription().getName()+" to the same version.");
for (Plugin plugin : pm.getPlugins())
{
if (plugin.getDescription().getName().startsWith("Essentials"))
{
if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion()))
{
logger.log(Level.WARNING, "Version mismatch! Please update " + plugin.getDescription().getName() + " to the same version.");
}
}
}
Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion());
if (versionMatch.matches()) {
if (versionMatch.matches())
{
int versionNumber = Integer.parseInt(versionMatch.group(4));
if (versionNumber < minBukkitBuildVersion) {
if (versionNumber < minBukkitBuildVersion)
{
logger.log(Level.WARNING, "Bukkit version is not the recommended build for Essentials.");
}
} else {
}
else
{
logger.log(Level.INFO, "Bukkit version format changed. Version not checked.");
}
@ -132,7 +124,9 @@ public class Essentials extends JavaPlugin
pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Lowest, this);
if (getSettings().getNetherPortalsEnabled())
{
pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this);
}
pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.High, this);
@ -150,7 +144,7 @@ public class Essentials extends JavaPlugin
pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this);
pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this);
jail = new Jail(this.getDataFolder());
jail = new Jail(this);
jailPlayerListener = new JailPlayerListener(this);
confList.add(jail);
pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this);
@ -164,17 +158,19 @@ public class Essentials extends JavaPlugin
getServer().createWorld(settings.getNetherName(), World.Environment.NETHER);
}
timer = new EssentialsTimer(this);
getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 50);
logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS);
}
public void onDisable()
{
staticThis = null;
instance = null;
}
public void reload()
{
loadData();
loadBanList();
for (IConf iConf : confList)
@ -192,190 +188,6 @@ public class Essentials extends JavaPlugin
}
}
public static Map<String, Object> getData(User player)
{
return getData(player.getName());
}
public static Map<String, Object> getData(String player)
{
try
{
Map<String, Object> retval;
synchronized (usersLock)
{
retval = (Map<String, Object>)users.get(player.toLowerCase());
}
return retval == null ? new HashMap<String, Object>() : retval;
}
catch (Throwable ex)
{
return new HashMap<String, Object>();
}
}
public static void flushData()
{
Thread run = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
if (!Essentials.getStatic().getDataFolder().exists())
Essentials.getStatic().getDataFolder().mkdirs();
File file = new File(Essentials.getStatic().getDataFolder(), "users.yml");
if (!file.exists())
file.createNewFile();
FileWriter tx = new FileWriter(file);
synchronized (usersLock)
{
tx.write(yaml.dump(users));
}
tx.flush();
tx.close();
}
catch (Throwable ex)
{
Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
run.setDaemon(false);
run.start();
}
public static void loadData()
{
try
{
if (!Essentials.getStatic().getDataFolder().exists()) Essentials.getStatic().getDataFolder().mkdirs();
File file = new File(Essentials.getStatic().getDataFolder(), "users.yml");
if (!file.exists()) file.createNewFile();
FileInputStream rx = new FileInputStream(file);
synchronized (usersLock)
{
users = (Map<String, Object>)yaml.load(new UnicodeReader(rx));
}
rx.close();
}
catch (Exception ex)
{
Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex);
synchronized (usersLock)
{
users = new HashMap<String, Object>();
}
}
finally
{
synchronized (usersLock)
{
if (users == null) users = new HashMap<String, Object>();
}
}
}
public static void setData(User player, Map<String, Object> data)
{
setData(player.getName(), data);
}
public static void setData(String player, Map<String, Object> data)
{
synchronized (usersLock)
{
users.put(player.toLowerCase(), data);
}
}
public static List<String> readMail(User player)
{
return readMail(player.getName());
}
public static List<String> readMail(String player)
{
try
{
Map<String, Object> data = getData(player);
List<String> retval = (List<String>)data.get("mail");
return retval == null ? new ArrayList<String>() : retval;
}
catch (Throwable ex)
{
return new ArrayList<String>();
}
}
public static void clearMail(User player)
{
try
{
Map<String, Object> data = getData(player);
data.put("mail", new ArrayList<String>());
setData(player, data);
flushData();
}
catch (Throwable ex)
{
}
}
public static void sendMail(User from, String to, String message)
throws Exception
{
try
{
Map<String, Object> data = getData(ChatColor.stripColor(to));
List<String> mail = readMail(to);
mail.add(ChatColor.stripColor(from.getDisplayName()) + ": " + message);
data.put("mail", mail);
setData(to, data);
flushData();
}
catch (Throwable ex)
{
throw new Exception("An error was encountered while sending the mail.", ex);
}
}
public String readNickname(User player)
{
try
{
Map<String, Object> data = getData(player);
String nick = (String)data.get("nickname");
if (nick == null)
return player.getName();
if (nick.equals(player.getName()))
return player.getName();
return getSettings().getNicknamePrefix() + nick;
}
catch (Exception ex)
{
return player.getName();
}
}
public void saveNickname(User player, String nickname) throws Exception
{
try
{
Map<String, Object> data = getData(player);
data.put("nickname", nickname);
setData(player, data);
flushData();
}
catch (Throwable ex)
{
throw new Exception("An error was encountered while saving the nickname.", ex);
}
}
public String[] getMotd(CommandSender sender, String def)
{
return getLines(sender, "motd", def);
@ -384,7 +196,10 @@ public class Essentials extends JavaPlugin
public String[] getLines(CommandSender sender, String node, String def)
{
List<String> lines = (List<String>)getConfiguration().getProperty(node);
if (lines == null) return new String[0];
if (lines == null)
{
return new String[0];
}
String[] retval = new String[lines.size()];
if (lines == null || lines.isEmpty() || lines.get(0) == null)
@ -408,18 +223,22 @@ public class Essentials extends JavaPlugin
// if still empty, call it a day
if (lines == null || lines.isEmpty() || lines.get(0) == null)
{
return new String[0];
}
for (int i = 0; i < lines.size(); i++)
{
String m = lines.get(i);
if (m == null)
{
continue;
}
m = m.replace('&', '§').replace("§§", "&");
if (sender instanceof User || sender instanceof Player)
{
User user = User.get(sender);
User user = getUser(sender);
m = m.replace("{PLAYER}", user.getDisplayName());
m = m.replace("{IP}", user.getAddress().toString());
m = m.replace("{BALANCE}", Double.toString(user.getMoney()));
@ -433,7 +252,9 @@ public class Essentials extends JavaPlugin
for (Player p : getServer().getOnlinePlayers())
{
if (online.length() > 0)
{
online.append(", ");
}
online.append(p.getDisplayName());
}
m = m.replace("{PLAYERLIST}", online.toString());
@ -462,36 +283,16 @@ public class Essentials extends JavaPlugin
return retval;
}
public static String FormatTime(long Milliseconds)
{ // format time into a string showing hours, minutes, or seconds
if (Milliseconds > 3600000)
{
double val = Math.round((double)Milliseconds / 360000D) / 10D;
return val + " hour" + (val > 1 ? "s" : "");
}
else if (Milliseconds > 60000)
{
double val = Math.round((double)Milliseconds / 6000D) / 10D;
return val + " minute" + (val > 1 ? "s" : "");
}
else if (Milliseconds <= 1000)
return "1 second";
else
return (Milliseconds / 1000L) + " seconds";
}
@SuppressWarnings("LoggerStringConcat")
public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
if (sender instanceof Player)
{
logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0));
}
}
@Override
@SuppressWarnings(
{
"LoggerStringConcat", "CallToThreadDumpStack"
})
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
// Allow plugins to override the command via onCommand
@ -500,26 +301,38 @@ public class Essentials extends JavaPlugin
for (Plugin p : getServer().getPluginManager().getPlugins())
{
if (p == this)
{
continue;
}
PluginDescriptionFile desc = p.getDescription();
if (desc == null)
{
continue;
}
if (desc.getName() == null)
{
continue;
}
if (!(desc.getCommands() instanceof Map))
{
continue;
}
Map<String, Object> cmds = (Map<String, Object>)desc.getCommands();
if (!cmds.containsKey(command.getName()))
{
continue;
}
PluginCommand pcmd = getServer().getPluginCommand(desc.getName() + ":" + commandLabel);
if (pcmd == null)
{
continue;
}
return getServer().getPluginCommand(p.getDescription().getName() + ":" + commandLabel).execute(sender, commandLabel, args);
}
@ -528,17 +341,23 @@ public class Essentials extends JavaPlugin
try
{
previewCommand(sender, command, commandLabel, args);
User user = sender instanceof Player ? User.get(sender) : null;
User user = sender instanceof Player ? getUser(sender) : null;
// New mail notification
if (user != null && !Essentials.getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail"))
if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail"))
{
List<String> mail = Essentials.readMail(user);
if (!mail.isEmpty()) user.sendMessage(ChatColor.RED + "You have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail.");
List<String> mail = user.getMails();
if (!mail.isEmpty())
{
user.sendMessage(ChatColor.RED + "You have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail.");
}
}
// Check for disabled commands
if (Essentials.getSettings().isCommandDisabled(commandLabel)) return true;
if (getSettings().isCommandDisabled(commandLabel))
{
return true;
}
IEssentialsCommand cmd;
try
@ -548,14 +367,14 @@ public class Essentials extends JavaPlugin
catch (Exception ex)
{
sender.sendMessage(ChatColor.RED + "That command is improperly loaded.");
ex.printStackTrace();
logger.log(Level.SEVERE, "Command " + commandLabel + " is improperly loaded.", ex);
return true;
}
// Check authorization
if (user != null && !user.isAuthorized(cmd))
{
logger.warning(user.getName() + " was denied access to command.");
logger.log(Level.WARNING, user.getName() + " was denied access to command.");
user.sendMessage(ChatColor.RED + "You do not have access to that command.");
return true;
}
@ -564,23 +383,34 @@ public class Essentials extends JavaPlugin
try
{
if (user == null)
cmd.run(getServer(), this, sender, commandLabel, command, args);
{
cmd.run(getServer(), sender, commandLabel, command, args);
}
else
cmd.run(getServer(), this, user, commandLabel, command, args);
{
cmd.run(getServer(), user, commandLabel, command, args);
}
return true;
}
catch (NotEnoughArgumentsException ex)
{
sender.sendMessage(command.getDescription());
sender.sendMessage(command.getUsage());
return true;
}
catch (Throwable ex)
{
sender.sendMessage(ChatColor.RED + "Error: " + ex.getMessage());
if (getSettings().isDebug()) {
logger.log(Level.WARNING, "Error calling command /"+commandLabel, ex);
if (getSettings().isDebug())
{
logger.log(Level.WARNING, "Error calling command /" + commandLabel, ex);
}
return true;
}
}
catch (Throwable ex)
{
ex.printStackTrace();
logger.log(Level.SEVERE, "Command " + commandLabel + " failed: ", ex);
return true;
}
}
@ -592,7 +422,10 @@ public class Essentials extends JavaPlugin
File ipFile = new File("banned-ips.txt");
try
{
if (!file.exists()) throw new FileNotFoundException("banned-players.txt not found");
if (!file.exists())
{
throw new FileNotFoundException("banned-players.txt not found");
}
BufferedReader rx = new BufferedReader(new FileReader(file));
bans.clear();
@ -602,7 +435,10 @@ public class Essentials extends JavaPlugin
{
String line = rx.readLine().trim().toLowerCase();
if (line.startsWith("#")) continue;
if (line.startsWith("#"))
{
continue;
}
bans.add(line);
}
@ -619,7 +455,10 @@ public class Essentials extends JavaPlugin
try
{
if (!ipFile.exists()) throw new FileNotFoundException("banned-ips.txt not found");
if (!ipFile.exists())
{
throw new FileNotFoundException("banned-ips.txt not found");
}
BufferedReader rx = new BufferedReader(new FileReader(ipFile));
bannedIps.clear();
@ -629,7 +468,10 @@ public class Essentials extends JavaPlugin
{
String line = rx.readLine().trim().toLowerCase();
if (line.startsWith("#")) continue;
if (line.startsWith("#"))
{
continue;
}
bannedIps.add(line);
}
@ -648,8 +490,8 @@ public class Essentials extends JavaPlugin
private void attachEcoListeners()
{
PluginManager pm = getServer().getPluginManager();
EssentialsEcoBlockListener ecoBlockListener = new EssentialsEcoBlockListener();
EssentialsEcoPlayerListener ecoPlayerListener = new EssentialsEcoPlayerListener();
EssentialsEcoBlockListener ecoBlockListener = new EssentialsEcoBlockListener(this);
EssentialsEcoPlayerListener ecoPlayerListener = new EssentialsEcoPlayerListener(this);
pm.registerEvent(Type.PLAYER_INTERACT, ecoPlayerListener, Priority.High, this);
pm.registerEvent(Type.BLOCK_BREAK, ecoBlockListener, Priority.High, this);
pm.registerEvent(Type.SIGN_CHANGE, ecoBlockListener, Priority.Monitor, this);
@ -674,4 +516,86 @@ public class Essentials extends JavaPlugin
{
return getStatic().worth;
}
public static Backup getBackup()
{
return getStatic().backup;
}
public static Spawn getSpawn()
{
return getStatic().spawn;
}
public <T> User getUser(T base)
{
if (base instanceof Player)
{
return getUser((Player)base);
}
return null;
}
private <T extends Player> User getUser(T base)
{
if (base == null)
{
return null;
}
if (base instanceof User)
{
return (User)base;
}
if (users.containsKey(base.getName()))
{
return users.get(base.getName()).update(base);
}
User u = new User(base, this);
users.put(u.getName(), u);
return u;
}
public User getOfflineUser(String name)
{
File userFolder = new File(getDataFolder(), "userdata");
File userFile = new File(userFolder, Util.sanitizeFileName(name) + ".yml");
if (userFile.exists())
{
return new User(new OfflinePlayer(name), this);
}
return null;
}
private boolean newWorldsLoaded = false;
public World getWorld(String name)
{
if (name.matches("[0-9]+"))
{
int id = Integer.parseInt(name);
if (id < getServer().getWorlds().size())
{
return getServer().getWorlds().get(id);
}
}
World w = getServer().getWorld(name);
if (w != null)
{
return w;
}
File bukkitDirectory = getStatic().getDataFolder().getParentFile().getParentFile();
File worldDirectory = new File(bukkitDirectory, name);
if (worldDirectory.exists() && worldDirectory.isDirectory())
{
w = getServer().createWorld(name, World.Environment.NORMAL);
if (w != null)
{
newWorldsLoaded = true;
}
return w;
}
return null;
}
}

View File

@ -1,20 +1,16 @@
package com.earth2me.essentials;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.craftbukkit.block.CraftSign;
import org.bukkit.event.block.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
public class EssentialsBlockListener extends BlockListener
{
private final Essentials parent;
private final Essentials ess;
public final static ArrayList<Material> protectedBlocks = new ArrayList<Material>(4);
static
@ -25,17 +21,17 @@ public class EssentialsBlockListener extends BlockListener
protectedBlocks.add(Material.DISPENSER);
}
public EssentialsBlockListener(Essentials parent)
public EssentialsBlockListener(Essentials ess)
{
this.parent = parent;
this.ess = ess;
}
@Override
public void onBlockBreak(BlockBreakEvent event)
{
if (event.isCancelled()) return;
if (Essentials.getSettings().areSignsDisabled()) return;
User user = User.get(event.getPlayer());
if (ess.getSettings().areSignsDisabled()) return;
User user = ess.getUser(event.getPlayer());
if (protectedBlocks.contains(event.getBlock().getType()) && !user.isAuthorized("essentials.signs.protection.override"))
{
if (isBlockProtected(event.getBlock(), user))
@ -58,8 +54,8 @@ public class EssentialsBlockListener extends BlockListener
public void onSignChange(SignChangeEvent event)
{
if (event.isCancelled()) return;
if (Essentials.getSettings().areSignsDisabled()) return;
User user = User.get(event.getPlayer());
if (ess.getSettings().areSignsDisabled()) return;
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
try
@ -171,7 +167,7 @@ public class EssentialsBlockListener extends BlockListener
return;
}
}
final User user = User.get(event.getPlayer());
final User user = ess.getUser(event.getPlayer());
// Do not rely on getItemInHand();
// http://leaky.bukkit.org/issues/663
final ItemStack is = new ItemStack(event.getBlockPlaced().getType(), 1, (short)0, event.getBlockPlaced().getData());
@ -236,7 +232,7 @@ public class EssentialsBlockListener extends BlockListener
}
boolean unlimitedForUser = user.hasUnlimited(is);
if (unlimitedForUser) {
Essentials.getStatic().getScheduler().scheduleSyncDelayedTask(Essentials.getStatic(),
ess.getScheduler().scheduleSyncDelayedTask(ess,
new Runnable() {
public void run() {

View File

@ -28,7 +28,8 @@ public class EssentialsConf extends Configuration
{
super(configFile);
this.configFile = configFile;
if (this.root == null) {
if (this.root == null)
{
this.root = new HashMap<String, Object>();
}
}
@ -62,7 +63,8 @@ public class EssentialsConf extends Configuration
}
}
super.load();
if (this.root == null) {
if (this.root == null)
{
this.root = new HashMap<String, Object>();
}
}
@ -98,7 +100,8 @@ public class EssentialsConf extends Configuration
{
try
{
if (ostr != null) {
if (ostr != null)
{
ostr.close();
}
}
@ -120,73 +123,83 @@ public class EssentialsConf extends Configuration
return configFile;
}
public void setTemplateName(String templateName, Class<?> resClass) {
public void setTemplateName(String templateName, Class<?> resClass)
{
this.templateName = templateName;
this.resourceClass = resClass;
}
public boolean hasProperty(String path) {
public boolean hasProperty(String path)
{
return getProperty(path) != null;
}
public Location getLocation(String path, Server server) {
String worldName = getString(path+".world");
if (worldName == null || worldName.isEmpty()) {
public Location getLocation(String path, Server server)
{
String worldName = getString((path != null ? path + "." : "") + "world");
if (worldName == null || worldName.isEmpty())
{
return null;
}
World world = server.getWorld(worldName);
if (world == null) {
if (world == null)
{
return null;
}
return new Location(world,
getDouble(path+".x", 0),
getDouble(path+".y", 0),
getDouble(path+".z", 0),
(float)getDouble(path+".paw", 0),
(float)getDouble(path+".pitch", 0));
getDouble((path != null ? path + "." : "") + "x", 0),
getDouble((path != null ? path + "." : "") + "y", 0),
getDouble((path != null ? path + "." : "") + "z", 0),
(float)getDouble((path != null ? path + "." : "") + "yaw", 0),
(float)getDouble((path != null ? path + "." : "") + "pitch", 0));
}
public void setProperty(String path, Location loc) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("world", loc.getWorld().getName());
map.put("x", loc.getX());
map.put("y", loc.getY());
map.put("z", loc.getZ());
map.put("yaw", loc.getYaw());
map.put("pitch", loc.getPitch());
setProperty(path, map);
public void setProperty(String path, Location loc)
{
setProperty((path != null ? path + "." : "") + "world", loc.getWorld().getName());
setProperty((path != null ? path + "." : "") + "x", loc.getX());
setProperty((path != null ? path + "." : "") + "y", loc.getY());
setProperty((path != null ? path + "." : "") + "z", loc.getZ());
setProperty((path != null ? path + "." : "") + "yaw", loc.getYaw());
setProperty((path != null ? path + "." : "") + "pitch", loc.getPitch());
}
public ItemStack getItemStack(String path) {
public ItemStack getItemStack(String path)
{
return new ItemStack(
Material.valueOf(getString(path+".type", "AIR")),
getInt(path+".amount", 1),
(short)getInt(path+".damage", 0),
(byte)getInt(path+".data", 0));
Material.valueOf(getString(path + ".type", "AIR")),
getInt(path + ".amount", 1),
(short)getInt(path + ".damage", 0)/*,
(byte)getInt(path + ".data", 0)*/);
}
public void setProperty(String path, ItemStack stack) {
public void setProperty(String path, ItemStack stack)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", stack.getType().toString());
map.put("amount", stack.getAmount());
map.put("damage", stack.getDurability());
// getData().getData() is broken
map.put("data", stack.getDurability());
//map.put("data", stack.getDurability());
setProperty(path, map);
}
public long getLong(String path, long def) {
public long getLong(String path, long def)
{
Number num = (Number)getProperty(path);
if (num == null) {
if (num == null)
{
return def;
}
return num.longValue();
}
@Override
public double getDouble(String path, double def) {
public double getDouble(String path, double def)
{
Number num = (Number)getProperty(path);
if (num == null) {
if (num == null)
{
return def;
}
return num.doubleValue();

View File

@ -11,21 +11,37 @@ import org.bukkit.inventory.ItemStack;
public class EssentialsEcoBlockListener extends BlockListener
{
Essentials ess;
public EssentialsEcoBlockListener(Essentials ess)
{
this.ess = ess;
}
@Override
public void onBlockBreak(BlockBreakEvent event)
{
if (event.isCancelled()) return;
if (Essentials.getSettings().areSignsDisabled()) return;
User user = User.get(event.getPlayer());
if (event.isCancelled())
{
return;
}
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST)
{
return;
}
Sign sign = new CraftSign(event.getBlock());
if (sign.getLine(0).equals("§1[Trade]"))
{
if (!sign.getLine(3).substring(2).equals(username)) {
if (!user.isOp()) {
if (!sign.getLine(3).substring(2).equals(username))
{
if (!user.isOp())
{
event.setCancelled(true);
}
return;
@ -40,20 +56,31 @@ public class EssentialsEcoBlockListener extends BlockListener
int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]);
int r1 = Integer.parseInt(l1[m1 ? 1 : 2]);
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0.");
if (q1 < 1 || q2 < 1)
{
throw new Exception("Quantities must be greater than 0.");
}
ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], r1);
ItemStack i2 = m2 || r2 <= 0 ? null : ItemDb.get(l2[1], r2);
if (m1)
{
user.giveMoney(r1);
}
else if (i1 != null)
{
user.getWorld().dropItem(user.getLocation(), i1);
}
if (m2)
{
user.giveMoney(r2);
}
else if (i2 != null)
{
user.getWorld().dropItem(user.getLocation(), i2);
}
sign.setType(Material.AIR);
}
@ -65,12 +92,14 @@ public class EssentialsEcoBlockListener extends BlockListener
}
}
@Override
public void onSignChange(SignChangeEvent event)
{
if (Essentials.getSettings().areSignsDisabled()) return;
User user = User.get(event.getPlayer());
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getLine(0).equalsIgnoreCase("[Buy]") && user.isAuthorized("essentials.signs.buy.create"))
@ -80,7 +109,8 @@ public class EssentialsEcoBlockListener extends BlockListener
event.setLine(0, "§1[Buy]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0) {
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Don't sell air.");
}
event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", "")));
@ -103,7 +133,8 @@ public class EssentialsEcoBlockListener extends BlockListener
event.setLine(0, "§1[Sell]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0) {
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Don't buy air.");
}
event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", "")));
@ -131,19 +162,31 @@ public class EssentialsEcoBlockListener extends BlockListener
int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]);
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
r2 = r2 - r2 % q2;
if (q1 < 1 || q2 < 1 || r2 < 1) throw new Exception("Quantities must be greater than 0.");
if (!m1) ItemDb.get(l1[1]);
if (q1 < 1 || q2 < 1 || r2 < 1)
{
throw new Exception("Quantities must be greater than 0.");
}
if (!m1)
{
ItemDb.get(l1[1]);
}
if (m2)
{
if (user.getMoney() < r2) throw new Exception("You do not have sufficient funds.");
if (user.getMoney() < r2)
{
throw new Exception("You do not have sufficient funds.");
}
user.takeMoney(r2);
user.sendMessage("r2: " + r2 + " q2: " + q2);
}
else
{
ItemStack i2 = ItemDb.get(l2[1], r2);
if (!InventoryWorkaround.containsItem(user.getInventory(), true, i2)) throw new Exception("You do not have " + r2 + "x " + l2[1] + ".");
if (!InventoryWorkaround.containsItem(user.getInventory(), true, i2))
{
throw new Exception("You do not have " + r2 + "x " + l2[1] + ".");
}
InventoryWorkaround.removeItem(user.getInventory(), true, i2);
user.updateInventory();
}

View File

@ -12,17 +12,30 @@ import org.bukkit.inventory.ItemStack;
public class EssentialsEcoPlayerListener extends PlayerListener
{
Essentials ess;
@Override
EssentialsEcoPlayerListener(Essentials ess)
{
this.ess = ess;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
if (Essentials.getSettings().areSignsDisabled()) return;
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
User user = User.get(event.getPlayer());
if (ess.getSettings().areSignsDisabled())
{
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
{
return;
}
Sign sign = new CraftSign(event.getClickedBlock());
if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use"))
@ -32,10 +45,14 @@ public class EssentialsEcoPlayerListener extends PlayerListener
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (user.getMoney() < cost) throw new Exception("You do not have sufficient funds.");
if (user.getMoney() < cost)
{
throw new Exception("You do not have sufficient funds.");
}
user.takeMoney(cost);
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(item);
for (ItemStack itemStack : leftOver.values()) {
for (ItemStack itemStack : leftOver.values())
{
user.getWorld().dropItem(user.getLocation(), itemStack);
}
user.updateInventory();
@ -54,7 +71,10 @@ public class EssentialsEcoPlayerListener extends PlayerListener
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
int cost = Integer.parseInt(sign.getLine(3).substring(1));
if (!InventoryWorkaround.containsItem(user.getInventory(), true, item)) throw new Exception("You do not have enough items to sell.");
if (!InventoryWorkaround.containsItem(user.getInventory(), true, item))
{
throw new Exception("You do not have enough items to sell.");
}
user.giveMoney(cost);
InventoryWorkaround.removeItem(user.getInventory(), true, item);
user.updateInventory();
@ -80,9 +100,12 @@ public class EssentialsEcoPlayerListener extends PlayerListener
int r2 = Integer.parseInt(l2[m2 ? 1 : 2]);
r1 = r1 - r1 % q1;
r2 = r2 - r2 % q2;
if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0.");
if (q1 < 1 || q2 < 1)
{
throw new Exception("Quantities must be greater than 0.");
}
ItemStack i1 = m1 || r1 <= 0? null : ItemDb.get(l1[1], r1);
ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], r1);
ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], q1);
ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], q2);
@ -95,7 +118,8 @@ public class EssentialsEcoPlayerListener extends PlayerListener
else if (i1 != null)
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i1);
for (ItemStack itemStack : leftOver.values()) {
for (ItemStack itemStack : leftOver.values())
{
user.getWorld().dropItem(user.getLocation(), itemStack);
}
user.updateInventory();
@ -108,26 +132,41 @@ public class EssentialsEcoPlayerListener extends PlayerListener
if (m1)
{
if (user.getMoney() < q1)
{
throw new Exception("You do not have sufficient funds.");
}
}
else
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, qi1))
{
throw new Exception("You do not have " + q1 + "x " + l1[1] + ".");
}
}
if (r2 < q2) throw new Exception("The trade sign does not have enough supply left.");
if (r2 < q2)
{
throw new Exception("The trade sign does not have enough supply left.");
}
if (m1)
{
user.takeMoney(q1);
}
else
{
InventoryWorkaround.removeItem(user.getInventory(), true, qi1);
}
if (m2)
{
user.giveMoney(q2);
else {
}
else
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(qi2);
for (ItemStack itemStack : leftOver.values()) {
for (ItemStack itemStack : leftOver.values())
{
user.getWorld().dropItem(user.getLocation(), itemStack);
}
}

View File

@ -16,13 +16,11 @@ import org.bukkit.inventory.ItemStack;
public class EssentialsEntityListener extends EntityListener
{
private final Server server;
private final Essentials parent;
private final Essentials ess;
public EssentialsEntityListener(Essentials parent)
{
this.parent = parent;
this.server = parent.getServer();
this.ess = parent;
}
@Override
@ -35,11 +33,12 @@ public class EssentialsEntityListener extends EntityListener
Entity eDefend = edEvent.getEntity();
if (eDefend instanceof Player && eAttack instanceof Player)
{
User defender = User.get(eDefend);
User attacker = User.get(eAttack);
User defender = ess.getUser(eDefend);
User attacker = ess.getUser(eAttack);
ItemStack is = attacker.getItemInHand();
String command = attacker.getPowertool(is);
if (command != null && !command.isEmpty()) {
if (command != null && !command.isEmpty())
{
attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", defender.getName()));
event.setCancelled(true);
return;
@ -49,7 +48,7 @@ public class EssentialsEntityListener extends EntityListener
if (event instanceof EntityDamageEvent || event instanceof EntityDamageByBlockEvent || event instanceof EntityDamageByProjectileEvent)
{
if (event.getEntity() instanceof Player && User.get(event.getEntity()).isGodModeEnabled())
if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled())
{
CraftPlayer player = (CraftPlayer)event.getEntity();
player.getHandle().fireTicks = 0;
@ -59,11 +58,10 @@ public class EssentialsEntityListener extends EntityListener
}
}
@Override
public void onEntityCombust(EntityCombustEvent event)
{
if (event.getEntity() instanceof Player && User.get(event.getEntity()).isGodModeEnabled())
if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled())
{
event.setCancelled(true);
}
@ -74,13 +72,12 @@ public class EssentialsEntityListener extends EntityListener
{
if (event.getEntity() instanceof Player)
{
User user = User.get(event.getEntity());
if(user.isAuthorized("essentials.back.ondeath"))
User user = ess.getUser(event.getEntity());
if (user.isAuthorized("essentials.back.ondeath"))
{
user.lastLocation = user.getLocation();
user.sendMessage("§7Use the /back command to return to your death point");
user.setLastLocation();
user.sendMessage("§7Use the /back command to return to your death point");
}
}
}
}

View File

@ -20,12 +20,12 @@ public class EssentialsPlayerListener extends PlayerListener
{
private static final Logger logger = Logger.getLogger("Minecraft");
private final Server server;
private final Essentials parent;
private final Essentials ess;
private EssentialsBlockListener essBlockListener = null;
public EssentialsPlayerListener(Essentials parent)
{
this.parent = parent;
this.ess = parent;
this.server = parent.getServer();
essBlockListener = new EssentialsBlockListener(parent);
}
@ -33,15 +33,24 @@ public class EssentialsPlayerListener extends PlayerListener
@Override
public void onPlayerRespawn(PlayerRespawnEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
user.setDisplayName(user.getNick());
updateCompass(user);
if (user.isJailed() && user.getJail() != null && !user.getJail().isEmpty()) {
try
{
event.setRespawnLocation(Essentials.getJail().getJail(user.getJail()));
}
catch (Exception ex)
{
}
}
}
@Override
public void onPlayerChat(PlayerChatEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
if (user.isMuted())
{
event.setCancelled(true);
@ -52,20 +61,29 @@ public class EssentialsPlayerListener extends PlayerListener
@Override
public void onPlayerMove(PlayerMoveEvent event)
{
if (event.isCancelled()) return;
final User user = User.get(event.getPlayer());
if (event.isCancelled())
{
return;
}
final User user = ess.getUser(event.getPlayer());
if (!Essentials.getSettings().getNetherPortalsEnabled()) return;
if (!ess.getSettings().getNetherPortalsEnabled())
{
return;
}
final Block block = event.getPlayer().getWorld().getBlockAt(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ());
List<World> worlds = server.getWorlds();
if (block.getType() == Material.PORTAL && worlds.size() > 1 && user.isAuthorized("essentials.portal"))
{
if (user.getJustPortaled()) return;
if (user.getJustPortaled())
{
return;
}
Location loc = event.getTo();
World nether = server.getWorld(Essentials.getSettings().getNetherName());
World nether = server.getWorld(ess.getSettings().getNetherName());
if (nether == null) {
for (World world : worlds)
{
@ -81,8 +99,9 @@ public class EssentialsPlayerListener extends PlayerListener
final World world = user.getWorld() == nether ? worlds.get(0) : nether;
double factor;
if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL) {
if (Essentials.getSettings().use1to1RatioInNether())
if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL)
{
if (ess.getSettings().use1to1RatioInNether())
{
factor = 1.0;
}
@ -91,8 +110,9 @@ public class EssentialsPlayerListener extends PlayerListener
factor = 16.0;
}
}
else if (user.getWorld().getEnvironment() != world.getEnvironment()) {
if (Essentials.getSettings().use1to1RatioInNether())
else if (user.getWorld().getEnvironment() != world.getEnvironment())
{
if (ess.getSettings().use1to1RatioInNether())
{
factor = 1.0;
}
@ -101,7 +121,8 @@ public class EssentialsPlayerListener extends PlayerListener
factor = 1.0 / 16.0;
}
}
else {
else
{
factor = 1.0;
}
@ -110,9 +131,13 @@ public class EssentialsPlayerListener extends PlayerListener
int z = loc.getBlockZ();
if (user.getWorld().getBlockAt(x, y, z - 1).getType() == Material.PORTAL)
{
z--;
}
if (user.getWorld().getBlockAt(x - 1, y, z).getType() == Material.PORTAL)
{
x--;
}
x = (int)(x * factor);
z = (int)(z * factor);
@ -122,7 +147,7 @@ public class EssentialsPlayerListener extends PlayerListener
NetherPortal portal = NetherPortal.findPortal(dest);
if (portal == null)
{
if (world.getEnvironment() == World.Environment.NETHER || Essentials.getSettings().getGenerateExitPortals())
if (world.getEnvironment() == World.Environment.NETHER || ess.getSettings().getGenerateExitPortals())
{
portal = NetherPortal.createPortal(dest);
logger.info(event.getPlayer().getName() + " used a portal and generated an exit portal.");
@ -141,7 +166,7 @@ public class EssentialsPlayerListener extends PlayerListener
event.setTo(loc);
try
{
user.teleportToNow(loc);
user.getTeleport().teleport(loc, "portal");
}
catch (Exception ex)
{
@ -160,14 +185,14 @@ public class EssentialsPlayerListener extends PlayerListener
@Override
public void onPlayerQuit(PlayerQuitEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
if(user.savedInventory != null)
if (user.getSavedInventory() != null)
{
user.getInventory().setContents(user.savedInventory);
user.savedInventory = null;
user.getInventory().setContents(user.getSavedInventory());
user.setSavedInventory(null);
}
if (!Essentials.getSettings().getReclaimSetting())
if (!ess.getSettings().getReclaimSetting())
{
return;
}
@ -201,54 +226,68 @@ public class EssentialsPlayerListener extends PlayerListener
@Override
public void onPlayerJoin(PlayerJoinEvent event)
{
Essentials.getStatic().backup.onPlayerJoin();
User user = User.get(event.getPlayer());
Essentials.getBackup().onPlayerJoin();
User user = ess.getUser(event.getPlayer());
//we do not know the ip address on playerlogin so we need to do this here.
if (user.isIpBanned())
{
user.kickPlayer("The Ban Hammer has spoken!");
String banReason = user.getBanReason();
user.kickPlayer(banReason != null && !banReason.isEmpty() ? banReason : "The Ban Hammer has spoken!");
return;
}
user.setDisplayName(user.getNick());
if (!Essentials.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd"))
if (!ess.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd"))
{
for (String m : parent.getMotd(user, null))
for (String m : ess.getMotd(user, null))
{
if (m == null) continue;
if (m == null)
{
continue;
}
user.sendMessage(m);
}
}
if (!Essentials.getSettings().isCommandDisabled("mail"))
if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail"))
{
List<String> mail = Essentials.readMail(user);
if (mail.isEmpty()) user.sendMessage("§7You have no new mail.");
else user.sendMessage("§cYou have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail.");
List<String> mail = user.getMails();
if (mail.isEmpty())
{
user.sendMessage("§7You have no new mail.");
}
else
{
user.sendMessage("§cYou have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail.");
}
}
}
@Override
public void onPlayerLogin(PlayerLoginEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
if (event.getResult() != Result.ALLOWED)
return;
if (user.isBanned())
{
event.disallow(Result.KICK_BANNED, "The Ban Hammer has spoken!");
return;
}
if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !user.isOp())
if (user.isBanned())
{
String banReason = user.getBanReason();
event.disallow(Result.KICK_BANNED, banReason != null && !banReason.isEmpty() ? banReason : "The Ban Hammer has spoken!");
return;
}
if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !user.isAuthorized("essentials.joinfullserver"))
{
event.disallow(Result.KICK_FULL, "Server is full");
return;
}
user.setLastLogin(System.currentTimeMillis());
updateCompass(user);
}
@ -266,13 +305,18 @@ public class EssentialsPlayerListener extends PlayerListener
@Override
public void onPlayerTeleport(PlayerTeleportEvent event)
{
if (event.isCancelled()) return;
User user = User.get(event.getPlayer());
if (user.currentJail == null || user.currentJail.isEmpty())
if (event.isCancelled())
{
return;
}
User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
{
return;
}
try
{
event.setTo(Essentials.getJail().getJail(user.currentJail));
event.setTo(Essentials.getJail().getJail(user.getJail()));
}
catch (Exception ex)
{
@ -284,11 +328,21 @@ public class EssentialsPlayerListener extends PlayerListener
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
if (event.isCancelled()) return;
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
User user = User.get(event.getPlayer());
if (user.isJailed()) return;
if (!Essentials.getSettings().areSignsDisabled() && EssentialsBlockListener.protectedBlocks.contains(event.getClickedBlock().getType()))
if (event.isCancelled())
{
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
{
return;
}
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
return;
}
if (!ess.getSettings().areSignsDisabled() && EssentialsBlockListener.protectedBlocks.contains(event.getClickedBlock().getType()))
{
if (!user.isAuthorized("essentials.signs.protection.override"))
{
@ -301,7 +355,7 @@ public class EssentialsPlayerListener extends PlayerListener
}
}
if (Essentials.getSettings().getBedSetsHome() && event.getClickedBlock().getType() == Material.BED_BLOCK)
if (ess.getSettings().getBedSetsHome() && event.getClickedBlock().getType() == Material.BED_BLOCK)
{
try
{
@ -314,9 +368,14 @@ public class EssentialsPlayerListener extends PlayerListener
}
if (Essentials.getSettings().areSignsDisabled()) return;
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
if (ess.getSettings().areSignsDisabled())
{
return;
}
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
{
return;
}
Sign sign = new CraftSign(event.getClickedBlock());
try
@ -375,13 +434,16 @@ public class EssentialsPlayerListener extends PlayerListener
}
if (sign.getLine(0).equals("§1[Mail]") && user.isAuthorized("essentials.signs.mail.use") && user.isAuthorized("essentials.mail"))
{
List<String> mail = Essentials.readMail(user);
List<String> mail = user.getMails();
if (mail.isEmpty())
{
user.sendMessage("§cYou do not have any mail!");
return;
}
for (String s : mail) user.sendMessage(s);
for (String s : mail)
{
user.sendMessage(s);
}
user.sendMessage("§cTo mark your mail as read, type §c/mail clear");
return;
}
@ -425,22 +487,19 @@ public class EssentialsPlayerListener extends PlayerListener
{
if (sign.getLine(2).equals("§2Everyone"))
{
user.teleportCooldown();
user.warpTo(sign.getLine(1));
user.getTeleport().warp(sign.getLine(1), "warpsign");
return;
}
if (user.inGroup(sign.getLine(2)))
{
user.teleportCooldown();
user.warpTo(sign.getLine(1));
user.getTeleport().warp(sign.getLine(1), "warpsign");
return;
}
}
if (user.isAuthorized("essentials.signs.warp.use")
&& (!Essentials.getSettings().getPerWarpPermission() || user.isAuthorized("essentials.warp." + sign.getLine(1))))
&& (!ess.getSettings().getPerWarpPermission() || user.isAuthorized("essentials.warp." + sign.getLine(1))))
{
user.teleportCooldown();
user.warpTo(sign.getLine(1));
user.getTeleport().warp(sign.getLine(1), "warpsign");
}
return;
}
@ -454,7 +513,7 @@ public class EssentialsPlayerListener extends PlayerListener
@Override
public void onPlayerEggThrow(PlayerEggThrowEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
ItemStack is = new ItemStack(Material.EGG, 1);
if (user.hasUnlimited(is))
{
@ -466,7 +525,7 @@ public class EssentialsPlayerListener extends PlayerListener
@Override
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event)
{
final User user = User.get(event.getPlayer());
final User user = ess.getUser(event.getPlayer());
if (user.hasUnlimited(new ItemStack(event.getBucket())))
{
event.getItemStack().setType(event.getBucket());
@ -493,7 +552,7 @@ public class EssentialsPlayerListener extends PlayerListener
{
return;
}
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
ItemStack is = user.getItemInHand();
if (is == null || is.getType() == Material.AIR)
{

View File

@ -0,0 +1,81 @@
package com.earth2me.essentials;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.Player;
public class EssentialsTimer implements Runnable, IConf
{
private Essentials parent;
private Set<User> allUsers = new HashSet<User>();
EssentialsTimer(Essentials parent)
{
this.parent = parent;
File userdir = new File(parent.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
for (String string : userdir.list())
{
if (!string.endsWith(".yml")) {
continue;
}
String name = string.substring(0, string.length()-4);
User u = parent.getUser(new OfflinePlayer(name));
allUsers.add(u);
}
}
public void run()
{
long currentTime = System.currentTimeMillis();
for (Player player : parent.getServer().getOnlinePlayers())
{
User u = parent.getUser(player);
allUsers.add(u);
u.setLastActivity(currentTime);
}
for (User user: allUsers) {
if (user.getBanTimeout() > 0 && user.getBanTimeout() < currentTime) {
user.setBanTimeout(0);
((CraftServer)parent.getServer()).getHandle().b(user.getName());
Essentials.getStatic().loadBanList();
}
if (user.getMuteTimeout() > 0 && user.getMuteTimeout() < currentTime && user.isMuted()) {
user.setMuteTimeout(0);
user.sendMessage("§7You can talk again");
user.setMuted(false);
}
if (user.getJailTimeout() > 0 && user.getJailTimeout() < currentTime && user.isJailed()) {
user.setJailTimeout(0);
user.setJailed(false);
user.sendMessage("§7You have been released");
user.setJail(null);
try
{
user.getTeleport().back();
}
catch (Exception ex)
{
}
}
if (user.getLastActivity() < currentTime && user.getLastActivity() > user.getLastLogout()) {
user.setLastLogout(user.getLastActivity());
}
}
}
public void reloadConfig()
{
for (User user : allUsers)
{
user.reloadConfig();
}
}
}

View File

@ -5,77 +5,351 @@ import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.inventory.ItemStack;
public class EssentialsUpgrade {
public class EssentialsUpgrade
{
private static boolean alreadyRun = false;
private final static Logger logger = Logger.getLogger("Minecraft");
private Essentials ess;
EssentialsUpgrade(String version, File dataFolder) {
if (alreadyRun == true) return;
EssentialsUpgrade(String version, Essentials essentials)
{
if (alreadyRun == true)
{
return;
}
alreadyRun = true;
moveWorthValuesToWorthYml(dataFolder);
ess = essentials;
if (!ess.getDataFolder().exists())
{
ess.getDataFolder().mkdirs();
}
moveWorthValuesToWorthYml();
sanitizeAllUserFilenames();
updateUsersToNewDefaultHome();
moveUsersDataToUserdataFolder();
convertWarps();
}
private void moveWorthValuesToWorthYml(File dataFolder) {
try {
File configFile = new File(dataFolder, "config.yml");
if (!configFile.exists()) {
private void moveWorthValuesToWorthYml()
{
try
{
File configFile = new File(ess.getDataFolder(), "config.yml");
if (!configFile.exists())
{
return;
}
EssentialsConf conf = new EssentialsConf(configFile);
conf.load();
Worth w = new Worth(dataFolder);
for (Material mat : Material.values()) {
Worth w = new Worth(ess.getDataFolder());
for (Material mat : Material.values())
{
int id = mat.getId();
double value = conf.getDouble("worth-"+id, Double.NaN);
if (!Double.isNaN(value)) {
double value = conf.getDouble("worth-" + id, Double.NaN);
if (!Double.isNaN(value))
{
w.setPrice(new ItemStack(mat, 1, (short)0, (byte)0), value);
}
}
removeLinesFromConfig(configFile,"\\s*#?\\s*worth-[0-9]+.*", "# Worth values have been moved to worth.yml");
} catch (Throwable e) {
removeLinesFromConfig(configFile, "\\s*#?\\s*worth-[0-9]+.*", "# Worth values have been moved to worth.yml");
}
catch (Throwable e)
{
logger.log(Level.SEVERE, "Error while upgrading the files", e);
}
}
private void removeLinesFromConfig(File file, String regex, String info) throws Exception {
private void removeLinesFromConfig(File file, String regex, String info) throws Exception
{
boolean needUpdate = false;
BufferedReader br = new BufferedReader(new FileReader(file));
File tempFile = File.createTempFile("essentialsupgrade", ".yml");
File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder());
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
do {
do
{
String line = br.readLine();
if (line == null) break;
if (line.matches(regex)) {
if (needUpdate == false && info != null) {
if (line == null)
{
break;
}
if (line.matches(regex))
{
if (needUpdate == false && info != null)
{
bw.write(info, 0, info.length());
bw.newLine();
}
needUpdate = true;
} else {
if (line.endsWith("\r\n")) {
}
else
{
if (line.endsWith("\r\n"))
{
bw.write(line, 0, line.length() - 2);
} else if (line.endsWith("\r") || line.endsWith("\n")) {
}
else if (line.endsWith("\r") || line.endsWith("\n"))
{
bw.write(line, 0, line.length() - 1);
} else {
}
else
{
bw.write(line, 0, line.length());
}
bw.newLine();
}
} while(true);
}
while (true);
br.close();
bw.close();
if (needUpdate) {
if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("."+System.currentTimeMillis()+".upgradebackup")))) {
if (needUpdate)
{
if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup"))))
{
throw new Exception("Failed to move config.yml to backup location.");
}
if (!tempFile.renameTo(file)) {
if (!tempFile.renameTo(file))
{
throw new Exception("Failed to rename temp file to config.yml");
}
}
}
private void updateUsersToNewDefaultHome()
{
File userdataFolder = new File(ess.getDataFolder(), "userdata");
if (!userdataFolder.exists() || !userdataFolder.isDirectory())
{
return;
}
File[] userFiles = userdataFolder.listFiles();
for (File file : userFiles)
{
if (!file.isFile() || !file.getName().endsWith(".yml"))
{
continue;
}
EssentialsConf config = new EssentialsConf(file);
if (config.hasProperty("home") && !config.hasProperty("home.default"))
{
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>)config.getProperty("home");
World world = ess.getServer() == null ? null : ess.getServer().getWorlds().get(0);
if (vals.size() > 5 && ess.getServer() != null)
{
world = ess.getServer().getWorld((String)vals.get(5));
}
if (world != null)
{
Location loc = new Location(
world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
String worldName = world.getName().toLowerCase();
if (worldName != null && !worldName.isEmpty())
{
config.removeProperty("home");
config.setProperty("home.default", worldName);
config.setProperty("home.worlds." + worldName, loc);
config.save();
}
}
}
}
}
private void moveUsersDataToUserdataFolder()
{
File usersFile = new File(ess.getDataFolder(), "users.yml");
if (!usersFile.exists())
{
return;
}
EssentialsConf usersConfig = new EssentialsConf(usersFile);
usersConfig.load();
for (String username : usersConfig.getKeys(null))
{
User user = new User(new OfflinePlayer(username), ess);
String nickname = usersConfig.getString(username + ".nickname");
if (nickname != null && !nickname.isEmpty() && !nickname.equals(username))
{
user.setNickname(nickname);
}
List<String> mails = usersConfig.getStringList(username + ".mail", null);
if (mails != null && !mails.isEmpty())
{
user.setMails(mails);
}
if (user.getHome() == null)
{
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>)usersConfig.getProperty(username + ".home");
World world = ess.getServer().getWorlds().get(0);
if (vals.size() > 5)
{
world = ess.getWorld((String)vals.get(5));
}
if (world != null)
{
user.setHome(new Location(world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue()), true);
}
}
}
}
private void convertWarps()
{
File warpsFolder = new File(ess.getDataFolder(), "warps");
if (!warpsFolder.exists())
{
warpsFolder.mkdirs();
}
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(".dat"))
{
try
{
BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i]));
double x = Double.parseDouble(rx.readLine().trim());
double y = Double.parseDouble(rx.readLine().trim());
double z = Double.parseDouble(rx.readLine().trim());
float yaw = Float.parseFloat(rx.readLine().trim());
float pitch = Float.parseFloat(rx.readLine().trim());
String worldName = rx.readLine();
rx.close();
World w = null;
for (World world : ess.getServer().getWorlds())
{
if (world.getEnvironment() != World.Environment.NETHER)
{
w = world;
break;
}
}
boolean forceWorldName = false;
if (worldName != null)
{
worldName.trim();
World w1 = null;
w1 = ess.getWorld(worldName);
if (w1 != null)
{
w = w1;
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
Essentials.getWarps().setWarp(filename.substring(0, filename.length() - 4), loc);
if (!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old")))
{
throw new Exception("Renaming file " + filename + " failed");
}
}
catch (Exception ex)
{
logger.log(Level.SEVERE, null, ex);
}
}
}
}
File warpFile = new File(ess.getDataFolder(), "warps.txt");
if (warpFile.exists())
{
try
{
BufferedReader rx = new BufferedReader(new FileReader(warpFile));
for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":"))
{
if (parts.length < 6)
{
continue;
}
String name = parts[0];
double x = Double.parseDouble(parts[1].trim());
double y = Double.parseDouble(parts[2].trim());
double z = Double.parseDouble(parts[3].trim());
float yaw = Float.parseFloat(parts[4].trim());
float pitch = Float.parseFloat(parts[5].trim());
if (name.isEmpty())
{
continue;
}
World w = null;
for (World world : ess.getServer().getWorlds())
{
if (world.getEnvironment() != World.Environment.NETHER)
{
w = world;
break;
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
Essentials.getWarps().setWarp(name, loc);
if (!warpFile.renameTo(new File(ess.getDataFolder(), "warps.txt.old")))
{
throw new Exception("Renaming warps.txt failed");
}
}
}
catch (Exception ex)
{
logger.log(Level.SEVERE, null, ex);
}
}
}
private void sanitizeAllUserFilenames()
{
File usersFolder = new File(ess.getDataFolder(), "userdata");
if (!usersFolder.exists())
{
return;
}
File[] listOfFiles = usersFolder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
String filename = listOfFiles[i].getName();
if (!listOfFiles[i].isFile() || !filename.endsWith(".yml"))
{
continue;
}
String sanitizedFilename = Util.sanitizeFileName(filename);
if (sanitizedFilename.equals(filename))
{
continue;
}
File newFile = new File(listOfFiles[i].getParentFile(), sanitizedFilename);
if (newFile.exists())
{
logger.log(Level.WARNING, "Duplicated userdata: "+filename+" and "+sanitizedFilename);
continue;
}
if (!listOfFiles[i].renameTo(newFile)) {
logger.log(Level.WARNING, "Failed to move userdata/"+filename+" to userdata/"+sanitizedFilename);
}
}
}
}

View File

@ -8,7 +8,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
@ -96,7 +95,7 @@ public class ItemDb
throw new Exception("Unknown item id: "+itemid);
}
ItemStack retval = new ItemStack(mat);
retval.setAmount(Essentials.getSettings().getDefaultStackSize());
retval.setAmount(Essentials.getStatic().getSettings().getDefaultStackSize());
retval.setDurability(durabilities.containsKey(id.toLowerCase()) ? durabilities.get(id.toLowerCase()) : 0);
return retval;
}

View File

@ -1,12 +1,9 @@
package com.earth2me.essentials;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockListener;
@ -17,23 +14,18 @@ public class Jail extends BlockListener implements IConf
{
private static final Logger logger = Logger.getLogger("Minecraft");
private EssentialsConf config;
private Essentials ess;
public Jail(File dataFolder)
public Jail(Essentials ess)
{
config = new EssentialsConf(new File(dataFolder, "jail.yml"));
this.ess = ess;
config = new EssentialsConf(new File(ess.getDataFolder(), "jail.yml"));
config.load();
}
public void setJail(Location loc, String jailName) throws Exception
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("world", loc.getWorld().getName());
map.put("x", loc.getX());
map.put("y", loc.getY());
map.put("z", loc.getZ());
map.put("yaw", loc.getYaw());
map.put("pitch", loc.getPitch());
config.setProperty(jailName.toLowerCase(), map);
config.setProperty(jailName.toLowerCase(), loc);
config.save();
}
@ -44,29 +36,14 @@ public class Jail extends BlockListener implements IConf
throw new Exception("That jail does not exist");
}
World jWorld = null;
String world = config.getString(jailName + ".world", ""); // wh.spawnX
double x = config.getDouble(jailName + ".x", 0); // wh.spawnX
double y = config.getDouble(jailName + ".y", 0); // wh.spawnY
double z = config.getDouble(jailName + ".z", 0); // wh.spawnZ
float yaw = (float)config.getDouble(jailName + ".yaw", 0);
float pitch = (float)config.getDouble(jailName + ".pitch", 0);
for (World w : Essentials.getStatic().getServer().getWorlds())
{
if (w.getName().equalsIgnoreCase(world))
{
jWorld = w;
break;
}
}
return new Location(jWorld, x, y, z, yaw, pitch);
Location loc = config.getLocation(jailName.toLowerCase(), Essentials.getStatic().getServer());
return loc;
}
public void sendToJail(User user, String jail) throws Exception
{
user.teleportToNow(getJail(jail));
user.currentJail = jail;
user.getTeleport().now(getJail(jail));
user.setJail(jail);
}
public void delJail(String jail) throws Exception
@ -88,7 +65,7 @@ public class Jail extends BlockListener implements IConf
@Override
public void onBlockBreak(BlockBreakEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
@ -98,7 +75,7 @@ public class Jail extends BlockListener implements IConf
@Override
public void onBlockPlace(BlockPlaceEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
@ -108,7 +85,7 @@ public class Jail extends BlockListener implements IConf
@Override
public void onBlockDamage(BlockDamageEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);

View File

@ -1,25 +1,22 @@
package com.earth2me.essentials;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;
public class JailPlayerListener extends PlayerListener
{
private final Server server;
private final Essentials parent;
private final Essentials ess;
public JailPlayerListener(Essentials parent)
{
this.parent = parent;
this.server = parent.getServer();
this.ess = parent;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
User user = User.get(event.getPlayer());
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);

View File

@ -1,7 +1,5 @@
package com.earth2me.essentials;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import net.minecraft.server.EntityPlayer;
import net.minecraft.server.IInventory;
@ -45,63 +43,6 @@ public class PlayerExtension extends PlayerWrapper
showInventory((IInventory)inventory.getInventory());
}
public Location getSafeDestination(Location loc) throws Exception
{
World world = loc.getWorld();
double x = Math.floor(loc.getX())+0.5;
double y = Math.floor(loc.getY());
double z = Math.floor(loc.getZ())+0.5;
while (isBlockAboveAir(world, x, y, z))
{
y -= 1.0D;
if (y < 0.0D) {
throw new Exception("Hole in floor");
}
}
while (isBlockUnsafe(world, x, y, z))
{
y += 1.0D;
if (y >= 110.0D) {
x += 1.0D;
break;
}
}
while (isBlockUnsafe(world, x, y, z))
{
y -= 1.0D;
if (y <= 1.0D)
{
y = 110.0D;
x += 1.0D;
}
}
return new Location(world, x, y, z, loc.getYaw(), loc.getPitch());
}
private boolean isBlockAboveAir(World world, double x, double y, double z)
{
return world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)).getType() == Material.AIR;
}
public boolean isBlockUnsafe(World world, double x, double y, double z)
{
Block below = world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z));
if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA)
return true;
if (below.getType() == Material.FIRE)
return true;
if ((world.getBlockAt((int)Math.floor(x), (int)Math.floor(y), (int)Math.floor(z)).getType() != Material.AIR)
|| (world.getBlockAt((int)Math.floor(x), (int)Math.floor(y + 1.0D), (int)Math.floor(z)).getType() != Material.AIR))
{
return true;
}
return isBlockAboveAir(world, x, y, z);
}
public TargetBlock getTarget()
{
return new TargetBlock(getBase());

View File

@ -38,9 +38,9 @@ public class Settings implements IConf
return config.getInt("chat.radius", config.getInt("chat-radius", 0));
}
public long getTeleportDelay()
public double getTeleportDelay()
{
return config.getInt("teleport-delay", 0) * 1000L;
return config.getDouble("teleport-delay", 0);
}
public int getDefaultStackSize()
@ -134,14 +134,14 @@ public class Settings implements IConf
return config.getString("nickname-prefix", "");
}
public long getTeleportCooldown()
public double getTeleportCooldown()
{
return ((Number)config.getInt("teleport-cooldown", 60)).longValue() * 1000L;
return config.getDouble("teleport-cooldown", 60);
}
public long getHealCooldown()
public double getHealCooldown()
{
return ((Number)config.getInt("heal-cooldown", 60)).longValue() * 1000L;
return config.getDouble("heal-cooldown", 60);
}
public Object getKit(String name)

View File

@ -0,0 +1,257 @@
package com.earth2me.essentials;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
public class Teleport implements Runnable
{
private static class Target
{
private Location location = null;
private Entity entity = null;
public Target(Location location)
{
this.location = location;
}
public Target(Entity entity)
{
this.entity = entity;
}
public Location getLocation()
{
if (this.entity != null)
{
return this.entity.getLocation();
}
return location;
}
}
User user;
private int teleTimer = -1;
private long started; // time this task was initiated
private long delay; // how long to delay the teleport
private int health;
// note that I initially stored a clone of the location for reference, but...
// when comparing locations, I got incorrect mismatches (rounding errors, looked like)
// so, the X/Y/Z values are stored instead and rounded off
private long initX;
private long initY;
private long initZ;
private Target teleportTarget;
private String chargeFor;
private Essentials ess;
private void initTimer(long delay, Target target, String chargeFor)
{
this.started = System.currentTimeMillis();
this.delay = delay;
this.health = user.getHealth();
this.initX = Math.round(user.getLocation().getX() * 10000);
this.initY = Math.round(user.getLocation().getY() * 10000);
this.initZ = Math.round(user.getLocation().getZ() * 10000);
this.teleportTarget = target;
this.chargeFor = chargeFor;
}
public void run()
{
if (user == null || !user.isOnline() || user.getLocation() == null)
{
cancel();
return;
}
if (Math.round(user.getLocation().getX() * 10000) != initX
|| Math.round(user.getLocation().getY() * 10000) != initY
|| Math.round(user.getLocation().getZ() * 10000) != initZ
|| user.getHealth() < health)
{ // user moved, cancel teleport
cancel(true);
return;
}
health = user.getHealth(); // in case user healed, then later gets injured
long now = System.currentTimeMillis();
if (now > started + delay)
{
try
{
cooldown(false);
user.sendMessage("§7Teleportation commencing...");
try
{
if (chargeFor != null)
{
user.charge(chargeFor);
}
now(teleportTarget);
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
}
return;
}
catch (Exception ex)
{
user.sendMessage("§cCooldown: " + ex.getMessage());
}
}
}
public Teleport(User user, Essentials ess)
{
this.user = user;
this.ess = ess;
}
public void respawn(Spawn spawn, String chargeFor) throws Exception
{
teleport(new Target(spawn.getSpawn(user.getGroup())), chargeFor);
}
public void warp(String warp, String chargeFor) throws Exception
{
Location loc = Essentials.getWarps().getWarp(warp);
teleport(new Target(loc), chargeFor);
user.sendMessage("§7Warping to " + warp + ".");
}
public void cooldown(boolean check) throws Exception
{
Calendar now = new GregorianCalendar();
if (user.getLastTeleportTimestamp() > 0)
{
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("Time before next teleport: " + Util.formatDateDiff(cooldownTime.getTimeInMillis()));
}
}
// if justCheck is set, don't update lastTeleport; we're just checking
if (!check)
{
user.setLastTeleportTimestamp(now.getTimeInMillis());
}
}
public void cancel(boolean notifyUser)
{
if (teleTimer == -1)
{
return;
}
try
{
user.getServer().getScheduler().cancelTask(teleTimer);
if (notifyUser)
{
user.sendMessage("§cPending teleportation request cancelled.");
}
}
finally
{
teleTimer = -1;
}
}
public void cancel()
{
cancel(false);
}
public void teleport(Location loc, String name) throws Exception
{
teleport(new Target(loc), chargeFor);
}
public void teleport(Entity entity, String name) throws Exception
{
teleport(new Target(entity), chargeFor);
}
private void teleport(Target target, String chargeFor) throws Exception
{
double delay = ess.getSettings().getTeleportDelay();
cooldown(true);
if (delay <= 0 || user.isAuthorized("essentials.teleport.timer.bypass"))
{
if (chargeFor != null)
{
user.charge(chargeFor);
}
now(target);
return;
}
cancel();
Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int)delay);
c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0));
user.sendMessage("§7Teleportation will commence in " + Util.formatDateDiff(c.getTimeInMillis()) + ". Don't move.");
initTimer((long)(delay * 1000.0), target, chargeFor);
teleTimer = user.getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), this, 10, 10);
}
private void now(Target target) throws Exception
{
cancel();
user.setLastLocation();
user.getBase().teleport(Util.getSafeDestination(target.getLocation()));
}
public void now(Location loc) throws Exception
{
now(new Target(loc));
}
public void now(Entity entity) throws Exception
{
now(new Target(entity));
}
public void back(final String chargeFor) throws Exception
{
teleport(new Target(user.getLastLocation()), chargeFor);
}
public void back() throws Exception
{
back(null);
}
public void home(String chargeFor) throws Exception
{
home(user, chargeFor);
}
public void home(User user, String chargeFor) throws Exception
{
Location loc = user.getHome();
if (loc == null)
{
if (ess.getSettings().spawnIfNoHome())
{
respawn(Essentials.getSpawn(), chargeFor);
}
else
{
throw new Exception(user == this.user ? "You have not set a home." : "Player has not set a home.");
}
}
teleport(new Target(loc), chargeFor);
}
}

View File

@ -1,73 +0,0 @@
package com.earth2me.essentials;
import java.util.TimerTask;
import java.util.Calendar;
public abstract class TeleportTimer implements Runnable
{
private long started; // time this task was initiated
private long delay; // how long to delay the teleport
public User user; // the person doing the teleport
private int health;
// note that I initially stored a clone of the location for reference, but...
// when comparing locations, I got incorrect mismatches (rounding errors, looked like)
// so, the X/Y/Z values are stored instead and rounded off
private long initX;
private long initY;
private long initZ;
public TeleportTimer(User tUser, long tDelay)
{
this.started = Calendar.getInstance().getTimeInMillis();
this.delay = tDelay;
this.user = tUser;
this.health = user.getHealth();
this.initX = Math.round(user.getLocation().getX() * 10000);
this.initY = Math.round(user.getLocation().getY() * 10000);
this.initZ = Math.round(user.getLocation().getZ() * 10000);
}
// This function needs to be defined when creating a new TeleportTimer
// The actual teleport command by itself should be stuck in there, such as teleportToNow(loc)
public abstract void DoTeleport();
public abstract void DoCancel();
public void run()
{
if (user == null || !user.isOnline() || user.getLocation() == null)
{
DoCancel();
return;
}
if (Math.round(user.getLocation().getX() * 10000) != initX
|| Math.round(user.getLocation().getY() * 10000) != initY
|| Math.round(user.getLocation().getZ() * 10000) != initZ
|| user.getHealth() < health)
{ // user moved, cancel teleport
user.cancelTeleport(true);
return;
}
health = user.getHealth(); // in case user healed, then later gets injured
long now = Calendar.getInstance().getTimeInMillis();
if (now > started + delay)
{
try
{
user.teleportCooldown(false);
user.sendMessage("§7Teleportation commencing...");
this.DoTeleport();
return;
}
catch (Exception ex)
{
user.sendMessage("§cCooldown: " + ex.getMessage());
}
}
//else // uncomment for timing debug
// user.sendMessage("§7" + (started + delay - now));
}
}

View File

@ -1,97 +1,31 @@
package com.earth2me.essentials;
import java.util.*;
import java.util.logging.*;
import java.io.*;
import org.bukkit.*;
import com.earth2me.essentials.commands.IEssentialsCommand;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
import org.bukkit.entity.Player;
public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public class User extends UserData implements Comparable<User>, IReplyTo
{
private static final Logger logger = Logger.getLogger("Minecraft");
private final Yaml yaml = new Yaml(new SafeConstructor());
private boolean isLoaded = false;
private final File folder;
private Map<String, Object> data = new HashMap<String, Object>();
private static Map<String, User> users = new HashMap<String, User>();
private boolean teleEnabled = true;
private long lastTeleport = 0;
private long lastHeal = 0;
private boolean justPortaled = false;
//private TimerTask teleTimer = null;
private int teleTimer = -1;
public Location lastLocation = null;
private CommandSender replyTo = null;
private boolean isNew = false;
public String currentJail;
public ItemStack[] savedInventory;
private Map<String,Object> metadata = new HashMap<String,Object>();
private User teleportRequester;
private boolean teleportRequestHere;
private Teleport teleport;
private long lastActivity;
private User(Player base)
User(Player base, Essentials ess)
{
super(base);
this.folder = new File((Essentials.getStatic() == null ? new File(".") : Essentials.getStatic().getDataFolder()), "userdata");
this.lastLocation = getBase().getLocation();
load();
super(base, ess);
teleport = new Teleport(this, ess);
}
public static int size()
{
return users.size();
}
public static <T> User get(T base)
{
if (base instanceof Player)
return get((Player)base);
return null;
}
public static <T extends Player> User get(T base)
{
if (base == null)
return null;
if (base instanceof User)
return (User)base;
if (users.containsKey(base.getName()))
return users.get(base.getName()).update(base);
User u = new User(base);
users.put(u.getName(), u);
return u;
}
public static <T> void charge(T base, IEssentialsCommand cmd) throws Exception
{
if (base instanceof Player)
User.get(base).charge(cmd);
}
public boolean isNew()
{
return isNew;
}
public void respawn(Spawn spawn) throws Exception
{
respawn(spawn, null);
}
public void respawn(Spawn spawn, final String chargeFor) throws Exception
{
teleportTo(getSafeDestination(spawn.getSpawn(getGroup())), chargeFor);
}
private User update(Player base)
User update(Player base)
{
setBase(base);
return this;
@ -105,10 +39,14 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public boolean isAuthorized(String node)
{
if (isOp())
{
return true;
}
if (isJailed())
{
return false;
}
try
{
@ -117,204 +55,44 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
catch (Throwable ex)
{
String[] cmds = node.split("\\.", 2);
return !Essentials.getSettings().isCommandRestricted(cmds[cmds.length - 1]);
return !ess.getSettings().isCommandRestricted(cmds[cmds.length - 1]);
}
}
public boolean isTeleEnabled()
{
return teleEnabled;
}
public boolean toggleTeleEnabled()
{
return teleEnabled = !teleEnabled;
}
public void teleportCooldown(boolean justCheck) throws Exception
{
long now = Calendar.getInstance().getTimeInMillis();
if (lastTeleport > 0)
{
long cooldown = Essentials.getSettings().getTeleportCooldown();
long left = lastTeleport + cooldown - now;
if (left > 0 && !isOp() && !isAuthorized("essentials.teleport.cooldown.bypass"))
{
throw new Exception("Time before next teleport: " + Essentials.FormatTime(left));
}
}
// if justCheck is set, don't update lastTeleport; we're just checking
if (!justCheck) lastTeleport = now;
}
public void teleportCooldown() throws Exception
{
teleportCooldown(true);
}
public void healCooldown() throws Exception
{
long now = Calendar.getInstance().getTimeInMillis();
if (lastHeal > 0)
Calendar now = new GregorianCalendar();
if (getLastHealTimestamp() > 0)
{
long cooldown = Essentials.getSettings().getHealCooldown();
long left = lastHeal + cooldown - now;
if (left > 0 && !isOp() && !isAuthorized("essentials.heal.cooldown.bypass"))
double cooldown = ess.getSettings().getHealCooldown();
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("Time before next heal: " + Essentials.FormatTime(left));
throw new Exception("Time before next heal: " + Util.formatDateDiff(cooldownTime.getTimeInMillis()));
}
}
lastHeal = now;
}
private void load()
{
if (isLoaded) return;
isLoaded = true;
data = Essentials.getData(this);
try
{
if (!folder.exists()) folder.mkdirs();
File file = new File(folder, getName() + ".yml");
if (!file.exists())
{
isNew = true;
file.createNewFile();
logger.info(getName() + " has logged in for the first time.");
}
FileInputStream rx = new FileInputStream(file);
Map<String, Object> userData = (Map<String, Object>)yaml.load(new UnicodeReader(rx));
if (userData != null) data.putAll(userData);
rx.close();
}
catch (Throwable ex)
{
logger.log(Level.SEVERE, null, ex);
}
finally
{
if (data == null) data = new HashMap<String, Object>();
}
}
private void flush()
{
try
{
if (!folder.exists()) folder.mkdirs();
File file = new File(folder, getName() + ".yml");
if (!file.exists()) file.createNewFile();
FileWriter tx = new FileWriter(file);
tx.write(yaml.dump(data));
tx.flush();
tx.close();
}
catch (Throwable ex)
{
logger.log(Level.SEVERE, null, ex);
}
}
public boolean isGodModeEnabled()
{
load();
return data.containsKey("godmode") && (Boolean)data.get("godmode");
}
public boolean toggleGodMode()
{
boolean retval = !isGodModeEnabled();
data.put("godmode", retval);
flush();
return retval;
}
public boolean isMuted()
{
load();
return data.containsKey("muted") && (Boolean)data.get("muted");
}
public boolean toggleMuted()
{
boolean retval = !isMuted();
data.put("muted", retval);
flush();
return retval;
}
public boolean isJailed()
{
//load(); Do not load config everytime time!
return data.containsKey("jailed") && (Boolean)data.get("jailed");
}
public boolean toggleJailed()
{
boolean retval = !isJailed();
data.put("jailed", retval);
flush();
load();
return retval;
}
public double getMoney()
{
load();
if (data.containsKey("money"))
{
if (data.get("money") instanceof Number)
{
return ((Number)data.get("money")).doubleValue();
}
logger.log(Level.SEVERE, "Can't convert money value to double:" + data.get("money"));
}
try
{
return com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).getBalance();
}
catch (Throwable ex)
{
try
{
Map<String, Object> idata = Essentials.getData(this);
return ((Number)idata.get("money")).doubleValue();
}
catch (Throwable ex2)
{
return Essentials.getSettings().getStartingBalance();
}
}
}
public void setMoney(double value)
{
try
{
com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).setBalance(value);
}
catch (Throwable ex)
{
data.put("money", value);
flush();
}
setLastHealTimestamp(now.getTimeInMillis());
}
public void giveMoney(double value)
{
if (value == 0) return;
if (value == 0)
{
return;
}
setMoney(getMoney() + value);
sendMessage("§a$" + value + " has been added to your account.");
}
public void payUser(User reciever, int value) throws Exception
public void payUser(User reciever, double value) throws Exception
{
if (value == 0) return;
if (value == 0)
{
return;
}
if (!canAfford(value))
{
throw new Exception("You do not have sufficient funds.");
@ -330,7 +108,10 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public void takeMoney(double value)
{
if (value == 0) return;
if (value == 0)
{
return;
}
setMoney(getMoney() - value);
sendMessage("§c$" + value + " has been taken from your account.");
}
@ -343,24 +124,28 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
return;
}
double mon = getMoney();
double cost = Essentials.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd);
if (mon < cost && !isOp())
double cost = ess.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd);
if (mon < cost && !isAuthorized("essentials.eco.loan"))
{
throw new Exception("You do not have sufficient funds.");
}
takeMoney(cost);
}
public void canAfford(String cmd) throws Exception
{
double mon = getMoney();
double cost = Essentials.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd);
if (mon < cost && !isOp())
double cost = ess.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd);
if (mon < cost && !isAuthorized("essentials.eco.loan"))
{
throw new Exception("You do not have sufficient funds.");
}
}
public boolean canAfford(double cost)
{
double mon = getMoney();
if (mon < cost && !isOp())
if (mon < cost && !isAuthorized("essentials.eco.loan"))
{
return false;
}
@ -375,312 +160,6 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
canAfford(cmd.getName());
}
public void cancelTeleport(boolean notifyUser)
{
if (teleTimer == -1) return;
try
{
getServer().getScheduler().cancelTask(teleTimer);
if (notifyUser) sendMessage("§cPending teleportation request cancelled.");
}
catch (Throwable ex)
{
}
finally
{
teleTimer = -1;
}
}
public void cancelTeleport()
{
cancelTeleport(false);
}
public void teleportTo(final Location loc, final String chargeFor)
{
final long delay = Essentials.getSettings().getTeleportDelay();
if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass"))
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportCooldown(false);
teleportToNow(loc);
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
return;
}
cancelTeleport();
sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move.");
teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay)
{
public void DoTeleport()
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportToNow(loc);
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
}
public void DoCancel()
{
cancelTeleport();
}
}, 10, 10);
}
@Override
public void teleportTo(final Location loc)
{
teleportTo(loc, null);
}
public void teleportTo(final Entity entity, final String chargeFor)
{
final long delay = Essentials.getSettings().getTeleportDelay();
if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass"))
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportCooldown(false);
teleportToNow(entity);
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
return;
}
cancelTeleport();
sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move.");
teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay)
{
public void DoTeleport()
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportToNow(entity);
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
}
public void DoCancel()
{
cancelTeleport();
}
}, 10, 10);
}
@Override
public void teleportTo(final Entity entity)
{
teleportTo(entity, null);
}
public Location getHome() throws Exception
{
return getHome(null);
}
public Location getHome(String playerName) throws Exception
{
Map<String, Object> userData = new HashMap<String, Object>();
if (playerName == null)
{
userData = data;
}
else
{
userData = Essentials.getData(playerName);
}
if (userData.containsKey("home"))
{
List<Object> vals = (List<Object>)userData.get("home");
World world = getServer() == null ? null : getServer().getWorlds().get(0);
if (vals.size() > 5 && getServer() != null)
{
world = getServer().getWorld((String)vals.get(5));
}
if (world == null)
{
throw new Exception();
}
return new Location(
world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
}
try
{
Map<String, Object> gdata = null;
if (playerName != null)
{
gdata = Essentials.getData(playerName);
}
else
{
gdata = Essentials.getData(this);
}
List<Object> vals = (List<Object>)gdata.get("home");
World world = getServer().getWorlds().get(0);
if (vals.size() > 5)
{
world = getServer().getWorld((String)vals.get(5));
}
if (world == null)
{
throw new Exception();
}
return new Location(world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
}
catch (Throwable ex)
{
throw new Exception("You have not set a home.");
}
}
public void teleportToHome(final String chargeFor)
{
teleportToHome(chargeFor, null);
}
public void teleportToHome(final String chargeFor, String otherPlayer)
{
final long delay = Essentials.getSettings().getTeleportDelay();
Location loc = null;
try
{// check this first in case user hasn't set a home yet
if (otherPlayer == null)
{
loc = getHome();
}
else
{
loc = getHome(otherPlayer);
}
}
catch (Throwable ex)
{
if (Essentials.getSettings().spawnIfNoHome())
{
try
{
respawn(Essentials.getStatic().spawn, null);
return;
}
catch (Throwable rex)
{
sendMessage("§cTeleport: " + rex.getMessage());
return;
}
}
sendMessage("§cTeleport: " + ex.getMessage());
return;
}
if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass"))
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportCooldown(false);
teleportToNow(loc);
sendMessage("§7Teleporting home...");
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
return;
}
cancelTeleport();
sendMessage("§7Teleportation will commence in "
+ Essentials.FormatTime(delay) + ". Don't move.");
teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay)
{
public void DoTeleport()
{
try
{
if (chargeFor != null) charge(chargeFor);
teleportToNow(getHome());
}
catch (Throwable ex)
{
sendMessage("§cError: " + ex.getMessage());
}
}
public void DoCancel()
{
cancelTeleport();
}
}, 10, 10);
}
public void teleportToHome()
{
teleportToHome(null);
}
public void teleportToNow(Location loc) throws Exception
{
cancelTeleport();
lastLocation = getLocation();
getBase().teleport(getSafeDestination(loc));
}
public void teleportToNow(Entity entity)
{
cancelTeleport();
lastLocation = getLocation();
getBase().teleport(entity);
}
public void teleportBack(final String chargeFor)
{
teleportTo(lastLocation, chargeFor);
}
public void teleportBack()
{
teleportBack(null);
}
public void dispose()
{
this.base = new OfflinePlayer(getName());
@ -694,9 +173,6 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public boolean getJustPortaled()
{
return justPortaled;
}
public void setJustPortaled(boolean value)
@ -714,53 +190,6 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
return replyTo;
}
public void setHome()
{
setHome(getLocation());
}
public void setHome(Location home)
{
List<Object> vals = new ArrayList<Object>(6);
vals.add(new Double(home.getX()));
vals.add(new Double(home.getY()));
vals.add(new Double(home.getZ()));
vals.add(new Double(home.getYaw()));
vals.add(new Double(home.getPitch()));
vals.add(home.getWorld() == null ? "world" : home.getWorld().getName());
data.put("home", vals);
flush();
setCompassTarget(home);
}
public String getNick()
{
Essentials ess = Essentials.getStatic();
String name = Essentials.getSettings().isCommandDisabled("nick") ? getName() : ess.readNickname(this);
if (isOp() && ess.getConfiguration().getString("ops-name-color", "c").matches("^[0-9a-f]$"))
name = "§" + ess.getConfiguration().getString("ops-name-color", "c") + name + "§f";
return name;
}
public void warpTo(String warp, final String chargeFor) throws Exception
{
lastLocation = getLocation();
Location loc = Essentials.getWarps().getWarp(warp);
teleportTo(loc, chargeFor);
sendMessage("§7Warping to " + warp + ".");
}
public void warpTo(String string) throws Exception
{
warpTo(string, null);
}
public void clearNewFlag()
{
isNew = false;
}
public int compareTo(User t)
{
return ChatColor.stripColor(this.getDisplayName()).compareToIgnoreCase(ChatColor.stripColor(t.getDisplayName()));
@ -768,75 +197,70 @@ public class User extends PlayerExtension implements Comparable<User>, IReplyTo
public Boolean canSpawnItem(int itemId)
{
return !Essentials.getSettings().itemSpawnBlacklist().contains(itemId);
return !ess.getSettings().itemSpawnBlacklist().contains(itemId);
}
@SuppressWarnings("unchecked")
public List<Integer> getUnlimited()
public void setHome()
{
if (!data.containsKey("unlimited"))
{
return new ArrayList<Integer>();
}
return (List<Integer>)data.get("unlimited");
setHome(getLocation(), true);
}
public boolean hasUnlimited(ItemStack stack)
public void setHome(boolean defaultHome)
{
return getUnlimited().contains(stack.getTypeId());
setHome(getLocation(), defaultHome);
}
@SuppressWarnings("unchecked")
public void setUnlimited(ItemStack stack, boolean state)
public void setLastLocation()
{
List<Integer> items = getUnlimited();
if (items.contains(stack.getTypeId()))
{
items.remove(Integer.valueOf(stack.getTypeId()));
}
if (state)
{
items.add(stack.getTypeId());
}
data.put("unlimited", items);
flush();
setLastLocation(getLocation());
}
public String getPowertool(ItemStack stack)
public void requestTeleport(User player, boolean here)
{
if (!data.containsKey("powertools"))
{
return null;
}
@SuppressWarnings("unchecked")
Map<Integer, String> tools = (Map<Integer, String>)data.get("powertools");
return tools.get(stack.getTypeId());
teleportRequester = player;
teleportRequestHere = here;
}
public void setPowertool(ItemStack stack, String command)
public User getTeleportRequest()
{
Map<Integer, String> tools = new HashMap<Integer, String>();
if (data.containsKey("powertools"))
return teleportRequester;
}
public boolean isTeleportRequestHere()
{
return teleportRequestHere;
}
public String getNick()
{
String nickname = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nickname == null || nickname.isEmpty() || nickname.equals(getName()))
{
tools = (Map<Integer, String>)data.get("powertools");
}
if (command == null || command.trim().isEmpty())
{
tools.remove(Integer.valueOf(stack.getTypeId()));
nickname = getName();
}
else
{
tools.put(Integer.valueOf(stack.getTypeId()), command.trim());
nickname = ess.getSettings().getNicknamePrefix() + nickname;
}
data.put("powertools", tools);
flush();
if (isOp())
{
nickname = ess.getSettings().getOperatorColor().toString() + nickname + "§f";
}
return nickname;
}
public Map<String,Object> getMetadata() {
return metadata;
public Teleport getTeleport()
{
return teleport;
}
public void setMetadata(String key, Object value) {
metadata.put(key, value);
public long getLastActivity()
{
return lastActivity;
}
public void setLastActivity(long timestamp)
{
lastActivity = timestamp;
}
}

View File

@ -13,23 +13,29 @@ import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public abstract class UserData extends PlayerExtension implements IConf {
public abstract class UserData extends PlayerExtension implements IConf
{
private EssentialsConf config;
private static final Logger logger = Logger.getLogger("Minecraft");
protected Essentials ess;
protected UserData(Player base, File folder) {
protected UserData(Player base, Essentials ess)
{
super(base);
folder = new File(folder, "userdata");
if (!folder.exists()) {
this.ess = ess;
File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
config = new EssentialsConf(new File(folder, base.getName()+".yml"));
config = new EssentialsConf(new File(folder, Util.sanitizeFileName(base.getName()) + ".yml"));
reloadConfig();
}
public final void reloadConfig() {
public final void reloadConfig()
{
config.load();
updateConfig();
unlimited = _getUnlimited();
powertools = getPowertools();
lastLocation = _getLastLocation();
@ -47,12 +53,15 @@ public abstract class UserData extends PlayerExtension implements IConf {
jailTimeout = _getJailTimeout();
lastLogin = _getLastLogin();
lastLogout = _getLastLogout();
afk = getAfk();
geolocation = _getGeoLocation();
}
public double getMoney() {
public double getMoney()
{
if (config.hasProperty("money"))
{
return config.getDouble("money", Essentials.getSettings().getStartingBalance());
return config.getDouble("money", ess.getSettings().getStartingBalance());
}
try
@ -61,11 +70,12 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
catch (Throwable ex)
{
return Essentials.getSettings().getStartingBalance();
return ess.getSettings().getStartingBalance();
}
}
public void setMoney(double value) {
public void setMoney(double value)
{
try
{
com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).setBalance(value);
@ -77,446 +87,572 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
}
public Location getHome() throws Exception {
public Location getHome()
{
if (config.hasProperty("home"))
{
World world = getLocation().getWorld();
String worldHome = "home.worlds." + world.getName().toLowerCase();
if (!config.hasProperty(worldHome)) {
if (!config.hasProperty(worldHome))
{
String defaultWorld = config.getString("home.default");
worldHome = "home.worlds." + defaultWorld;
}
Location loc = config.getLocation(worldHome, getServer());
if (loc == null) {
throw new Exception();
}
return loc;
} else {
throw new Exception("You have not set a home.");
}
return null;
}
public void setHome(Location loc, boolean b) {
public void setHome(Location loc, boolean b)
{
String worldName = loc.getWorld().getName().toLowerCase();
if (worldName == null || worldName.isEmpty()) {
if (worldName == null || worldName.isEmpty())
{
logger.log(Level.WARNING, "Set Home: World name is null or empty.");
return;
}
if (b) {
if (b || !config.hasProperty("home.default"))
{
config.setProperty("home.default", worldName);
}
config.setProperty("home.worlds."+worldName, loc);
config.setProperty("home.worlds." + worldName, loc);
config.save();
}
public String getNickname() {
public String getNickname()
{
return config.getString("nickname");
}
public void setNickname(String nick) {
public void setNickname(String nick)
{
config.setProperty("nickname", nick);
config.save();
}
private List<Integer> unlimited;
private List<Integer> _getUnlimited() {
private List<Integer> _getUnlimited()
{
return config.getIntList("unlimited", new ArrayList<Integer>());
}
public List<Integer> getUnlimited() {
public List<Integer> getUnlimited()
{
return unlimited;
}
public boolean hasUnlimited(ItemStack stack) {
public boolean hasUnlimited(ItemStack stack)
{
return unlimited.contains(stack.getTypeId());
}
public void setUnlimited(ItemStack stack, boolean state) {
if (unlimited.contains(stack.getTypeId())) {
public void setUnlimited(ItemStack stack, boolean state)
{
if (unlimited.contains(stack.getTypeId()))
{
unlimited.remove(Integer.valueOf(stack.getTypeId()));
}
if (state) {
if (state)
{
unlimited.add(stack.getTypeId());
}
config.setProperty("unlimited", unlimited);
config.save();
}
private Map<Integer, String> powertools;
@SuppressWarnings("unchecked")
private Map<Integer, String> getPowertools() {
private Map<Integer, String> getPowertools()
{
Object o = config.getProperty("powertools");
if (o != null && o instanceof Map) {
if (o != null && o instanceof Map)
{
return (Map<Integer, String>)o;
} else {
}
else
{
return new HashMap<Integer, String>();
}
}
public String getPowertool(ItemStack stack) {
public String getPowertool(ItemStack stack)
{
return powertools.get(stack.getTypeId());
}
public void setPowertool(ItemStack stack, String command) {
if (command == null || command.isEmpty()) {
public void setPowertool(ItemStack stack, String command)
{
if (command == null || command.isEmpty())
{
powertools.remove(stack.getTypeId());
} else {
}
else
{
powertools.put(stack.getTypeId(), command);
}
config.setProperty("powertools", powertools);
config.save();
}
private Location lastLocation;
private Location _getLastLocation() {
private Location _getLastLocation()
{
return config.getLocation("lastlocation", getServer());
}
public Location getLastLocation() {
public Location getLastLocation()
{
return lastLocation;
}
public void setLastLocation(Location loc) {
public void setLastLocation(Location loc)
{
lastLocation = loc;
config.setProperty("lastlocation", loc);
config.save();
}
private long lastTeleportTimestamp;
private long _getLastTeleportTimestamp() {
private long _getLastTeleportTimestamp()
{
return config.getLong("timestamps.lastteleport", 0);
}
public long getLastTeleportTimestamp() {
public long getLastTeleportTimestamp()
{
return lastTeleportTimestamp;
}
public void setLastTeleportTimestamp(long time) {
public void setLastTeleportTimestamp(long time)
{
lastTeleportTimestamp = time;
config.setProperty("timestamps.lastteleport", time);
config.save();
}
private long lastHealTimestamp;
private long _getLastHealTimestamp() {
private long _getLastHealTimestamp()
{
return config.getLong("timestamps.lastheal", 0);
}
public long getLastHealTimestamp() {
public long getLastHealTimestamp()
{
return lastHealTimestamp;
}
public void setLastHealTimestamp(long time) {
public void setLastHealTimestamp(long time)
{
lastHealTimestamp = time;
config.setProperty("timestamps.lastheal", time);
config.save();
}
private String jail;
private String _getJail() {
private String _getJail()
{
return config.getString("jail");
}
public String getJail() {
public String getJail()
{
return jail;
}
public void setJail(String jail) {
if (jail == null || jail.isEmpty()) {
public void setJail(String jail)
{
if (jail == null || jail.isEmpty())
{
this.jail = null;
config.removeProperty("jail");
} else {
}
else
{
this.jail = jail;
config.setProperty("jail", jail);
}
config.save();
}
private List<String> mails;
private List<String> _getMails() {
private List<String> _getMails()
{
return config.getStringList("mail", new ArrayList<String>());
}
public List<String> getMails() {
public List<String> getMails()
{
return mails;
}
public void setMails(List<String> mails) {
if (mails == null) {
public void setMails(List<String> mails)
{
if (mails == null)
{
config.removeProperty("mail");
} else {
}
else
{
config.setProperty("mail", mails);
}
this.mails = mails;
config.save();
}
public void addMail(String mail) {
public void addMail(String mail)
{
mails.add(mail);
setMails(mails);
}
private ItemStack[] savedInventory;
public ItemStack[] getSavedInventory() {
public ItemStack[] getSavedInventory()
{
return savedInventory;
}
private ItemStack[] _getSavedInventory() {
private ItemStack[] _getSavedInventory()
{
int size = config.getInt("inventory.size", 0);
if (size < 1 || size > getInventory().getSize()) {
if (size < 1 || size > getInventory().getSize())
{
return null;
}
ItemStack[] is = new ItemStack[size];
for (int i = 0; i < size; i++) {
is[i] = config.getItemStack("inventory."+i);
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) {
public void setSavedInventory(ItemStack[] is)
{
if (is == null || is.length == 0)
{
savedInventory = null;
config.removeProperty("inventory");
} else {
}
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) {
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.setProperty("inventory." + i, is[i]);
}
}
config.save();
}
private boolean teleportEnabled;
private boolean getTeleportEnabled() {
private boolean getTeleportEnabled()
{
return config.getBoolean("teleportenabled", true);
}
public boolean isTeleportEnabled() {
public boolean isTeleportEnabled()
{
return teleportEnabled;
}
public void setTeleportEnabled(boolean set) {
public void setTeleportEnabled(boolean set)
{
teleportEnabled = set;
config.setProperty("teleportenabled", set);
config.save();
}
public boolean toggleTeleportEnabled() {
public boolean toggleTeleportEnabled()
{
boolean ret = !isTeleportEnabled();
setTeleportEnabled(ret);
return ret;
}
private List<String> ignoredPlayers;
public List<String> getIgnoredPlayers() {
public List<String> getIgnoredPlayers()
{
return config.getStringList("ignore", new ArrayList<String>());
}
public void setIgnoredPlayers(List<String> players) {
if (players == null || players.isEmpty()) {
public void setIgnoredPlayers(List<String> players)
{
if (players == null || players.isEmpty())
{
ignoredPlayers = new ArrayList<String>();
config.removeProperty("ignore");
} else {
}
else
{
ignoredPlayers = players;
config.setProperty("ignore", players);
}
config.save();
}
public boolean isIgnoredPlayer(String name) {
public boolean isIgnoredPlayer(String name)
{
return ignoredPlayers.contains(name);
}
public void setIgnoredPlayer(String name, boolean set) {
if (set) {
public void setIgnoredPlayer(String name, boolean set)
{
if (set)
{
ignoredPlayers.add(name);
} else {
}
else
{
ignoredPlayers.remove(name);
}
setIgnoredPlayers(ignoredPlayers);
}
private boolean godmode;
private boolean getGodModeEnabled() {
return config.getBoolean("godmode", true);
private boolean getGodModeEnabled()
{
return config.getBoolean("godmode", false);
}
public boolean isGodModeEnabled() {
public boolean isGodModeEnabled()
{
return godmode;
}
public void setGodModeEnabled(boolean set) {
public void setGodModeEnabled(boolean set)
{
godmode = set;
config.setProperty("godmode", set);
config.save();
}
public boolean toggleGodModeEnabled() {
public boolean toggleGodModeEnabled()
{
boolean ret = !isGodModeEnabled();
setGodModeEnabled(ret);
return ret;
}
private boolean muted;
private boolean getMuted() {
return config.getBoolean("muted", true);
private boolean getMuted()
{
return config.getBoolean("muted", false);
}
public boolean isMuted() {
public boolean isMuted()
{
return muted;
}
public void setMuted(boolean set) {
public void setMuted(boolean set)
{
muted = set;
config.setProperty("muted", set);
config.save();
}
public boolean toggleMuted() {
public boolean toggleMuted()
{
boolean ret = !isMuted();
setMuted(ret);
return ret;
}
private long muteTimeout;
private long _getMuteTimeout() {
private long _getMuteTimeout()
{
return config.getLong("timestamps.mute", 0);
}
public long getMuteTimeout() {
public long getMuteTimeout()
{
return muteTimeout;
}
public void setMuteTimeout(long time) {
public void setMuteTimeout(long time)
{
muteTimeout = time;
config.setProperty("timestamps.mute", time);
config.save();
}
private boolean jailed;
private boolean getJailed() {
return config.getBoolean("jailed", true);
private boolean getJailed()
{
return config.getBoolean("jailed", false);
}
public boolean isJailed() {
public boolean isJailed()
{
return jailed;
}
public void setJailed(boolean set) {
public void setJailed(boolean set)
{
jailed = set;
config.setProperty("jailed", set);
config.save();
}
public boolean toggleJailed() {
public boolean toggleJailed()
{
boolean ret = !isJailed();
setJailed(ret);
return ret;
}
private long jailTimeout;
private long _getJailTimeout() {
private long _getJailTimeout()
{
return config.getLong("timestamps.jail", 0);
}
public long getJailTimeout() {
public long getJailTimeout()
{
return jailTimeout;
}
public void setJailTimeout(long time) {
public void setJailTimeout(long time)
{
jailTimeout = time;
config.setProperty("timestamps.jail", time);
config.save();
}
public String getBanReason() {
public String getBanReason()
{
return config.getString("ban.reason");
}
public void setBanReason(String reason) {
public void setBanReason(String reason)
{
config.setProperty("ban.reason", reason);
config.save();
}
public long getBanTimeout() {
public long getBanTimeout()
{
return config.getLong("ban.timeout", 0);
}
public void setBanTimeout(long time) {
public void setBanTimeout(long time)
{
config.setProperty("ban.timeout", time);
config.save();
}
private long lastLogin;
private long _getLastLogin() {
private long _getLastLogin()
{
return config.getLong("timestamps.login", 0);
}
public long getLastLogin() {
public long getLastLogin()
{
return lastLogin;
}
public void setLastLogin(long time) {
public void setLastLogin(long time)
{
lastLogin = time;
config.setProperty("timestamps.login", time);
config.save();
}
private long lastLogout;
private long _getLastLogout() {
private long _getLastLogout()
{
return config.getLong("timestamps.logout", 0);
}
public long getLastLogout() {
public long getLastLogout()
{
return lastLogout;
}
public void setLastLogout(long time) {
public void setLastLogout(long time)
{
lastLogout = time;
config.setProperty("timestamps.logout", time);
config.save();
}
private boolean afk;
private void updateConfig() {
if (config.hasProperty("home") && !config.hasProperty("home.default")) {
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>)config.getProperty("home");
World world = getServer() == null ? null : getServer().getWorlds().get(0);
if (vals.size() > 5 && getServer() != null) {
world = getServer().getWorld((String)vals.get(5));
}
Location loc = new Location(
world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
config.removeProperty("home");
setHome(loc, true);
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 boolean getNew()
{
return config.getBoolean("newplayer", true);
}
public boolean isNew()
{
return newplayer;
}
public void setNew(boolean set)
{
newplayer = set;
config.setProperty("newplayer", set);
config.save();
}
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();
}
}

View File

@ -0,0 +1,259 @@
package com.earth2me.essentials;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
public class Util
{
public static String sanitizeFileName(String name)
{
return name.toLowerCase().replaceAll("[^a-z0-9]", "_");
}
public static String formatDateDiff(long date)
{
Calendar c = new GregorianCalendar();
c.setTimeInMillis(date);
Calendar now = new GregorianCalendar();
return Util.formatDateDiff(now, c);
}
public static String formatDateDiff(Calendar fromDate, Calendar toDate)
{
boolean future = false;
if (toDate.equals(fromDate))
{
return "now";
}
if (toDate.after(fromDate))
{
future = true;
}
StringBuilder sb = new StringBuilder();
int[] types = new int[]
{
Calendar.YEAR,
Calendar.MONTH,
Calendar.DAY_OF_MONTH,
Calendar.HOUR_OF_DAY,
Calendar.MINUTE,
Calendar.SECOND
};
String[] names = new String[]
{
"year",
"month",
"day",
"hour",
"minute",
"second"
};
for (int i = 0; i < types.length; i++)
{
int diff = dateDiff(types[i], fromDate, toDate, future);
if (diff > 0)
{
sb.append(" ").append(diff).append(" ").append(names[i]);
if (diff > 1)
{
sb.append("s");
}
}
}
if (sb.length() == 0)
{
return "now";
}
return sb.toString();
}
private static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future)
{
int diff = 0;
while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate)))
{
fromDate.add(type, future ? 1 : -1);
diff++;
}
diff--;
fromDate.add(type, future ? -1 : 1);
return diff;
}
private static Pattern timePattern = Pattern.compile(
"(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?"
+ "(?:([0-9]+)\\s*s[a-z]*)?", Pattern.CASE_INSENSITIVE);
public static long parseDateDiff(String time, boolean future) throws Exception
{
Matcher m = timePattern.matcher(time);
int years = 0;
int months = 0;
int weeks = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
boolean found = false;
while (m.find())
{
if (m.group() == null || m.group().isEmpty())
{
continue;
}
for (int i = 0; i < m.groupCount(); i++)
{
if (m.group(i) != null && !m.group(i).isEmpty())
{
found = true;
break;
}
}
if (found)
{
if (m.group(1) != null && !m.group(1).isEmpty())
{
years = Integer.parseInt(m.group(1));
}
if (m.group(2) != null && !m.group(2).isEmpty())
{
months = Integer.parseInt(m.group(2));
}
if (m.group(3) != null && !m.group(3).isEmpty())
{
weeks = Integer.parseInt(m.group(3));
}
if (m.group(4) != null && !m.group(4).isEmpty())
{
days = Integer.parseInt(m.group(4));
}
if (m.group(5) != null && !m.group(5).isEmpty())
{
hours = Integer.parseInt(m.group(5));
}
if (m.group(6) != null && !m.group(6).isEmpty())
{
minutes = Integer.parseInt(m.group(6));
}
if (m.group(7) != null && !m.group(7).isEmpty())
{
seconds = Integer.parseInt(m.group(7));
}
break;
}
}
if (!found)
{
throw new Exception("Illegal date format.");
}
Calendar c = new GregorianCalendar();
if (years > 0)
{
c.add(Calendar.YEAR, years * (future ? 1 : -1));
}
if (months > 0)
{
c.add(Calendar.MONTH, months * (future ? 1 : -1));
}
if (weeks > 0)
{
c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1));
}
if (days > 0)
{
c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1));
}
if (hours > 0)
{
c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1));
}
if (minutes > 0)
{
c.add(Calendar.MINUTE, minutes * (future ? 1 : -1));
}
if (seconds > 0)
{
c.add(Calendar.SECOND, seconds * (future ? 1 : -1));
}
return c.getTimeInMillis();
}
public static Location getSafeDestination(Location loc) throws Exception
{
if (loc == null)
{
throw new Exception("Destination not set");
}
World world = loc.getWorld();
double x = Math.floor(loc.getX()) + 0.5;
double y = Math.floor(loc.getY());
double z = Math.floor(loc.getZ()) + 0.5;
while (isBlockAboveAir(world, x, y, z))
{
y -= 1.0D;
if (y < 0.0D)
{
throw new Exception("Hole in floor");
}
}
while (isBlockUnsafe(world, x, y, z))
{
y += 1.0D;
if (y >= 110.0D)
{
x += 1.0D;
break;
}
}
while (isBlockUnsafe(world, x, y, z))
{
y -= 1.0D;
if (y <= 1.0D)
{
y = 110.0D;
x += 1.0D;
}
}
return new Location(world, x, y, z, loc.getYaw(), loc.getPitch());
}
private static boolean isBlockAboveAir(World world, double x, double y, double z)
{
return world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)).getType() == Material.AIR;
}
public static boolean isBlockUnsafe(World world, double x, double y, double z)
{
Block below = world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z));
if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA)
{
return true;
}
if (below.getType() == Material.FIRE)
{
return true;
}
if ((world.getBlockAt((int)Math.floor(x), (int)Math.floor(y), (int)Math.floor(z)).getType() != Material.AIR)
|| (world.getBlockAt((int)Math.floor(x), (int)Math.floor(y + 1.0D), (int)Math.floor(z)).getType() != Material.AIR))
{
return true;
}
return isBlockAboveAir(world, x, y, z);
}
}

View File

@ -1,215 +1,109 @@
package com.earth2me.essentials;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
public class Warps implements IConf {
public class Warps implements IConf
{
private static final Logger logger = Logger.getLogger("Minecraft");
Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>();
File warpsFolder;
Server server;
public Warps(Server server, File dataFolder) {
public Warps(Server server, File dataFolder)
{
this.server = server;
warpsFolder = new File(dataFolder, "warps");
if (!warpsFolder.exists()) {
if (!warpsFolder.exists())
{
warpsFolder.mkdirs();
} else {
convertWarps(dataFolder);
}
reloadConfig();
}
private String convertToFileName(String name) {
return name.toLowerCase().replaceAll("[^a-z0-9]", "_");
}
public boolean isEmpty() {
public boolean isEmpty()
{
return warpPoints.isEmpty();
}
public Iterable<String> getWarpNames() {
public Iterable<String> getWarpNames()
{
List<String> keys = new ArrayList<String>();
for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) {
for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet())
{
keys.add(stringIgnoreCase.string);
}
Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
return keys;
}
public Location getWarp(String warp) throws Exception {
public Location getWarp(String warp) throws Exception
{
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
if (conf == null) {
if (conf == null)
{
throw new Exception("That warp does not exist.");
}
double x = conf.getDouble("x", 0);
double y = conf.getDouble("y", 0);
double z = conf.getDouble("z", 0);
float yaw = (float) conf.getDouble("yaw", 0);
float pitch = (float) conf.getDouble("pitch", 0);
String world = conf.getString("world");
World w = server.getWorld(world);
if (w == null) {
throw new Exception("World of warp does not exist.");
}
return new Location(w, x, y, z, yaw, pitch);
return conf.getLocation(null, server);
}
public void setWarp(String name, Location loc) throws Exception {
setWarp(name, loc, null);
}
private void setWarp(String name, Location loc, String worldName) throws Exception {
String filename = convertToFileName(name);
public void setWarp(String name, Location loc) throws Exception
{
String filename = Util.sanitizeFileName(name);
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) {
if (conf == null)
{
File confFile = new File(warpsFolder, filename + ".yml");
if (confFile.exists()) {
if (confFile.exists())
{
throw new Exception("A warp with a similar name already exists.");
}
conf = new EssentialsConf(confFile);
conf.setProperty("name", name);
warpPoints.put(new StringIgnoreCase(name), conf);
}
conf.setProperty("x", loc.getBlockX());
conf.setProperty("y", loc.getBlockY());
conf.setProperty("z", loc.getBlockZ());
conf.setProperty("yaw", loc.getYaw());
conf.setProperty("pitch", loc.getPitch());
if (worldName != null) {
conf.setProperty("world", worldName);
} else {
conf.setProperty("world", loc.getWorld().getName());
}
conf.setProperty(null, loc);
conf.setProperty("name", name);
conf.save();
}
public void delWarp(String name) throws Exception {
public void delWarp(String name) throws Exception
{
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) {
if (conf == null)
{
throw new Exception("Warp does not exist.");
}
if (!conf.getFile().delete()) {
if (!conf.getFile().delete())
{
throw new Exception("Problem deleting the warp file.");
}
warpPoints.remove(new StringIgnoreCase(name));
}
private void convertWarps(File dataFolder) {
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(".dat")) {
try {
BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i]));
double x = Double.parseDouble(rx.readLine().trim());
double y = Double.parseDouble(rx.readLine().trim());
double z = Double.parseDouble(rx.readLine().trim());
float yaw = Float.parseFloat(rx.readLine().trim());
float pitch = Float.parseFloat(rx.readLine().trim());
String worldName = rx.readLine();
rx.close();
World w = null;
for (World world : server.getWorlds()) {
if (world.getEnvironment() != World.Environment.NETHER) {
w = world;
break;
}
}
boolean forceWorldName = false;
if (worldName != null) {
worldName.trim();
World w1 = null;
for (World world : server.getWorlds()) {
if (world.getName().equalsIgnoreCase(worldName)) {
w1 = world;
break;
}
}
if (w1 != null) {
w = w1;
} else {
File worldFolder = new File(dataFolder.getAbsoluteFile().getParentFile().getParentFile(), worldName);
if (worldFolder.exists() && worldFolder.isDirectory()) {
logger.log(Level.WARNING, "World " + worldName + " not loaded, but directory found. Converting warp anyway.");
forceWorldName = true;
}
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
setWarp(filename.substring(0, filename.length() - 4), loc, forceWorldName ? worldName : null);
if(!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old")))
{
throw new Exception("Renaming file " + filename + " failed");
}
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
}
File warpFile = new File(dataFolder, "warps.txt");
if (warpFile.exists()) {
try {
BufferedReader rx = new BufferedReader(new FileReader(warpFile));
for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":")) {
if (parts.length < 6) {
continue;
}
String name = parts[0];
double x = Double.parseDouble(parts[1].trim());
double y = Double.parseDouble(parts[2].trim());
double z = Double.parseDouble(parts[3].trim());
float yaw = Float.parseFloat(parts[4].trim());
float pitch = Float.parseFloat(parts[5].trim());
if (name.isEmpty()) {
continue;
}
World w = null;
for (World world : server.getWorlds()) {
if (world.getEnvironment() != World.Environment.NETHER) {
w = world;
break;
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
setWarp(name, loc);
if(!warpFile.renameTo(new File(dataFolder, "warps.txt.old")));
{
throw new Exception("Renaming warps.txt failed");
}
}
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
public final void reloadConfig() {
public final void reloadConfig()
{
warpPoints.clear();
File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles.length >= 1)
{
for (int i = 0; i < listOfFiles.length; i++)
{
String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".yml")) {
if (listOfFiles[i].isFile() && filename.endsWith(".yml"))
{
EssentialsConf conf = new EssentialsConf(listOfFiles[i]);
conf.load();
String name = conf.getString("name");
if (name != null) {
if (name != null)
{
warpPoints.put(new StringIgnoreCase(name), conf);
}
}
@ -217,26 +111,32 @@ public class Warps implements IConf {
}
}
private class StringIgnoreCase {
private class StringIgnoreCase
{
String string;
public StringIgnoreCase(String string) {
public StringIgnoreCase(String string)
{
this.string = string;
}
@Override
public int hashCode() {
public int hashCode()
{
return string.toLowerCase().hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof String) {
return string.equalsIgnoreCase((String) o);
public boolean equals(Object o)
{
if (o instanceof String)
{
return string.equalsIgnoreCase((String)o);
}
if (o instanceof StringIgnoreCase) {
return string.equalsIgnoreCase(((StringIgnoreCase) o).string);
if (o instanceof StringIgnoreCase)
{
return string.equalsIgnoreCase(((StringIgnoreCase)o).string);
}
return false;
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,20 +12,17 @@ public class Commandafk extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
charge(user);
if (parent.away.contains(user))
if (!user.toggleAfk())
{
user.sendMessage("§7You are no longer marked as away.");
server.broadcastMessage("§7" + user.getDisplayName() + " is no longer AFK");
parent.away.remove(user);
return;
} else {
user.sendMessage("§7You are now marked as away.");
server.broadcastMessage("§7" + user.getDisplayName() + " is now AFK");
}
user.sendMessage("§7You are now marked as away.");
server.broadcastMessage("§7" + user.getDisplayName() + " is now AFK");
parent.away.add(user);
}
}

View File

@ -5,7 +5,6 @@ import net.minecraft.server.World;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.craftbukkit.CraftWorld;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.TargetBlock;
@ -18,14 +17,9 @@ public class Commandantioch extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
/*if (!user.isOp())
{
user.sendMessage("§cNone shall pass.");
return;
}*/
charge(user);
server.broadcastMessage("...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,");
server.broadcastMessage("who being naughty in My sight, shall snuff it.");

View File

@ -1,6 +1,5 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server;
@ -13,10 +12,10 @@ public class Commandback extends EssentialsCommand
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.canAfford(this);
user.sendMessage("§7Returning to previous location.");
user.teleportBack(this.getName());
user.getTeleport().back(this.getName());
}
}

View File

@ -1,43 +1,28 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Backup;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
/**
*
* @author schlex
*/
public class Commandbackup extends EssentialsCommand {
public Commandbackup() {
public class Commandbackup extends EssentialsCommand
{
public Commandbackup()
{
super("backup");
}
@Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception {
Backup backup = Essentials.getStatic().backup;
if (backup == null) return;
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
Backup backup = Essentials.getBackup();
if (backup == null)
{
return;
}
charge(sender);
backup.run();
sender.sendMessage("Backup started");
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception {
Backup backup = Essentials.getStatic().backup;
if (backup == null) return;
user.charge(this);
backup.run();
user.sendMessage("Backup started");
}
}

View File

@ -1,9 +1,8 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand;
import org.bukkit.command.CommandSender;
public class Commandbalance extends EssentialsCommand
@ -14,10 +13,22 @@ public class Commandbalance extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
sender.sendMessage("§7Balance: $" + getPlayer(server, args, 0).getMoney());
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
charge(user);
user.sendMessage("§7Balance: $" + (args.length < 1 || !user.isAuthorized("essentials.balance.other")
? user
: getPlayer(server, args, 0)).getMoney());
? user
: getPlayer(server, args, 0)).getMoney());
}
}

View File

@ -3,7 +3,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -15,35 +14,31 @@ public class Commandban extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("§cUsage: /" + commandLabel + " [player] <reason>");
return;
throw new NotEnoughArgumentsException();
}
try
User p = null;
if (server.matchPlayer(args[0]).isEmpty())
{
User p = null;
if (server.matchPlayer(args[0]).isEmpty())
{
((CraftServer)server).getHandle().a(args[0]);
sender.sendMessage("§cPlayer " + args[0] + " banned");
}
else
{
p = User.get(server.matchPlayer(args[0]).get(0));
p.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Banned from server");
((CraftServer)server).getHandle().a(p.getName());
sender.sendMessage("§cPlayer " + p.getName() + " banned");
}
Essentials.getStatic().loadBanList();
((CraftServer)server).getHandle().a(args[0]);
sender.sendMessage("§cPlayer " + args[0] + " banned");
}
catch (Throwable ex)
else
{
ex.printStackTrace();
sender.sendMessage("Error: " + ex);
p = ess.getUser(server.matchPlayer(args[0]).get(0));
String banReason = "Banned from server";
if(args.length > 1) {
banReason = getFinalArg(args, 1);
p.setBanReason(commandLabel);
}
p.kickPlayer(banReason);
((CraftServer)server).getHandle().a(p.getName());
sender.sendMessage("§cPlayer " + p.getName() + " banned");
}
ess.loadBanList();
}
}

View File

@ -3,7 +3,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.Essentials;
public class Commandbanip extends EssentialsCommand
@ -14,17 +13,16 @@ public class Commandbanip extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("Usage: /" + commandLabel + " [address]");
return;
throw new NotEnoughArgumentsException();
}
((CraftServer)server).getHandle().c(args[0]);
sender.sendMessage("§7Banned IP address.");
Essentials.getStatic().loadBanList();
ess.loadBanList();
}
}

View File

@ -2,8 +2,8 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.TreeType;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.Location;
@ -15,7 +15,7 @@ public class Commandbigtree extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
Object tree = new Object();
if (args.length > 0 && args[0].equalsIgnoreCase("redwood"))
@ -28,8 +28,7 @@ public class Commandbigtree extends EssentialsCommand
}
else
{
user.sendMessage("§cUsage: /" + commandLabel + " [tree|redwood]");
return;
throw new NotEnoughArgumentsException();
}
double x = user.getLocation().getX();
@ -38,19 +37,33 @@ public class Commandbigtree extends EssentialsCommand
// offset tree in direction player is facing
int r = (int)user.getCorrectedYaw();
if (r < 68 || r > 292) x -= 3.0D; // north
else if (r > 112 && r < 248) x += 3.0D; // south
if (r > 22 && r < 158) z -= 3.0D; // east
else if (r > 202 && r < 338) z += 3.0D; // west
if (r < 68 || r > 292) // north
{
x -= 3.0D;
}
else if (r > 112 && r < 248) // south
{
x += 3.0D;
}
if (r > 22 && r < 158) // east
{
z -= 3.0D;
}
else if (r > 202 && r < 338) // west
{
z += 3.0D;
}
Location safeLocation = user.getSafeDestination(new Location(user.getWorld(), x, y, z));
Location safeLocation = Util.getSafeDestination(new Location(user.getWorld(), x, y, z));
boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree);
if (success)
{
user.charge(this);
charge(user);
user.sendMessage("Big tree spawned.");
}
else
{
user.sendMessage("§cBig tree generation failure. Try again on grass or dirt.");
}
}
}

View File

@ -1,8 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
@ -14,20 +12,14 @@ public class Commandbroadcast extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("Usage: /" + commandLabel + " [msg]");
throw new NotEnoughArgumentsException();
}
StringBuilder message = new StringBuilder();
for (int i = 0; i < args.length; i++)
{
message.append(args[i]);
message.append(' ');
}
server.broadcastMessage("[§cBroadcast§f]§a " + message.toString());
charge(sender);
server.broadcastMessage("[§cBroadcast§f]§a " + getFinalArg(args, 0));
}
}

View File

@ -1,32 +1,30 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandburn extends EssentialsCommand
{
public Commandburn()
{
super("burn");
}
public Commandburn()
{
super("burn");
}
@Override
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
user.sendMessage("§cUsage: /burn [player] [seconds]");
return;
}
User.charge(user, this);
for (Player p : server.matchPlayer(args[0]))
{
p.setFireTicks(Integer.parseInt(args[1]) * 20);
user.sendMessage("§cYou set " + p.getDisplayName() + " on fire for " + Integer.parseInt(args[1]) + "seconds.");
}
}
charge(sender);
for (Player p : server.matchPlayer(args[0]))
{
p.setFireTicks(Integer.parseInt(args[1]) * 20);
sender.sendMessage("§cYou set " + p.getDisplayName() + " on fire for " + Integer.parseInt(args[1]) + "seconds.");
}
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
@ -17,16 +16,7 @@ public class Commandclearinventory extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[]
{
getName(), "ci"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length > 0 && user.isAuthorized("essentials.clearinventory.others"))
{
@ -36,11 +26,11 @@ public class Commandclearinventory extends EssentialsCommand
if (!online.isEmpty())
{
charge(user);
for (Player p : online)
{
p.getInventory().clear();
user.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared.");
user.charge(this);
}
return;
}
@ -48,12 +38,12 @@ public class Commandclearinventory extends EssentialsCommand
}
else
{
Player u = server.getPlayer(args[0]);
if (u != null)
Player p = server.getPlayer(args[0]);
if (p != null)
{
u.getInventory().clear();
user.sendMessage("§7Inventory of §c" + u.getDisplayName() + "§7 cleared.");
user.charge(this);
charge(user);
p.getInventory().clear();
user.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared.");
}
else
{
@ -63,14 +53,14 @@ public class Commandclearinventory extends EssentialsCommand
}
else
{
charge(user);
user.getInventory().clear();
user.sendMessage("§7Inventory cleared.");
user.charge(this);
}
}
@Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,9 +12,9 @@ public class Commandcompass extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
charge(user);
int r = (int)user.getCorrectedYaw();
String dir;
if (r < 23) dir = "N";

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
@ -12,22 +11,13 @@ public class Commanddeljail extends EssentialsCommand {
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception {
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception {
if (args.length < 1)
{
user.sendMessage("§cUsage: /" + commandLabel + " [jailname]");
return;
throw new NotEnoughArgumentsException();
}
user.charge(this);
charge(sender);
Essentials.getJail().delJail(args[0]);
user.sendMessage("§7Jail " + args[0] + " has been removed");
sender.sendMessage("§7Jail " + args[0] + " has been removed");
}
@Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception {
super.run(server, parent, sender, commandLabel, args);
}
}

View File

@ -3,7 +3,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commanddelwarp extends EssentialsCommand
@ -14,27 +13,13 @@ public class Commanddelwarp extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /" + commandLabel + " [warp name]");
return;
throw new NotEnoughArgumentsException();
}
user.charge(this);
Essentials.getWarps().delWarp(args[0]);
user.sendMessage("§7Warp removed.");
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("§cUsage: /" + commandLabel + " [warp name]");
return;
}
charge(sender);
Essentials.getWarps().delWarp(args[0]);
sender.sendMessage("§7Warp removed.");
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,12 +12,21 @@ public class Commanddepth extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
charge(user);
int y = user.getLocation().getBlockY() - 63;
if (y > 0) user.sendMessage("§7You are " + y + " block(s) above sea level.");
else if (y < 0) user.sendMessage("§7You are " + (-y) + " block(s) below sea level.");
else user.sendMessage("§7You are at sea level.");
if (y > 0)
{
user.sendMessage("§7You are " + y + " block(s) above sea level.");
}
else if (y < 0)
{
user.sendMessage("§7You are " + (-y) + " block(s) below sea level.");
}
else
{
user.sendMessage("§7You are at sea level.");
}
}
}

View File

@ -15,26 +15,29 @@ public class Commandeco extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
EcoCommands cmd;
int amount;
double amount;
try
{
cmd = EcoCommands.valueOf(args[0].toUpperCase());
amount = Integer.parseInt(args[2].replaceAll("[^0-9]", ""));
amount = Double.parseDouble(args[2].replaceAll("[^0-9\\.]", ""));
}
catch (Exception ex)
{
sender.sendMessage("§cUsage: /eco [give|take|reset] [player] [money]");
return;
throw new NotEnoughArgumentsException();
}
if (args[1].contentEquals("*"))
{
for (Player p : server.getOnlinePlayers())
{
User u = User.get(p);
User u = ess.getUser(p);
switch (cmd)
{
case GIVE:
@ -46,7 +49,7 @@ public class Commandeco extends EssentialsCommand
break;
case RESET:
u.setMoney(amount == 0 ? Essentials.getSettings().getStartingBalance() : amount);
u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break;
}
}
@ -55,7 +58,7 @@ public class Commandeco extends EssentialsCommand
{
for (Player p : server.matchPlayer(args[1]))
{
User u = User.get(p);
User u = ess.getUser(p);
switch (cmd)
{
case GIVE:
@ -67,7 +70,7 @@ public class Commandeco extends EssentialsCommand
break;
case RESET:
u.setMoney(amount == 0 ? Essentials.getSettings().getStartingBalance() : amount);
u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break;
}
}

View File

@ -2,8 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commandessentials extends EssentialsCommand
@ -14,17 +12,10 @@ public class Commandessentials extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
parent.reload();
user.charge(this);
user.sendMessage("§7Essentials Reloaded " + parent.getDescription().getVersion());
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
parent.reload();
sender.sendMessage("Essentials Reloaded " + parent.getDescription().getVersion());
ess.reload();
charge(sender);
sender.sendMessage("§7Essentials Reloaded " + ess.getDescription().getVersion());
}
}

View File

@ -1,29 +1,50 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandext extends EssentialsCommand {
public Commandext() {
public class Commandext extends EssentialsCommand
{
public Commandext()
{
super("ext");
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception {
if (args.length < 1) {
User.charge(user, this);
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
extinguishPlayers(server, sender, args[0]);
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
charge(user);
user.setFireTicks(0);
user.sendMessage("§7You extinguished yourself.");
return;
}
for (Player p : server.matchPlayer(args[0])) {
User.charge(user, this);
extinguishPlayers(server, user, commandLabel);
}
private void extinguishPlayers(Server server, CommandSender sender, String name) throws Exception
{
for (Player p : server.matchPlayer(name))
{
charge(sender);
p.setFireTicks(0);
user.sendMessage("§7You extinguished " + p.getDisplayName() + ".");
sender.sendMessage("§7You extinguished " + p.getDisplayName() + ".");
}
}
}

View File

@ -1,6 +1,5 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
@ -14,11 +13,12 @@ public class Commandgc extends EssentialsCommand
}
@Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
charge(sender);
sender.sendMessage("Maximum memory: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " MB");
sender.sendMessage("Free memory: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " MB");
for (World w : parent.getServer().getWorlds())
for (World w : server.getWorlds())
{
sender.sendMessage(
(w.getEnvironment() == World.Environment.NETHER ? "Nether" : "World") + " \"" + w.getName() + "\": "

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -14,15 +13,9 @@ public class Commandgetpos extends EssentialsCommand
}
@Override
public String[] getTriggers()
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
return new String[] { getName(), "coords" };
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
charge(user);
Location coords = user.getLocation();
user.sendMessage("§7X: " + coords.getBlockX() + " (-North <-> +South)");
user.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)");

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.ItemDb;
import com.earth2me.essentials.User;
import org.bukkit.ChatColor;
@ -19,26 +18,29 @@ public class Commandgive extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
sender.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [player] [item]<:data> <amount>");
return;
throw new NotEnoughArgumentsException();
}
String[] itemArgs = args[1].split("[^a-zA-Z0-9]");
ItemStack stack = ItemDb.get(itemArgs[0]);
if(sender instanceof Player && !User.get(sender).isAuthorized("essentials.itemspawn.exempt") && !User.get(sender).canSpawnItem(stack.getTypeId()))
if (sender instanceof Player
&& !ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt")
&& !ess.getUser(sender).canSpawnItem(stack.getTypeId()))
{
sender.sendMessage(ChatColor.RED + "You are not allowed to spawn that item");
return;
}
if (itemArgs.length > 1) {
if (itemArgs.length > 1)
{
stack.setDurability(Short.parseShort(itemArgs[1]));
}
if (args.length > 2 && Integer.parseInt(args[2]) > 0) {
if (args.length > 2 && Integer.parseInt(args[2]) > 0)
{
stack.setAmount(Integer.parseInt(args[2]));
}
@ -49,9 +51,7 @@ public class Commandgive extends EssentialsCommand
User giveTo = getPlayer(server, args, 0);
String itemName = stack.getType().name().toLowerCase().replace('_', ' ');
if (sender instanceof Player) {
User.get(sender).charge(this);
}
charge(sender);
sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + ".");
giveTo.getInventory().addItem(stack);
}

View File

@ -1,8 +1,8 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -14,26 +14,37 @@ public class Commandgod extends EssentialsCommand
}
@Override
public String[] getTriggers() {
return new String[] {
getName(), "egod"
};
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
godOtherPlayers(server, sender, args[0]);
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length > 0 && (user.isAuthorized("essentials.god.others") || user.isOp()))
charge(user);
if (args.length > 0 && user.isAuthorized("essentials.god.others"))
{
for (Player p : server.matchPlayer(args[0]))
{
User u = User.get(p);
boolean enabled = u.toggleGodMode();
u.sendMessage("§7God mode " + (enabled ? "enabled." : "disabled."));
user.sendMessage("§7God mode " + (enabled ? "enabled for " : "disabled for ") + p.getDisplayName() + ".");
}
godOtherPlayers(server, user, args[0]);
return;
}
user.sendMessage("§7God mode " + (user.toggleGodMode() ? "enabled." : "disabled."));
user.sendMessage("§7God mode " + (user.toggleGodModeEnabled() ? "enabled." : "disabled."));
}
private void godOtherPlayers(Server server, CommandSender sender, String name)
{
for (Player p : server.matchPlayer(name))
{
User u = ess.getUser(p);
boolean enabled = u.toggleGodModeEnabled();
u.sendMessage("§7God mode " + (enabled ? "enabled." : "disabled."));
sender.sendMessage("§7God mode " + (enabled ? "enabled for " : "disabled for ") + p.getDisplayName() + ".");
}
}
}

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
@ -15,46 +14,46 @@ public class Commandheal extends EssentialsCommand
}
@Override
public String[] getTriggers() {
return new String[] {
getName(), "eheal"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length > 0 && user.isAuthorized("essentials.heal.others"))
{
if (!user.isAuthorized("essentials.heal.cooldown.bypass")) user.healCooldown();
user.charge(this);
for (Player p : server.matchPlayer(args[0]))
if (!user.isAuthorized("essentials.heal.cooldown.bypass"))
{
p.setHealth(20);
user.sendMessage("§7Healed " + p.getDisplayName() + ".");
user.healCooldown();
}
charge(user);
healOtherPlayers(server, user, commandLabel);
return;
}
if (!user.isAuthorized("essentials.heal.cooldown.bypass")) user.healCooldown();
user.charge(this);
if (!user.isAuthorized("essentials.heal.cooldown.bypass"))
{
user.healCooldown();
}
charge(user);
user.setHealth(20);
user.sendMessage("§7You have been healed.");
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("Usage: /" + commandLabel + " [player]");
return;
throw new NotEnoughArgumentsException();
}
for (Player p : server.matchPlayer(args[0]))
healOtherPlayers(server, sender, args[0]);
}
private void healOtherPlayers(Server server, CommandSender sender, String name)
{
for (Player p : server.matchPlayer(name))
{
p.setHealth(20);
sender.sendMessage("Healed " + p.getDisplayName() + ".");
sender.sendMessage("§7Healed " + p.getDisplayName() + ".");
}
}
}

View File

@ -26,7 +26,7 @@ public class Commandhelp extends EssentialsCommand
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
int page;
try
@ -38,7 +38,7 @@ public class Commandhelp extends EssentialsCommand
page = 1;
}
List<String> lines = getHelpLines(parent, user);
List<String> lines = getHelpLines(user);
int start = (page - 1) * 9;
int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0);
@ -50,16 +50,16 @@ public class Commandhelp extends EssentialsCommand
}
@Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
sender.sendMessage("To view help from the console, type \"?\".");
}
@SuppressWarnings("CallToThreadDumpStack")
private List<String> getHelpLines(Essentials parent, User user) throws Exception
private List<String> getHelpLines(User user) throws Exception
{
List<String> retval = new ArrayList<String>();
File file = new File(parent.getDataFolder(), "help.txt");
File file = new File(ess.getDataFolder(), "help.txt");
if (file.exists())
{
BufferedReader rx = new BufferedReader(new FileReader(file));
@ -71,7 +71,7 @@ public class Commandhelp extends EssentialsCommand
}
boolean reported = false;
for (Plugin p : parent.getServer().getPluginManager().getPlugins())
for (Plugin p : ess.getServer().getPluginManager().getPlugins())
{
try
{
@ -82,7 +82,7 @@ public class Commandhelp extends EssentialsCommand
if (p.getDescription().getName().toLowerCase().contains("essentials"))
{
String node = "essentials." + k;
if (!Essentials.getSettings().isCommandDisabled(k) && user.isAuthorized(node))
if (!ess.getSettings().isCommandDisabled(k) && user.isAuthorized(node))
{
HashMap<String, String> v = cmds.get(k);
retval.add("§c" + k + "§7: " + v.get("description"));
@ -90,7 +90,7 @@ public class Commandhelp extends EssentialsCommand
}
else
{
if (Essentials.getSettings().showNonEssCommandsInHelp())
if (ess.getSettings().showNonEssCommandsInHelp())
{
HashMap<String, String> v = cmds.get(k);
if (v.containsKey("permission") && v.get("permission") != null && !(v.get("permission").equals("")))
@ -111,7 +111,6 @@ public class Commandhelp extends EssentialsCommand
}
catch (NullPointerException ex)
{
continue;
}
catch (Exception ex)

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
@ -14,19 +13,21 @@ public class Commandhelpop extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cTo request help from an op, type §f/" + commandLabel+ "§c, followed by your question.");
return;
throw new NotEnoughArgumentsException();
}
user.charge(this);
charge(user);
for (Player p : server.getOnlinePlayers())
{
User u = User.get(p);
if (!u.isOp() && !u.isAuthorized("essentials.helpop.receive")) continue;
User u = ess.getUser(p);
if (!u.isAuthorized("essentials.helpop.receive"))
{
continue;
}
u.sendMessage("§c[HelpOp]§f §7" + user.getDisplayName() + ":§f " + getFinalArg(args, 0));
}
}

View File

@ -1,9 +1,9 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commandhome extends EssentialsCommand
{
public Commandhome()
@ -12,15 +12,15 @@ public class Commandhome extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.canAfford(this);
user.teleportCooldown();
if(args.length > 0 && user.isAuthorized("essentials.home.others"))
{
user.teleportToHome(this.getName(), args[0]);
User u = getPlayer(server, args, 0);
user.getTeleport().home(u, this.getName());
return;
}
user.teleportToHome(this.getName());
user.getTeleport().home(this.getName());
}
}

View File

@ -1,6 +1,5 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
@ -11,38 +10,45 @@ import java.util.Map;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
public class Commandinfo extends EssentialsCommand {
public Commandinfo() {
public class Commandinfo extends EssentialsCommand
{
public Commandinfo()
{
super("info");
}
@Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception {
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
String pageStr = args.length > 0 ? args[0].trim() : null;
List<String> lines = new ArrayList<String>();
List<String> chapters = new ArrayList<String>();
Map<String, Integer> bookmarks = new HashMap<String, Integer>();
File file = new File(parent.getDataFolder(), "info.txt");
File file = new File(ess.getDataFolder(), "info.txt");
if (file.exists())
{
BufferedReader rx = new BufferedReader(new FileReader(file));
int i = 0;
for (String l = null; rx.ready() && (l = rx.readLine()) != null; i++)
{
if (l.startsWith("#")) {
if (l.startsWith("#"))
{
bookmarks.put(l.substring(1).toLowerCase(), i);
chapters.add(l.substring(1));
}
lines.add(l.replace('&', '§'));
}
} else {
}
else
{
sender.sendMessage("File info.txt does not exists.");
return;
}
if (bookmarks.isEmpty()) {
if (bookmarks.isEmpty())
{
int page = 1;
try
{
@ -56,6 +62,7 @@ public class Commandinfo extends EssentialsCommand {
int start = (page - 1) * 9;
int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0);
charge(sender);
sender.sendMessage("Page §c" + page + "§f of §c" + pages + "§f:");
for (int i = start; i < lines.size() && i < start + 9; i++)
{
@ -64,13 +71,17 @@ public class Commandinfo extends EssentialsCommand {
return;
}
if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+")) {
if (lines.get(0).startsWith("#")) {
if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+"))
{
if (lines.get(0).startsWith("#"))
{
sender.sendMessage("Select chapter:");
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String string : chapters) {
if (!first) {
for (String string : chapters)
{
if (!first)
{
sb.append(", ");
}
first = false;
@ -78,7 +89,9 @@ public class Commandinfo extends EssentialsCommand {
}
sender.sendMessage(sb.toString());
return;
} else {
}
else
{
int page = 1;
try
{
@ -94,12 +107,14 @@ public class Commandinfo extends EssentialsCommand {
for (end = 0; end < lines.size(); end++)
{
String line = lines.get(end);
if (line.startsWith("#")) {
if (line.startsWith("#"))
{
break;
}
}
int pages = end / 9 + (end % 9 > 0 ? 1 : 0);
charge(sender);
sender.sendMessage("Page §c" + page + "§f of §c" + pages + "§f:");
for (int i = start; i < end && i < start + 9; i++)
{
@ -110,7 +125,8 @@ public class Commandinfo extends EssentialsCommand {
}
int chapterpage = 0;
if (args.length >= 2) {
if (args.length >= 2)
{
try
{
chapterpage = Integer.parseInt(args[1]) - 1;
@ -121,7 +137,8 @@ public class Commandinfo extends EssentialsCommand {
}
}
if (!bookmarks.containsKey(pageStr.toLowerCase())) {
if (!bookmarks.containsKey(pageStr.toLowerCase()))
{
sender.sendMessage("Unknown chapter.");
return;
}
@ -130,7 +147,8 @@ public class Commandinfo extends EssentialsCommand {
for (chapterend = chapterstart; chapterend < lines.size(); chapterend++)
{
String line = lines.get(chapterend);
if (line.startsWith("#")) {
if (line.startsWith("#"))
{
break;
}
}
@ -138,7 +156,8 @@ public class Commandinfo extends EssentialsCommand {
int page = chapterpage + 1;
int pages = (chapterend - chapterstart) / 9 + ((chapterend - chapterstart) % 9 > 0 ? 1 : 0);
sender.sendMessage("Chapter "+ pageStr +", page §c" + page + "§f of §c" + pages + "§f:");
charge(sender);
sender.sendMessage("Chapter " + pageStr + ", page §c" + page + "§f of §c" + pages + "§f:");
for (int i = start; i < chapterend && i < start + 9; i++)
{
sender.sendMessage(lines.get(i));

View File

@ -1,38 +1,44 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server;
public class Commandinvsee extends EssentialsCommand {
public Commandinvsee() {
public class Commandinvsee extends EssentialsCommand
{
public Commandinvsee()
{
super("invsee");
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception {
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length == 0 && user.savedInventory == null) {
user.sendMessage("§cUsage: /" + commandLabel + " <user>");
if (args.length < 1 && user.getSavedInventory() == null)
{
throw new NotEnoughArgumentsException();
}
User invUser = user;
if (args.length == 1) {
if (args.length == 1)
{
invUser = getPlayer(server, args, 0);
}
if (invUser == user && user.savedInventory != null) {
invUser.getInventory().setContents(user.savedInventory);
user.savedInventory = null;
if (invUser == user && user.getSavedInventory() != null)
{
invUser.getInventory().setContents(user.getSavedInventory());
user.setSavedInventory(null);
user.sendMessage("Your inventory has been restored.");
return;
}
user.charge(this);
if (user.savedInventory == null) {
user.savedInventory = user.getInventory().getContents();
charge(user);
if (user.getSavedInventory() == null)
{
user.setSavedInventory(user.getInventory().getContents());
}
user.getInventory().setContents(invUser.getInventory().getContents());
user.sendMessage("You see the inventory of "+invUser.getDisplayName()+".");
user.sendMessage("You see the inventory of " + invUser.getDisplayName() + ".");
user.sendMessage("Use /invsee to restore your inventory.");
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.ItemDb;
import com.earth2me.essentials.User;
import org.bukkit.ChatColor;
@ -17,12 +16,11 @@ public class Commanditem extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /" + commandLabel + " [item] <amount>");
return;
throw new NotEnoughArgumentsException();
}
String[] itemArgs = args[0].split("[^a-zA-Z0-9]");
ItemStack stack = ItemDb.get(itemArgs[0]);
@ -46,7 +44,7 @@ public class Commanditem extends EssentialsCommand
}
String itemName = stack.getType().name().toLowerCase().replace('_', ' ');
user.charge(this);
charge(user);
user.sendMessage("§7Giving " + stack.getAmount() + " of " + itemName + " to " + user.getDisplayName() + ".");
user.getInventory().addItem(stack);
}

View File

@ -1,18 +1,20 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
public class Commandjails extends EssentialsCommand {
public Commandjails() {
public class Commandjails extends EssentialsCommand
{
public Commandjails()
{
super("jails");
}
@Override
protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception {
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
StringBuilder jailList = new StringBuilder();
for (String j : Essentials.getJail().getJails())
{
@ -21,17 +23,4 @@ public class Commandjails extends EssentialsCommand {
}
sender.sendMessage("§7" + jailList);
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception {
StringBuilder jailList = new StringBuilder();
for (String j : Essentials.getJail().getJails())
{
jailList.append(j);
jailList.append(' ');
}
user.sendMessage("§7" + jailList);
}
}

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.TargetBlock;
import com.earth2me.essentials.User;
@ -15,16 +14,7 @@ public class Commandjump extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[]
{
getName(), "j"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
Location loc;
Location cloc = user.getLocation();
@ -45,6 +35,6 @@ public class Commandjump extends EssentialsCommand
}
user.canAfford(this);
user.teleportTo(loc, this.getName());
user.getTeleport().teleport(loc, this.getName());
}
}

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.ChatColor;
@ -15,18 +14,17 @@ public class Commandkick extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [player] <reason>");
return;
throw new NotEnoughArgumentsException();
}
User p;
User u;
try
{
p = User.get(server.matchPlayer(args[0]).get(0));
u = ess.getUser(server.matchPlayer(args[0]).get(0));
}
catch (Throwable ex)
{
@ -35,7 +33,6 @@ public class Commandkick extends EssentialsCommand
}
charge(sender);
p.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Kicked from server");
u.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Kicked from server");
}
}

View File

@ -3,8 +3,7 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commandkickall extends EssentialsCommand
{
@ -14,31 +13,20 @@ public class Commandkickall extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
charge(sender);
for (Player p : server.getOnlinePlayers())
{
if (server.getOnlinePlayers().length == 1 && p.getName().equalsIgnoreCase(user.getName()))
if (sender instanceof Player && p.getName().equalsIgnoreCase(((Player)sender).getName()))
{
user.sendMessage("§7Only you online...");
return;
continue;
}
else
{
if (!p.getName().equalsIgnoreCase(user.getName()))
{
p.kickPlayer(args.length < 1 ? getFinalArg(args, 0) : "Kicked from server");
}
p.kickPlayer(args.length < 1 ? getFinalArg(args, 0) : "Kicked from server");
}
}
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
for (Player p : server.getOnlinePlayers())
{
p.kickPlayer(args.length < 1 ? getFinalArg(args, 0) : "Kicked from server");
}
}
}

View File

@ -2,9 +2,7 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
public class Commandkill extends EssentialsCommand
@ -15,15 +13,14 @@ public class Commandkill extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("§cUsage: /kill [player]");
return;
throw new NotEnoughArgumentsException();
}
User.charge(sender, this);
charge(sender);
for (Player p : server.matchPlayer(args[0]))
{
p.setHealth(0);

View File

@ -7,6 +7,8 @@ import java.util.Map;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.util.GregorianCalendar;
import org.bukkit.inventory.ItemStack;
@ -20,13 +22,14 @@ public class Commandkit extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
@SuppressWarnings("unchecked")
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
try
{
Map<String, Object> kits = (Map<String, Object>)parent.getConfiguration().getProperty("kits");
Map<String, Object> kits = (Map<String, Object>)ess.getConfiguration().getProperty("kits");
StringBuilder list = new StringBuilder();
for (String k : kits.keySet())
{
@ -54,7 +57,7 @@ public class Commandkit extends EssentialsCommand
try
{
String kitName = args[0].toLowerCase();
Object kit = Essentials.getSettings().getKit(kitName);
Object kit = ess.getSettings().getKit(kitName);
List<String> items;
if (!user.isAuthorized("essentials.kit." + kitName))
@ -69,8 +72,13 @@ public class Commandkit extends EssentialsCommand
//System.out.println("Kit is timed");
Map<String, Object> els = (Map<String, Object>)kit;
items = (List<String>)els.get("items");
long delay = els.containsKey("delay") ? ((Number)els.get("delay")).longValue() * 1000L : 0L;
long time = Calendar.getInstance().getTimeInMillis();
double delay = els.containsKey("delay") ? ((Number)els.get("delay")).doubleValue() : 0L;
Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int)delay);
c.add(Calendar.MILLISECOND, (int)((delay*1000.0)%1000.0));
long time = c.getTimeInMillis();
Calendar now = new GregorianCalendar();
Map<String, Long> kitTimes;
if (!kitPlayers.containsKey(user))
@ -86,15 +94,13 @@ public class Commandkit extends EssentialsCommand
{
kitTimes.put(kitName, time);
}
else if (kitTimes.get(kitName) + delay <= time)
else if (kitTimes.get(kitName) < now.getTimeInMillis())
{
kitTimes.put(kitName, time);
}
else
{
long left = kitTimes.get(kitName) + delay - time;
user.sendMessage("§cYou can't use that kit again for another " + Essentials.FormatTime(left) + ".");
user.sendMessage("§cYou can't use that kit again for another " + Util.formatDateDiff(kitTimes.get(kitName)) + ".");
return;
}
}
@ -104,9 +110,12 @@ public class Commandkit extends EssentialsCommand
items = (List<String>)kit;
}
try {
try
{
user.canAfford("kit-" + kitName);
} catch (Exception ex) {
}
catch (Exception ex)
{
user.sendMessage(ex.getMessage());
return;
}
@ -118,24 +127,24 @@ public class Commandkit extends EssentialsCommand
int id = Integer.parseInt(parts[0]);
int amount = parts.length > 1 ? Integer.parseInt(parts[parts.length > 2 ? 2 : 1]) : 1;
short data = parts.length > 2 ? Short.parseShort(parts[1]) : 0;
if(user.getInventory().firstEmpty() != -1)
{
user.getInventory().addItem(new ItemStack(id, amount, data));
}
else
HashMap<Integer,ItemStack> overfilled = user.getInventory().addItem(new ItemStack(id, amount, data));
for (ItemStack itemStack : overfilled.values())
{
user.getWorld().dropItemNaturally(user.getLocation(), itemStack);
spew = true;
user.getWorld().dropItemNaturally(user.getLocation(), new ItemStack(id, amount, data));
}
}
if(spew)
if (spew)
{
user.sendMessage("§7Your inventory was full, placing kit on the floor");
}
try {
try
{
user.charge(this);
user.charge("kit-" + kitName);
} catch (Exception ex) {
}
catch (Exception ex)
{
user.sendMessage(ex.getMessage());
}
user.sendMessage("§7Giving kit " + args[0].toLowerCase() + ".");

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.TargetBlock;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.World;
@ -16,7 +15,7 @@ public class Commandlightning extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
World world = user.getWorld();
@ -26,7 +25,7 @@ public class Commandlightning extends EssentialsCommand
return;
}
if(server.matchPlayer(args[0]).isEmpty())
if (server.matchPlayer(args[0]).isEmpty())
{
user.sendMessage("§cPlayer not found");
return;
@ -37,7 +36,7 @@ public class Commandlightning extends EssentialsCommand
user.sendMessage("§7Smiting " + p.getDisplayName());
world.strikeLightning(p.getLocation());
p.setHealth(p.getHealth() < 5 ? 0 : p.getHealth() -5);
if(Essentials.getSettings().warnOnSmite())
if(ess.getSettings().warnOnSmite())
{
p.sendMessage("§7You have just been smited");
}

View File

@ -22,23 +22,25 @@ public class Commandlist extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
User.charge(sender, this);
charge(sender);
StringBuilder online = new StringBuilder();
online.append(ChatColor.BLUE).append("There are ").append(ChatColor.RED).append(server.getOnlinePlayers().length);
online.append(ChatColor.BLUE).append(" out of a maximum ").append(ChatColor.RED).append(server.getMaxPlayers());
online.append(ChatColor.BLUE).append(" players online.");
sender.sendMessage(online.toString());
if (Essentials.getSettings().getSortListByGroups()) {
if (ess.getSettings().getSortListByGroups())
{
Map<String, List<User>> sort = new HashMap<String, List<User>>();
for (Player p : server.getOnlinePlayers())
{
User u = User.get(p);
User u = ess.getUser(p);
String group = u.getGroup();
List<User> list = sort.get(group);
if (list == null) {
if (list == null)
{
list = new ArrayList<User>();
sort.put(group, list);
}
@ -46,43 +48,56 @@ public class Commandlist extends EssentialsCommand
}
String[] groups = sort.keySet().toArray(new String[0]);
Arrays.sort(groups, String.CASE_INSENSITIVE_ORDER);
for (String group : groups) {
for (String group : groups)
{
StringBuilder groupString = new StringBuilder();
groupString.append(group).append(": ");
List<User> users = sort.get(group);
Collections.sort(users);
boolean first = true;
for (User user : users) {
if (!first) {
for (User user : users)
{
if (!first)
{
groupString.append(", ");
} else {
}
else
{
first = false;
}
if (parent.away.contains(user)) {
if (user.isAfk())
{
groupString.append("§7[AFK]§f");
}
groupString.append(user.getDisplayName());
}
sender.sendMessage(groupString.toString());
}
} else {
}
else
{
List<User> users = new ArrayList<User>();
for (Player p : server.getOnlinePlayers())
{
users.add(User.get(p));
users.add(ess.getUser(p));
}
Collections.sort(users);
StringBuilder onlineUsers = new StringBuilder();
onlineUsers.append("Connected players: ");
boolean first = true;
for (User user : users) {
if (!first) {
for (User user : users)
{
if (!first)
{
onlineUsers.append(", ");
} else {
}
else
{
first = false;
}
if (parent.away.contains(user)) {
if (user.isAfk())
{
onlineUsers.append("§7[AFK]§f");
}
onlineUsers.append(user.getDisplayName());

View File

@ -2,8 +2,9 @@ package com.earth2me.essentials.commands;
import java.util.List;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class Commandmail extends EssentialsCommand
@ -14,21 +15,24 @@ public class Commandmail extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length >= 1 && "read".equalsIgnoreCase(args[0]))
{
List<String> mail = Essentials.readMail(user);
List<String> mail = user.getMails();
if (mail.isEmpty())
{
user.sendMessage("§cYou do not have any mail!");
return;
}
for (String s : mail) user.sendMessage(s);
for (String s : mail)
{
user.sendMessage(s);
}
user.sendMessage("§cTo mark your mail as read, type §c/mail clear");
return;
}
if(args.length >= 3 && "send".equalsIgnoreCase(args[0]))
if (args.length >= 3 && "send".equalsIgnoreCase(args[0]))
{
if (!user.isAuthorized("essentials.mail.send"))
{
@ -36,14 +40,29 @@ public class Commandmail extends EssentialsCommand
return;
}
user.charge(this);
Essentials.sendMail(user, args[1], getFinalArg(args, 2));
Player player = server.getPlayer(args[1]);
User u;
if (player != null)
{
u = ess.getUser(player);
}
else
{
u = ess.getOfflineUser(args[1]);
}
if (u == null)
{
user.sendMessage("§cPlayer " + args[1] + " never was on this server.");
return;
}
charge(user);
u.addMail(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 2));
user.sendMessage("§7Mail sent!");
return;
}
if (args.length >= 1 && "clear".equalsIgnoreCase(args[0]))
{
Essentials.clearMail(user);
user.setMails(null);
user.sendMessage("§7Mail cleared!");
return;
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,23 +12,17 @@ public class Commandme extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[] { getName(), "describe", "action" };
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (user.isMuted())
{ user.sendMessage("§7Your voice has been silenced");
return;
{
user.sendMessage("§7Your voice has been silenced");
return;
}
if (args.length < 1)
{
user.sendMessage("§cUsage: /me [description]");
return;
throw new NotEnoughArgumentsException();
}
StringBuilder message = new StringBuilder();
for (int i = 0; i < args.length; i++)
@ -37,7 +30,7 @@ public class Commandme extends EssentialsCommand
message.append(args[i]);
message.append(' ');
}
user.charge(this);
charge(user);
server.broadcastMessage("* " + user.getDisplayName() + " " + message);
}
}

View File

@ -1,8 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
@ -14,10 +12,10 @@ public class Commandmotd extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
User.charge(sender, this);
for (String m : parent.getMotd(sender, "§cThere is no message of the day."))
charge(sender);
for (String m : ess.getMotd(sender, "§cThere is no message of the day."))
{
sender.sendMessage(m);
}

View File

@ -2,13 +2,12 @@ package com.earth2me.essentials.commands;
import java.util.List;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Console;
import com.earth2me.essentials.IReplyTo;
import org.bukkit.command.CommandSender;
public class Commandmsg extends EssentialsCommand
{
public Commandmsg()
@ -17,24 +16,17 @@ public class Commandmsg extends EssentialsCommand
}
@Override
public String[] getTriggers()
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
return new String[] { getName(), "m", "tell", "whisper" };
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2 || args[0].trim().length() == 0 || args[1].trim().length() == 0)
if (args.length < 2 || args[0].trim().isEmpty() || args[1].trim().isEmpty())
{
sender.sendMessage("§cUsage: /" + commandLabel + " [player] [message]");
return;
throw new NotEnoughArgumentsException();
}
String message = getFinalArg(args, 1);
IReplyTo replyTo = sender instanceof Player?User.get((Player)sender):Console.getConsoleReplyTo();
String senderName = sender instanceof Player?((Player)sender).getDisplayName():Console.NAME;
IReplyTo replyTo = sender instanceof Player ? ess.getUser((Player)sender) : Console.getConsoleReplyTo();
String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
if (args[0].equalsIgnoreCase(Console.NAME))
{
@ -59,8 +51,8 @@ public class Commandmsg extends EssentialsCommand
{
sender.sendMessage("[Me -> " + p.getDisplayName() + "§f] " + message);
p.sendMessage("[" + senderName + " -> Me§f] " + message);
replyTo.setReplyTo(User.get(p));
User.get(p).setReplyTo(sender);
replyTo.setReplyTo(ess.getUser(p));
ess.getUser(p).setReplyTo(sender);
}
}
}

View File

@ -2,8 +2,8 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandmute extends EssentialsCommand
@ -14,51 +14,21 @@ public class Commandmute extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§7Usage: /" + commandLabel + " [player] <reason>");
return;
throw new NotEnoughArgumentsException();
}
String[] sects2 = args[0].split(" +");
User p;
try
{
p = User.get(server.matchPlayer(args[0]).get(0));
User p = getPlayer(server, args, 0);
long muteTimestamp = 0;
if (args.length > 1) {
String time = getFinalArg(args, 1);
muteTimestamp = Util.parseDateDiff(time, true);
}
catch (Exception ex)
{
user.sendMessage("§cThat player does not exist!");
return;
}
user.sendMessage("§7Player " + p.getName() + " " + (p.toggleMuted() ? "muted." : "unmuted."));
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("Usage: /" + commandLabel + " [player] <reason>");
return;
}
String[] sects2 = args[0].split(" +");
User p;
try
{
p = User.get(server.matchPlayer(args[0]).get(0));
}
catch (Exception ex)
{
sender.sendMessage("§cThat player does not exist!");
return;
}
sender.sendMessage("Player " + p.getName() + " " + (p.toggleMuted() ? "muted." : "unmuted."));
p.setMuteTimeout(muteTimestamp);
charge(sender);
sender.sendMessage("Player " + p.getDisplayName() + " " + (p.toggleMuted() ? "muted" : "unmuted") + (muteTimestamp > 0 ? " for" + Util.formatDateDiff(muteTimestamp) : "") + ".");
}
}

View File

@ -1,6 +1,5 @@
package com.earth2me.essentials.commands;
import java.util.List;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
@ -16,12 +15,11 @@ public class Commandnick extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /" + commandLabel + " <target> [nickname]");
return;
throw new NotEnoughArgumentsException();
}
if (args.length > 1)
@ -32,96 +30,74 @@ public class Commandnick extends EssentialsCommand
return;
}
List<Player> matches = server.matchPlayer(args[0]);
if (matches.isEmpty())
setOthersNickname(server, user, args);
return;
}
String nick = args[0];
if ("off".equalsIgnoreCase(nick) || user.getName().equalsIgnoreCase(nick))
{
user.setDisplayName(user.getName());
user.setNickname(null);
user.sendMessage("§7You no longer have a nickname.");
return;
}
if (nick.matches("[^a-zA-Z_0-9]"))
{
user.sendMessage("§cNicknames must be alphanumeric.");
return;
}
for (Player p : server.getOnlinePlayers())
{
if (user == p)
{
user.sendMessage("§cThat player does not exist.");
continue;
}
String dn = p.getDisplayName().toLowerCase();
String n = p.getName().toLowerCase();
String nk = nick.toLowerCase();
if (nk.equals(dn) || nk.equals(n))
{
user.sendMessage("§cThat name is already in use.");
return;
}
User target = User.get(matches.get(0));
String nick = args[1];
if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick))
{
target.setDisplayName(target.getName());
parent.saveNickname(target, target.getName());
target.sendMessage("§7You no longer have a nickname.");
}
else
{
user.charge(this);
target.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick);
parent.saveNickname(target, nick);
target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7.");
}
user.sendMessage("§7Nickname changed.");
}
else
{
String nick = args[0];
if ("off".equalsIgnoreCase(nick) || user.getName().equalsIgnoreCase(nick))
{
user.setDisplayName(user.getName());
parent.saveNickname(user, user.getName());
user.sendMessage("§7You no longer have a nickname.");
}
else
{
if (nick.matches("[^a-zA-Z_0-9]"))
{
user.sendMessage("§cNicknames must be alphanumeric.");
return;
}
for (Player p : server.getOnlinePlayers())
{
if (user == p) continue;
String dn = p.getDisplayName().toLowerCase();
String n = p.getName().toLowerCase();
String nk = nick.toLowerCase();
if (nk.equals(dn) || nk.equals(n))
{
user.sendMessage("§cThat name is already in use.");
return;
}
}
user.charge(this);
user.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick);
parent.saveNickname(user, nick);
user.sendMessage("§7Your nickname is now §c" + user.getDisplayName() + "§7.");
}
}
user.charge(this);
user.setDisplayName(ess.getConfiguration().getString("nickname-prefix", "~") + nick);
user.setNickname(nick);
user.sendMessage("§7Your nickname is now §c" + user.getDisplayName() + "§7.");
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
sender.sendMessage("Usage: /" + commandLabel + " [target] [nickname]");
return;
throw new NotEnoughArgumentsException();
}
List<Player> matches = server.matchPlayer(args[0]);
if (matches.isEmpty())
{
sender.sendMessage("That player does not exist.");
return;
}
setOthersNickname(server, sender, args);
User target = User.get(matches.get(0));
}
private void setOthersNickname(Server server, CommandSender sender, String[] args) throws Exception
{
User target = getPlayer(server, args, 0);
String nick = args[1];
if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick))
{
target.setDisplayName(target.getName());
parent.saveNickname(target, target.getName());
target.setNickname(null);
target.sendMessage("§7You no longer have a nickname.");
}
else
{
target.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick);
parent.saveNickname(target, nick);
target.setDisplayName(ess.getSettings().getNicknamePrefix() + nick);
target.setNickname(nick);
target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7.");
}
sender.sendMessage("Nickname changed.");

View File

@ -1,11 +1,8 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand;
public class Commandpay extends EssentialsCommand
@ -16,27 +13,19 @@ public class Commandpay extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
int amount;
try
{
amount = Integer.parseInt(args[1].replaceAll("[^0-9]", ""));
}
catch (Exception ex)
{
user.sendMessage("§cUsage: /" + commandLabel + " [player] [money]");
return;
}
double amount = Double.parseDouble(args[1].replaceAll("[^0-9\\.]", ""));
for (Player p : server.matchPlayer(args[0]))
{
User u = User.get(p);
User u = ess.getUser(p);
user.payUser(u, amount);
}
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,13 +12,7 @@ public class Commandping extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[] { getName(), "pong" };
}
@Override
public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception
public void run(Server server, User player, String commandLabel, String[] args) throws Exception
{
player.sendMessage("Pong!");
}

View File

@ -2,8 +2,6 @@ package com.earth2me.essentials.commands;
import java.io.File;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
@ -19,7 +17,7 @@ public class Commandplugin extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
this.server = server;
@ -69,7 +67,7 @@ public class Commandplugin extends EssentialsCommand
return;
case LIST:
User.charge(sender, this);
charge(sender);
listPlugins(sender);
return;
}
@ -115,7 +113,9 @@ public class Commandplugin extends EssentialsCommand
{
final PluginManager pm = server.getPluginManager();
final Plugin plugin = pm.getPlugin(name);
if (!plugin.isEnabled()) new Thread(new Runnable()
if (!plugin.isEnabled())
{
new Thread(new Runnable()
{
public void run()
{
@ -125,6 +125,7 @@ public class Commandplugin extends EssentialsCommand
}
}
}).start();
}
sender.sendMessage("§7Plugin enabled.");
return true;
}
@ -141,7 +142,9 @@ public class Commandplugin extends EssentialsCommand
{
final PluginManager pm = server.getPluginManager();
final Plugin plugin = pm.getPlugin(name);
if (plugin.isEnabled()) new Thread(new Runnable()
if (plugin.isEnabled())
{
new Thread(new Runnable()
{
public void run()
{
@ -151,6 +154,7 @@ public class Commandplugin extends EssentialsCommand
}
}
}).start();
}
sender.sendMessage("§7Plugin disabled.");
return true;
}

View File

@ -1,32 +1,37 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
public class Commandpowertool extends EssentialsCommand {
public Commandpowertool() {
public class Commandpowertool extends EssentialsCommand
{
public Commandpowertool()
{
super("powertool");
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception {
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
ItemStack is = user.getItemInHand();
if (is == null || is.getType() == Material.AIR) {
if (is == null || is.getType() == Material.AIR)
{
user.sendMessage("Command can't be attached to air.");
}
String command = getFinalArg(args, 0);
if (command != null && !command.isEmpty()) {
user.sendMessage("Command assigned to "+is.getType().toString().toLowerCase().replaceAll("_", " "));
} else {
user.sendMessage("Command removed from "+is.getType().toString().toLowerCase().replaceAll("_", " "));
if (command != null && !command.isEmpty())
{
user.sendMessage("Command assigned to " + is.getType().toString().toLowerCase().replaceAll("_", " "));
}
else
{
user.sendMessage("Command removed from " + is.getType().toString().toLowerCase().replaceAll("_", " "));
}
charge(user);
user.setPowertool(is, command);
}
}

View File

@ -1,6 +1,5 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.*;
import com.earth2me.essentials.Console;
import com.earth2me.essentials.IReplyTo;
import org.bukkit.*;
@ -16,19 +15,18 @@ public class Commandr extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("§cUsage: /" + commandLabel + " [message]");
return;
throw new NotEnoughArgumentsException();
}
String message = getFinalArg(args, 0);
IReplyTo replyTo = sender instanceof Player?User.get((Player)sender):Console.getConsoleReplyTo();
String senderName = sender instanceof Player?((Player)sender).getDisplayName():Console.NAME;
IReplyTo replyTo = sender instanceof Player ? ess.getUser((Player)sender) : Console.getConsoleReplyTo();
String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
CommandSender target = replyTo.getReplyTo();
String targetName = target instanceof Player?((Player)target).getDisplayName():Console.NAME;
String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME;
if (target == null)
{
@ -37,12 +35,16 @@ public class Commandr extends EssentialsCommand
charge(sender);
sender.sendMessage("[Me -> " + targetName + "] " + message);
target.sendMessage("[" + senderName + " -> Me] " + message);
target.sendMessage("[" + senderName + " -> Me] " + message);
replyTo.setReplyTo(target);
if (target != sender) {
if (target instanceof Player) {
User.get((Player)target).setReplyTo(sender);
} else {
if (target != sender)
{
if (target instanceof Player)
{
ess.getUser((Player)target).setReplyTo(sender);
}
else
{
Console.getConsoleReplyTo().setReplyTo(sender);
}
}

View File

@ -14,26 +14,24 @@ public class Commandrealname extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[] { getName(), "realnick" };
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /whois [nickname]");
return;
throw new NotEnoughArgumentsException();
}
String whois = args[0].toLowerCase();
user.charge(this);
for (Player p : server.getOnlinePlayers())
{
User u = User.get(p);
User u = ess.getUser(p);
String dn = u.getDisplayName().toLowerCase();
if (!whois.equals(dn) && !whois.equals(parent.getSettings().getNicknamePrefix() + dn) && !whois.equals(u.getName().toLowerCase())) continue;
if (!whois.equals(dn)
&& !whois.equals(ess.getSettings().getNicknamePrefix() + dn)
&& !whois.equals(u.getName().toLowerCase()))
{
continue;
}
user.sendMessage(u.getDisplayName() + " is " + u.getName());
}
}

View File

@ -2,36 +2,20 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
public class Commandreloadall extends EssentialsCommand
{
public Commandreloadall()
{
super("reloadall");
}
@Override
public String[] getTriggers()
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
return new String[] { getName(), "rel", "pr" };
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
charge(sender);
server.reload();
user.sendMessage("§7Reloaded all plugins.");
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
server.reload();
sender.sendMessage("Reloaded all plugins.");
sender.sendMessage("§7Reloaded all plugins.");
}
}

View File

@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import com.earth2me.essentials.*;
public class Commandrules extends EssentialsCommand
@ -12,10 +12,10 @@ public class Commandrules extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
for (String m : parent.getLines(user, "rules", "§cThere are no rules specified yet."))
charge(user);
for (String m : ess.getLines(user, "rules", "§cThere are no rules specified yet."))
{
user.sendMessage(m);
}

View File

@ -0,0 +1,38 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
public class Commandseen extends EssentialsCommand
{
public Commandseen()
{
super("seen");
}
@Override
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
try
{
User u = getPlayer(server, args, 0);
sender.sendMessage("Player " + u.getDisplayName() + " is online since" + Util.formatDateDiff(u.getLastLogin()));
}
catch (NoSuchFieldException e)
{
User u = ess.getOfflineUser(args[0]);
if (u == null)
{
return;
}
sender.sendMessage("Player " + u.getDisplayName() + " is offline since" + Util.formatDateDiff(u.getLastLogout()));
}
}
}

View File

@ -17,60 +17,73 @@ public class Commandsell extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1) {
user.sendMessage("§cUsage: /sell [itemname|id|hand] [-][amount]");
return;
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
ItemStack is;
if (args[0].equalsIgnoreCase("hand")) {
if (args[0].equalsIgnoreCase("hand"))
{
is = user.getItemInHand();
} else {
}
else
{
is = ItemDb.get(args[0]);
}
if(is.getType() == Material.AIR) {
if (is.getType() == Material.AIR)
{
throw new Exception("You really tried to sell Air? Put an item in your hand.");
}
int id = is.getTypeId();
int amount = 0;
if (args.length > 1) {
if (args.length > 1)
{
amount = Integer.parseInt(args[1].replaceAll("[^0-9]", ""));
if (args[1].startsWith("-")) {
if (args[1].startsWith("-"))
{
amount = -amount;
}
}
double worth = Essentials.getWorth().getPrice(is);
boolean stack = args.length > 1 && args[1].endsWith("s");
boolean requireStack = parent.getConfiguration().getBoolean("trade-in-stacks-" + id, false);
boolean requireStack = ess.getConfiguration().getBoolean("trade-in-stacks-" + id, false);
if (Double.isNaN(worth)) {
if (Double.isNaN(worth))
{
throw new Exception("That item cannot be sold to the server.");
}
if (requireStack && !stack) {
if (requireStack && !stack)
{
throw new Exception("Item must be traded in stacks. A quantity of 2s would be two stacks, etc.");
}
int max = 0;
for (ItemStack s : user.getInventory().getContents())
{
if (s == null) {
if (s == null)
{
continue;
}
if (s.getTypeId() != is.getTypeId()) {
if (s.getTypeId() != is.getTypeId())
{
continue;
}
if (s.getDurability() != is.getDurability()) {
if (s.getDurability() != is.getDurability())
{
continue;
}
max += s.getAmount();
}
if (stack) {
if (stack)
{
amount *= 64;
}
if (amount < 1) {
if (amount < 1)
{
amount += max;
}
@ -87,7 +100,7 @@ public class Commandsell extends EssentialsCommand
return;
}
user.charge(this);
charge(user);
InventoryWorkaround.removeItem(user.getInventory(), true, new ItemStack(is.getType(), amount, is.getDurability()));
user.updateInventory();
user.giveMoney(worth * amount);

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,10 +12,10 @@ public class Commandsethome extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.setHome();
user.charge(this);
user.setHome(args.length > 0 && args[0].equalsIgnoreCase("default"));
charge(user);
user.sendMessage("§7Home set.");
}
}

View File

@ -13,14 +13,13 @@ public class Commandsetjail extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /" + commandLabel + " [jailname]");
return;
throw new NotEnoughArgumentsException();
}
user.charge(this);
charge(user);
Essentials.getJail().setJail(user.getLocation(), args[0]);
user.sendMessage("§7Jail " + args[0] + " has been set");

View File

@ -14,15 +14,14 @@ public class Commandsetwarp extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /setwarp [warp name]");
return;
throw new NotEnoughArgumentsException();
}
user.charge(this);
charge(user);
Location loc = user.getLocation();
Essentials.getWarps().setWarp(args[0], loc);
user.sendMessage("§7Warp set.");

View File

@ -15,16 +15,16 @@ public class Commandsetworth extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if(args.length < 2)
if (args.length < 2)
{
user.sendMessage("§cUsage: /" + commandLabel + " [itemname|id] [price]");
return;
throw new NotEnoughArgumentsException();
}
ItemStack stack = ItemDb.get(args[0]);
charge(user);
Essentials.getWorth().setPrice(stack, Double.parseDouble(args[1]));
user.charge(this);
user.sendMessage("§7Worth value set");
}
}

View File

@ -1,8 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.Block;
@ -18,25 +16,27 @@ public class Commandspawner extends EssentialsCommand
}
@Override
protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [mob]");
return;
throw new NotEnoughArgumentsException();
}
Block target = user.getTarget().getTargetBlock();
if (target.getType() != Material.MOB_SPAWNER)
{
throw new Exception("Target block must be a mob spawner.");
}
charge(user);
try
{
user.charge(this);
((CreatureSpawner)target).setCreatureType(CreatureType.fromName(args[0]));
}
catch (Throwable ex)
{
throw new Exception("Error while changing mob spawner.");
}
}
}

View File

@ -29,22 +29,12 @@ public class Commandspawnmob extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[]
{
getName(), "mob"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /spawnmob [mob]<:data><,mount<:data>> <quantity>");
user.sendMessage("§7Mobs: Zombie PigZombie Skeleton Slime Chicken Pig Monster Spider Creeper Ghast Squid Giant Cow Sheep Wolf");
return;
throw new NotEnoughArgumentsException();
//TODO: user.sendMessage("§7Mobs: Zombie PigZombie Skeleton Slime Chicken Pig Monster Spider Creeper Ghast Squid Giant Cow Sheep Wolf");
}
@ -53,16 +43,19 @@ public class Commandspawnmob extends EssentialsCommand
String mobType = parts[0];
mobType = mobType.equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(mobType);
String mobData = null;
if (parts.length == 2) {
if (parts.length == 2)
{
mobData = parts[1];
}
String mountType = null;
String mountData = null;
if (mountparts.length > 1) {
if (mountparts.length > 1)
{
parts = mountparts[1].split(":");
mountType = parts[0];
mountType = mountType.equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(mountType);
if (parts.length == 2) {
if (parts.length == 2)
{
mountData = parts[1];
}
}
@ -79,7 +72,7 @@ public class Commandspawnmob extends EssentialsCommand
user.sendMessage("Invalid mob type.");
return;
}
user.charge(this);
charge(user);
WorldServer world = ((CraftWorld)user.getWorld()).getHandle();
try
{
@ -90,11 +83,14 @@ public class Commandspawnmob extends EssentialsCommand
user.sendMessage("Unable to spawn mob.");
return;
}
int[] ignore = {8, 9};
int[] ignore =
{
8, 9
};
Location loc = (new TargetBlock(user, 300, 0.2, ignore)).getTargetBlock().getLocation();
Block block = user.getWorld().getBlockAt(loc);
while (!(block.getType() == Material.AIR || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER ))
while (!(block.getType() == Material.AIR || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER))
{
loc.setY(loc.getY() + 1);
block = user.getWorld().getBlockAt(loc);
@ -123,17 +119,19 @@ public class Commandspawnmob extends EssentialsCommand
spawnedMount.getHandle().setPassengerOf(spawnedMob.getHandle());
world.addEntity(spawnedMount.getHandle());
}
if (mobData != null) {
if (mobData != null)
{
changeMobData(mob.name, spawnedMob, mobData, user);
}
if (spawnedMount != null && mountData != null) {
if (spawnedMount != null && mountData != null)
{
changeMobData(mobMount.name, spawnedMount, mountData, user);
}
if (args.length == 2)
{
int mobCount = Integer.parseInt(args[1]);
int serverLimit = Essentials.getSettings().getSpawnMobLimit();
if(mobCount > serverLimit)
int serverLimit = ess.getSettings().getSpawnMobLimit();
if (mobCount > serverLimit)
{
mobCount = serverLimit;
user.sendMessage("Mob quantity limited to server limit");
@ -161,10 +159,12 @@ public class Commandspawnmob extends EssentialsCommand
spawnedMount.getHandle().setPassengerOf(spawnedMob.getHandle());
world.addEntity(spawnedMount.getHandle());
}
if (mobData != null) {
if (mobData != null)
{
changeMobData(mob.name, spawnedMob, mobData, user);
}
if (spawnedMount != null && mountData != null) {
if (spawnedMount != null && mountData != null)
{
changeMobData(mobMount.name, spawnedMount, mountData, user);
}
}
@ -194,8 +194,10 @@ public class Commandspawnmob extends EssentialsCommand
return s.toUpperCase().charAt(0) + s.toLowerCase().substring(1);
}
private void changeMobData(String type, CraftEntity spawned, String data, User user) throws Exception {
if ("Slime".equalsIgnoreCase(type)) {
private void changeMobData(String type, CraftEntity spawned, String data, User user) throws Exception
{
if ("Slime".equalsIgnoreCase(type))
{
try
{
((CraftSlime)spawned).setSize(Integer.parseInt(data));
@ -205,7 +207,8 @@ public class Commandspawnmob extends EssentialsCommand
throw new Exception("Malformed size.");
}
}
if ("Sheep".equalsIgnoreCase(type)) {
if ("Sheep".equalsIgnoreCase(type))
{
try
{
((CraftSheep)spawned).setColor(DyeColor.valueOf(data.toUpperCase()));
@ -215,16 +218,18 @@ public class Commandspawnmob extends EssentialsCommand
throw new Exception("Malformed color.");
}
}
if ("Wolf".equalsIgnoreCase(type) && data.equalsIgnoreCase("tamed")) {
EntityWolf wolf = ((CraftWolf) spawned).getHandle();
if ("Wolf".equalsIgnoreCase(type) && data.equalsIgnoreCase("tamed"))
{
EntityWolf wolf = ((CraftWolf)spawned).getHandle();
wolf.d(true);
wolf.a((PathEntity) null);
wolf.a((PathEntity)null);
wolf.setSitting(true);
wolf.health = 20;
wolf.a(user.getName());
wolf.world.a(wolf, (byte) 7);
wolf.world.a(wolf, (byte)7);
}
if ("Wolf".equalsIgnoreCase(type) && data.equalsIgnoreCase("angry")) {
if ("Wolf".equalsIgnoreCase(type) && data.equalsIgnoreCase("angry"))
{
((CraftWolf)spawned).setAngry(true);
}
if ("Creeper".equalsIgnoreCase(type) && data.equalsIgnoreCase("powered")) {

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,11 +12,11 @@ public class Commandsuicide extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
charge(user);
user.setHealth(0);
user.sendMessage("§cGoodbye Cruel World...");
server.broadcastMessage("§7" + user.getDisplayName() + " took their own life" );
server.broadcastMessage("§7" + user.getDisplayName() + " took their own life");
}
}

View File

@ -0,0 +1,52 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandtempban extends EssentialsCommand
{
public Commandtempban()
{
super("tempban");
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
User p = null;
try
{
p = getPlayer(server, args, 0);
}
catch (NoSuchFieldException ex)
{
p = ess.getOfflineUser(args[0]);
}
if (p == null)
{
sender.sendMessage("§cPlayer " + args[0] + " not found");
}
String time = getFinalArg(args, 1);
long banTimestamp = Util.parseDateDiff(time, true);
p = ess.getUser(server.matchPlayer(args[0]).get(0));
String banReason = "Temporary banned from server for " + Util.formatDateDiff(banTimestamp);
p.setBanReason(banReason);
p.setBanTimeout(banTimestamp);
p.kickPlayer(banReason);
((CraftServer)server).getHandle().a(p.getName());
sender.sendMessage("§cPlayer " + p.getName() + " banned");
Essentials.getStatic().loadBanList();
}
}

View File

@ -1,8 +1,6 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.World;
@ -15,13 +13,12 @@ public class Commandthunder extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /" + commandLabel + " <true/false> [duration]");
return;
throw new NotEnoughArgumentsException();
}
user.charge(this);
@ -33,13 +30,11 @@ public class Commandthunder extends EssentialsCommand
world.setThundering(setThunder ? true : false);
world.setThunderDuration(Integer.parseInt(args[1]) * 20);
user.sendMessage("§7You " + (setThunder ? "enabled" : "disabled") + " thunder in your world for " + args[1] + " seconds");
return;
}
else
{
world.setThundering(setThunder ? true : false);
user.sendMessage("§7You " + (setThunder ? "enabled" : "disabled") + " thunder in your world");
return;
}
}

View File

@ -15,49 +15,47 @@ public class Commandtime extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
World world = user.getWorld();
long time = world.getTime();
time = time - time % 24000;
if (args.length < 1)
{
user.sendMessage("§cUsage: /time [day|night]");
return;
throw new NotEnoughArgumentsException();
}
if ("day".equalsIgnoreCase(args[0]))
World world = user.getWorld();
charge(user);
setWorldTime(world, args[0]);
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
for (World world : server.getWorlds())
{
setWorldTime(world, args[0]);
}
sender.sendMessage("Time set in all worlds.");
}
private void setWorldTime(World world, String timeString) throws Exception
{
long time = world.getTime();
time = time - time % 24000;
if ("day".equalsIgnoreCase(timeString))
{
user.charge(this);
world.setTime(time + 24000);
return;
}
if ("night".equalsIgnoreCase(args[0]))
if ("night".equalsIgnoreCase(timeString))
{
user.charge(this);
world.setTime(time + 37700);
return;
}
throw new Exception("/time only supports day/night.");
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
for (World world : server.getWorlds())
{
long time = world.getTime();
time = time - time % 24000;
if (args.length < 1)
{
sender.sendMessage("Usage: /time [day|night]");
return;
}
if ("day".equalsIgnoreCase(args[0])) world.setTime(time + 24000);
else if ("night".equalsIgnoreCase(args[0])) world.setTime(time + 37700);
else throw new Exception("/time only supports day/night.");
}
sender.sendMessage("Time set in all worlds.");
}
}

View File

@ -4,6 +4,7 @@ import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandtogglejail extends EssentialsCommand
@ -14,55 +15,67 @@ public class Commandtogglejail extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1 || args.length > 2)
if (args.length < 1)
{
sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]");
return;
throw new NotEnoughArgumentsException();
}
User p;
try
{
p = User.get(server.matchPlayer(args[0]).get(0));
}
catch (Exception ex)
{
sender.sendMessage("§cThat player does not exist.");
return;
}
User p = getPlayer(server, args, 0);
if (p.isOp() || p.isAuthorized("essentials.jail.exempt"))
if (p.isAuthorized("essentials.jail.exempt"))
{
sender.sendMessage("§cYou may not jail that person");
return;
}
if (args.length == 2 && !p.isJailed()) {
User.charge(sender, this);
sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed."));
if (args.length >= 2 && !p.isJailed())
{
charge(sender);
p.setJailed(true);
p.sendMessage("§7You have been jailed");
p.currentJail = null;
p.setJail(null);
Essentials.getJail().sendToJail(p, args[1]);
p.currentJail = (args[1]);
return;
}
if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) {
sender.sendMessage("§cPerson is already in jail "+ p.currentJail);
return;
}
if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) {
if (!p.isJailed()) {
sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]");
return;
p.setJail(args[1]);
long timeDiff = 0;
if (args.length > 2)
{
String time = getFinalArg(args, 2);
timeDiff = Util.parseDateDiff(time, true);
p.setJailTimeout(timeDiff);
}
sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed."));
sender.sendMessage("§7Player " + p.getName() + " jailed" + (timeDiff > 0 ? " for" + Util.formatDateDiff(timeDiff) : "") + ".");
return;
}
if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.getJail()))
{
sender.sendMessage("§cPerson is already in jail " + p.getJail());
return;
}
if (args.length >= 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.getJail()))
{
String time = getFinalArg(args, 2);
long timeDiff = Util.parseDateDiff(time, true);
p.setJailTimeout(timeDiff);
sender.sendMessage("Jail time extend to " + Util.formatDateDiff(timeDiff));
return;
}
if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.getJail())))
{
if (!p.isJailed())
{
throw new NotEnoughArgumentsException();
}
p.setJailed(false);
p.setJailTimeout(0);
p.sendMessage("§7You have been released");
p.currentJail = "";
p.teleportBack();
p.setJail(null);
p.getTeleport().back();
sender.sendMessage("§7Player " + p.getName() + " unjailed.");
}
}
}

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -14,13 +13,13 @@ public class Commandtop extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
int topX = user.getLocation().getBlockX();
int topZ = user.getLocation().getBlockZ();
int topY = user.getWorld().getHighestBlockYAt(topX, topZ);
user.charge(this);
user.teleportTo(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), this.getName());
charge(user);
user.getTeleport().teleport(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), this.getName());
user.sendMessage("§7Teleporting to top.");
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
@ -14,48 +13,51 @@ public class Commandtp extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
switch (args.length)
{
case 0:
user.sendMessage("§cUsage: /" + commandLabel + " <target> [to-player]");
return;
throw new NotEnoughArgumentsException();
case 1:
User p = getPlayer(server, args, 0);
user.teleportCooldown();
if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled.");
if (!p.isTeleportEnabled())
{
throw new Exception(p.getDisplayName() + " has teleportation disabled.");
}
user.sendMessage("§7Teleporting...");
user.canAfford(this);
user.teleportTo(p, this.getName());
user.getTeleport().teleport(p, this.getName());
break;
case 2:
if (!user.isAuthorized("essentials.tpohere")) throw new Exception("You need access to /tpohere to teleport other players.");
if (!user.isAuthorized("essentials.tpohere"))
{
throw new Exception("You need access to /tpohere to teleport other players.");
}
user.sendMessage("§7Teleporting...");
user.charge(this);
charge(user);
User target = getPlayer(server, args, 0);
User toPlayer = getPlayer(server, args, 1);
target.teleportToNow(toPlayer);
target.getTeleport().now(toPlayer);
target.sendMessage("§7" + user.getDisplayName() + "§7 teleported you to " + toPlayer.getDisplayName() + "§7.");
break;
}
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
sender.sendMessage("Usage: /" + commandLabel + " [target] [to-player]");
return;
throw new NotEnoughArgumentsException();
}
sender.sendMessage("§7Teleporting...");
User target = getPlayer(server, args, 0);
User toPlayer = getPlayer(server, args, 1);
target.teleportToNow(toPlayer);
target.getTeleport().now(toPlayer);
target.sendMessage("§7{Console}§7 teleported you to " + toPlayer.getDisplayName() + "§7.");
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,19 +12,20 @@ public class Commandtpa extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception
public void run(Server server, User player, String commandLabel, String[] args) throws Exception
{
if(args.length < 1)
if (args.length < 1)
{
player.sendMessage("§cUsage: /tpa [playername]");
return;
throw new NotEnoughArgumentsException();
}
User p = getPlayer(server, args, 0);
if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled.");
if (!p.isTeleportEnabled())
{
throw new Exception(p.getDisplayName() + " has teleportation disabled.");
}
player.charge(this);
parent.tpcRequests.put(p, player);
parent.tpcHere.put(p, false);
p.requestTeleport(player, false);
p.sendMessage("§c" + player.getDisplayName() + "§c has requested to teleport to you.");
p.sendMessage("§7To teleport, type §c/tpaccept§7.");
p.sendMessage("§7To deny this request, type §c/tpdeny§7.");

View File

@ -1,9 +1,7 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand;
public class Commandtpaccept extends EssentialsCommand
@ -14,27 +12,29 @@ public class Commandtpaccept extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
User p = parent.tpcRequests.get(user);
if (p == null) throw new Exception("You do not have a pending request.");
parent.tpcRequests.remove(user);
if (parent.tpcHere.get(user))
User p = user.getTeleportRequest();
if (p == null)
{
throw new Exception("You do not have a pending request.");
}
if (user.isTeleportRequestHere())
{
user.teleportCooldown();
user.canAfford(this);
user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted.");
user.teleportTo(p, this.getName());
user.getTeleport().teleport(p, this.getName());
}
else
{
user.canAfford(this);
user.sendMessage("§7Teleport request accepted.");
p.sendMessage("§7Teleport request accepted.");
p.teleportTo(user, this.getName());
user.getTeleport().teleport(user, this.getName());
}
user.requestTeleport(null, false);
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,19 +12,20 @@ public class Commandtpahere extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§cUsage: /tpahere [playername]");
return;
throw new NotEnoughArgumentsException();
}
User p = getPlayer(server, args, 0);
if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled.");
if (!p.isTeleportEnabled())
{
throw new Exception(p.getDisplayName() + " has teleportation disabled.");
}
user.charge(this);
parent.tpcRequests.put(p, user);
parent.tpcHere.put(p, true);
p.requestTeleport(user, true);
p.sendMessage("§c" + user.getDisplayName() + "§c has requested that you teleport to him/her.");
p.sendMessage("§7To teleport, type §c/tpaccept§7.");
user.sendMessage("§7Request sent to " + p.getDisplayName() + "§c.");

View File

@ -1,8 +1,8 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -14,31 +14,41 @@ public class Commandtpall extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.charge(this);
user.sendMessage("§7Teleporting...");
for (Player player : server.getOnlinePlayers()) {
User p = User.get(player);
if (p == user) {
continue;
}
p.teleportToNow(user);
if (sender instanceof Player)
{
charge(sender);
teleportAllPlayers(server, sender, ess.getUser(sender));
return;
}
throw new NotEnoughArgumentsException();
}
else
User p = getPlayer(server, args, 0);
charge(sender);
teleportAllPlayers(server, sender, p);
}
private void teleportAllPlayers(Server server, CommandSender sender, User p)
{
sender.sendMessage("§7Teleporting all players...");
for (Player player : server.getOnlinePlayers())
{
User p = getPlayer(server, args, 0);
user.charge(this);
user.sendMessage("§7Teleporting...");
for (Player player : server.getOnlinePlayers()) {
User u = User.get(player);
if (p == u) {
continue;
}
u.teleportToNow(p);
User u = ess.getUser(player);
if (p == u)
{
continue;
}
try
{
u.getTeleport().now(p);
}
catch (Exception ex)
{
sender.sendMessage("Error: "+ex.getMessage());
}
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,25 +12,26 @@ public class Commandtpdeny extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
User p = parent.tpcRequests.get(user);
if (p == null) throw new Exception("You do not have a pending request.");
parent.tpcRequests.remove(user);
User p = user.getTeleportRequest();
if (p == null)
{
throw new Exception("You do not have a pending request.");
}
if (parent.tpcHere.get(user))
if (user.isTeleportRequestHere())
{
user.charge(this);
user.sendMessage("§7Teleport request denied.");
p.sendMessage("§7Teleport request denied.");
parent.tpcHere.remove(user);
}
else
{
user.charge(this);
user.sendMessage("§7Teleport request denied.");
p.sendMessage("§7Teleport request denied.");
parent.tpcRequests.remove(user);
}
user.requestTeleport(null, false);
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,22 +12,15 @@ public class Commandtphere extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[]
{
getName(), "telehere", "s"
};
}
@Override
public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
User p = getPlayer(server, args, 0);
if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled.");
player.charge(this);
p.teleportTo(player);
player.sendMessage("§7Teleporting...");
if (!p.isTeleportEnabled())
{
throw new Exception(p.getDisplayName() + " has teleportation disabled.");
}
p.getTeleport().teleport(user, commandLabel);
user.sendMessage("§7Teleporting...");
p.sendMessage("§7Teleporting...");
}
}

View File

@ -1,9 +1,7 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.commands.EssentialsCommand;
public class Commandtpo extends EssentialsCommand
@ -14,21 +12,17 @@ public class Commandtpo extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§c Usage: /tpo [playername]");
}
else
{
//Just basically the old tp command
User p = getPlayer(server, args, 0);
user.teleportCooldown();
user.charge(this);
user.teleportToNow(p);
user.sendMessage("§7Teleporting...");
throw new NotEnoughArgumentsException();
}
//Just basically the old tp command
User p = getPlayer(server, args, 0);
charge(user);
user.getTeleport().now(p);
user.sendMessage("§7Teleporting...");
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,19 +12,17 @@ public class Commandtpohere extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
user.sendMessage("§c Usage: /tpohere [playername]");
}
else
{
//Just basically the old tphere command
User p = getPlayer(server, args, 0);
user.charge(this);
p.teleportToNow(user);
user.sendMessage("§7Teleporting...");
throw new NotEnoughArgumentsException();
}
//Just basically the old tphere command
User p = getPlayer(server, args, 0);
charge(user);
p.getTeleport().now(user);
user.sendMessage("§7Teleporting...");
}
}

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -14,29 +13,19 @@ public class Commandtppos extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[]
{
getName(), "tpp"
};
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length < 3)
{
user.sendMessage("§cUsage: /tppos [x] [y] [z]");
return;
throw new NotEnoughArgumentsException();
}
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int z = Integer.parseInt(args[2]);
Location l = new Location(user.getWorld(),x,y,z);
Location l = new Location(user.getWorld(), x, y, z);
user.canAfford(this);
user.teleportCooldown();
user.sendMessage("§7Teleporting...");
user.teleportTo(user.getSafeDestination(l), this.getName());
user.getTeleport().teleport(l, this.getName());
}
}

View File

@ -1,7 +1,6 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@ -13,9 +12,9 @@ public class Commandtptoggle extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
user.charge(this);
user.sendMessage("§7Teleportation " + (user.toggleTeleEnabled() ? "enabled." : "disabled."));
charge(user);
user.sendMessage("§7Teleportation " + (user.toggleTeleportEnabled() ? "enabled." : "disabled."));
}
}

View File

@ -3,8 +3,9 @@ package com.earth2me.essentials.commands;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.TreeType;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandtree extends EssentialsCommand
{
@ -14,13 +15,12 @@ public class Commandtree extends EssentialsCommand
}
@Override
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
Object tree = new Object();
if (args.length < 1)
{
user.sendMessage("§cUsage: /tree [tree|birch|redwood]");
return;
throw new NotEnoughArgumentsException();
}
else if (args[0].equalsIgnoreCase("birch"))
{
@ -36,8 +36,7 @@ public class Commandtree extends EssentialsCommand
}
else
{
user.sendMessage("§cUsage: /tree [tree|birch|redwood]");
return;
throw new NotEnoughArgumentsException();
}
double x = user.getLocation().getX();
@ -46,12 +45,24 @@ public class Commandtree extends EssentialsCommand
// offset tree in direction player is facing
int r = (int)user.getCorrectedYaw();
if (r < 68 || r > 292) x -= 3.0D; // north
else if (r > 112 && r < 248) x += 3.0D; // south
if (r > 22 && r < 158) z -= 3.0D; // east
else if (r > 202 && r < 338) z += 3.0D; // west
if (r < 68 || r > 292) // north
{
x -= 3.0D;
}
else if (r > 112 && r < 248) // south
{
x += 3.0D;
}
if (r > 22 && r < 158) // east
{
z -= 3.0D;
}
else if (r > 202 && r < 338) // west
{
z += 3.0D;
}
Location safeLocation = user.getSafeDestination(new Location(user.getWorld(), x, y, z));
Location safeLocation = Util.getSafeDestination(new Location(user.getWorld(), x, y, z));
boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree);
if (success)
{
@ -59,6 +70,8 @@ public class Commandtree extends EssentialsCommand
user.sendMessage("§7Tree spawned.");
}
else
{
user.sendMessage("§cTree generation failure. Try again on grass or dirt.");
}
}
}

View File

@ -3,7 +3,6 @@ package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.Essentials;
public class Commandunban extends EssentialsCommand
@ -14,22 +13,15 @@ public class Commandunban extends EssentialsCommand
}
@Override
public String[] getTriggers()
{
return new String[] { getName(), "pardon" };
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
sender.sendMessage("Usage: /" + commandLabel + " [player]");
return;
throw new NotEnoughArgumentsException();
}
((CraftServer)server).getHandle().b(args[0]);
sender.sendMessage("Unbanned player.");
Essentials.getStatic().loadBanList();
ess.loadBanList();
}
}

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