spacing :D

This commit is contained in:
drtshock
2013-04-11 19:43:59 -05:00
parent a0eabf700b
commit 678f61127e
23 changed files with 1161 additions and 1161 deletions
@@ -27,108 +27,108 @@ import com.drtshock.playervaults.util.VaultManager;
public class Listeners implements Listener { public class Listeners implements Listener {
public Main plugin; public Main plugin;
public Listeners(Main instance) { public Listeners(Main instance) {
this.plugin = instance; this.plugin = instance;
} }
VaultManager vm = new VaultManager(plugin); VaultManager vm = new VaultManager(plugin);
/** /**
* Save a players vault. * Save a players vault.
* Sends to method in VaultManager class. * Sends to method in VaultManager class.
* @param Player p * @param Player p
*/ */
public void saveVault(Player p) { public void saveVault(Player p) {
if(Commands.inVault.containsKey(p.getName())) { if(Commands.inVault.containsKey(p.getName())) {
Inventory inv = p.getOpenInventory().getTopInventory(); Inventory inv = p.getOpenInventory().getTopInventory();
VaultViewInfo info = Commands.inVault.get(p.getName()); VaultViewInfo info = Commands.inVault.get(p.getName());
try { try {
vm.saveVault(inv, info.getHolder(), info.getNumber()); vm.saveVault(inv, info.getHolder(), info.getNumber());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
Commands.inVault.remove(p.getName()); Commands.inVault.remove(p.getName());
} }
} }
@EventHandler @EventHandler
public void onTeleport(PlayerTeleportEvent event) { public void onTeleport(PlayerTeleportEvent event) {
saveVault(event.getPlayer()); saveVault(event.getPlayer());
} }
@EventHandler @EventHandler
public void onQuit(PlayerQuitEvent event) { public void onQuit(PlayerQuitEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
saveVault(player); saveVault(player);
} }
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
vm.playerVaultFile(player.getName()); vm.playerVaultFile(player.getName());
if(player.isOp() && Main.update) { if(player.isOp() && Main.update) {
player.sendMessage(ChatColor.GREEN + "Version " + Main.name + " of PlayerVaults is up for download!"); player.sendMessage(ChatColor.GREEN + "Version " + Main.name + " of PlayerVaults is up for download!");
player.sendMessage(ChatColor.GREEN + "http://dev.bukkit.org/server-mods/playervaults/ to view the changelog and download!"); player.sendMessage(ChatColor.GREEN + "http://dev.bukkit.org/server-mods/playervaults/ to view the changelog and download!");
} }
} }
@EventHandler @EventHandler
public void onDeath(PlayerDeathEvent event) { public void onDeath(PlayerDeathEvent event) {
Player player = event.getEntity(); Player player = event.getEntity();
saveVault(player); saveVault(player);
if(Main.dropOnDeath && (!player.hasPermission("playervaults.ignore.drops"))) { if(Main.dropOnDeath && (!player.hasPermission("playervaults.ignore.drops"))) {
DropOnDeath.drop(event.getEntity()); DropOnDeath.drop(event.getEntity());
} }
} }
@EventHandler @EventHandler
public void onClose(InventoryCloseEvent event) { public void onClose(InventoryCloseEvent event) {
HumanEntity he = event.getPlayer(); HumanEntity he = event.getPlayer();
if(he instanceof Player) { if(he instanceof Player) {
Player player = (Player) he; Player player = (Player) he;
saveVault(player); saveVault(player);
} }
} }
/** /**
* Check if a player is trying to do something while * Check if a player is trying to do something while
* in a vault. * in a vault.
* Don't let them open up another chest. * Don't let them open up another chest.
* @param PlayerInteractEvent * @param PlayerInteractEvent
*/ */
@EventHandler @EventHandler
public void onInteract(PlayerInteractEvent event) { public void onInteract(PlayerInteractEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if(Commands.inVault.containsKey(player.getName()) && event.getAction() == Action.RIGHT_CLICK_BLOCK) { if(Commands.inVault.containsKey(player.getName()) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
/** /**
* Different inventories that * Different inventories that
* we don't want the player to open. * we don't want the player to open.
*/ */
if(block.getType() == Material.CHEST if(block.getType() == Material.CHEST
|| block.getType() == Material.ENDER_CHEST || block.getType() == Material.ENDER_CHEST
|| block.getType() == Material.FURNACE || block.getType() == Material.FURNACE
|| block.getType() == Material.BURNING_FURNACE || block.getType() == Material.BURNING_FURNACE
|| block.getType() == Material.BREWING_STAND || block.getType() == Material.BREWING_STAND
|| block.getType() == Material.BEACON) { || block.getType() == Material.BEACON) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
/** /**
* Don't let a player open a trading inventory OR a minecart * Don't let a player open a trading inventory OR a minecart
* while he has his vault open. * while he has his vault open.
*/ */
@EventHandler @EventHandler
public void onInteractEntity(PlayerInteractEntityEvent event) { public void onInteractEntity(PlayerInteractEntityEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
EntityType type = event.getRightClicked().getType(); EntityType type = event.getRightClicked().getType();
if((type == EntityType.VILLAGER||type==EntityType.MINECART) && Commands.inVault.containsKey(player.getName())) { if((type == EntityType.VILLAGER||type==EntityType.MINECART) && Commands.inVault.containsKey(player.getName())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
+130 -130
View File
@@ -19,147 +19,147 @@ import com.drtshock.playervaults.util.Updater;
public class Main extends JavaPlugin { public class Main extends JavaPlugin {
public static Main plugin; public static Main plugin;
public Logger log; public Logger log;
public static boolean update = false; public static boolean update = false;
public static String name = ""; public static String name = "";
Commands commands; Commands commands;
public static Economy econ = null; public static Economy econ = null;
public static boolean dropOnDeath = false; public static boolean dropOnDeath = false;
public static int inventoriesToDrop = 0; public static int inventoriesToDrop = 0;
public static boolean useVault = false; public static boolean useVault = false;
public static YamlConfiguration lang; public static YamlConfiguration lang;
public static File langFile; public static File langFile;
public static String directory = "plugins" + File.separator + "PlayerVaults" + File.separator + "vaults"; public static String directory = "plugins" + File.separator + "PlayerVaults" + File.separator + "vaults";
@Override @Override
public void onEnable() { public void onEnable() {
loadLang(); loadLang();
log = getServer().getLogger(); log = getServer().getLogger();
getServer().getPluginManager().registerEvents(new Listeners(this), this); getServer().getPluginManager().registerEvents(new Listeners(this), this);
loadConfig(); loadConfig();
startMetrics(); startMetrics();
Updater u = new Updater(getDescription().getVersion()); Updater u = new Updater(getDescription().getVersion());
if(getConfig().getBoolean("check-update")) { if(getConfig().getBoolean("check-update")) {
try { try {
if(u.getUpdate()) { if(u.getUpdate()) {
update = true; update = true;
name = u.getNewVersion(); name = u.getNewVersion();
} }
} catch (Exception e) { } catch (Exception e) {
log.log(Level.WARNING, "PlayerVaults: Failed to check for updates."); log.log(Level.WARNING, "PlayerVaults: Failed to check for updates.");
log.log(Level.WARNING, "PlayerVaults: Report this stack trace to drtshock and gomeow."); log.log(Level.WARNING, "PlayerVaults: Report this stack trace to drtshock and gomeow.");
e.printStackTrace(); e.printStackTrace();
} }
} }
commands = new Commands(); commands = new Commands();
getCommand("pv").setExecutor(commands); getCommand("pv").setExecutor(commands);
getCommand("pvdel").setExecutor(commands); getCommand("pvdel").setExecutor(commands);
getCommand("workbench").setExecutor(commands); getCommand("workbench").setExecutor(commands);
setupEconomy(); setupEconomy();
if(getConfig().getBoolean("drop-on-death.enabled")) { if(getConfig().getBoolean("drop-on-death.enabled")) {
dropOnDeath = true; dropOnDeath = true;
inventoriesToDrop = getConfig().getInt("drop-on-death.inventories"); inventoriesToDrop = getConfig().getInt("drop-on-death.inventories");
} }
new File(directory + File.separator + "backups").mkdirs(); new File(directory + File.separator + "backups").mkdirs();
} }
public void startMetrics() { public void startMetrics() {
try { try {
Metrics metrics = new Metrics(this); Metrics metrics = new Metrics(this);
metrics.start(); metrics.start();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
private boolean setupEconomy() { private boolean setupEconomy() {
if(getServer().getPluginManager().getPlugin("Vault") == null) { if(getServer().getPluginManager().getPlugin("Vault") == null) {
return false; return false;
} }
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class); RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if(rsp == null) { if(rsp == null) {
return false; return false;
} }
econ = rsp.getProvider(); econ = rsp.getProvider();
useVault = true; useVault = true;
return econ != null; return econ != null;
} }
public void loadConfig() { public void loadConfig() {
File config = new File(getDataFolder() + File.separator + "config.yml"); File config = new File(getDataFolder() + File.separator + "config.yml");
if(!config.exists()) { if(!config.exists()) {
saveDefaultConfig(); saveDefaultConfig();
} else { } else {
updateConfig(); updateConfig();
} }
} }
public void updateConfig() { public void updateConfig() {
boolean checkUpdate = getConfig().getBoolean("check-update", true); boolean checkUpdate = getConfig().getBoolean("check-update", true);
boolean ecoEnabled = getConfig().getBoolean("economy.enabled", false); boolean ecoEnabled = getConfig().getBoolean("economy.enabled", false);
int ecoCreate = getConfig().getInt("economy.cost-to-create", 100); int ecoCreate = getConfig().getInt("economy.cost-to-create", 100);
int ecoOpen = getConfig().getInt("economy.cost-to-open", 10); int ecoOpen = getConfig().getInt("economy.cost-to-open", 10);
int ecoDelete = getConfig().getInt("economy.refund-on-delete", 50); int ecoDelete = getConfig().getInt("economy.refund-on-delete", 50);
boolean dropEnabled = getConfig().getBoolean("drop-on-death.enabled", false); boolean dropEnabled = getConfig().getBoolean("drop-on-death.enabled", false);
int dropInvs = getConfig().getInt("drop-on-death.inventories", 50); int dropInvs = getConfig().getInt("drop-on-death.inventories", 50);
File configFile = new File(getDataFolder(), "config.yml"); File configFile = new File(getDataFolder(), "config.yml");
configFile.delete(); configFile.delete();
YamlConfiguration conf = YamlConfiguration.loadConfiguration(getResource("config.yml")); YamlConfiguration conf = YamlConfiguration.loadConfiguration(getResource("config.yml"));
setInConfig("check-update", checkUpdate, conf); setInConfig("check-update", checkUpdate, conf);
setInConfig("economy.enabled", ecoEnabled, conf); setInConfig("economy.enabled", ecoEnabled, conf);
setInConfig("economy.cost-to-create", ecoCreate, conf); setInConfig("economy.cost-to-create", ecoCreate, conf);
setInConfig("economy.cost-to-open", ecoOpen, conf); setInConfig("economy.cost-to-open", ecoOpen, conf);
setInConfig("economy.refund-on-delete", ecoDelete, conf); setInConfig("economy.refund-on-delete", ecoDelete, conf);
setInConfig("drop-on-death.enabled", dropEnabled, conf); setInConfig("drop-on-death.enabled", dropEnabled, conf);
setInConfig("drop-on-death.inventories", dropInvs, conf); setInConfig("drop-on-death.inventories", dropInvs, conf);
try { try {
conf.save(configFile); conf.save(configFile);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public <T> void setInConfig(String path, T object, YamlConfiguration conf) { public <T> void setInConfig(String path, T object, YamlConfiguration conf) {
conf.set(path, object); conf.set(path, object);
} }
public YamlConfiguration loadLang() { public YamlConfiguration loadLang() {
File lang = new File(getDataFolder(), "lang.yml"); File lang = new File(getDataFolder(), "lang.yml");
if(!lang.exists()) { if(!lang.exists()) {
try { try {
getDataFolder().mkdir(); getDataFolder().mkdir();
lang.createNewFile(); lang.createNewFile();
InputStream defConfigStream = this.getResource("lang.yml"); InputStream defConfigStream = this.getResource("lang.yml");
if(defConfigStream != null) { if(defConfigStream != null) {
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
defConfig.save(lang); defConfig.save(lang);
Lang.setFile(defConfig); Lang.setFile(defConfig);
return defConfig; return defConfig;
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); // So they notice e.printStackTrace(); // So they notice
log.severe("[PlayerVaults] Couldn't create language file."); log.severe("[PlayerVaults] Couldn't create language file.");
log.severe("[PlayerVaults] This is a fatal error. Now disabling"); log.severe("[PlayerVaults] This is a fatal error. Now disabling");
this.setEnabled(false); // Without it loaded, we can't send them messages this.setEnabled(false); // Without it loaded, we can't send them messages
} }
} }
YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang);
Lang.setFile(conf); Lang.setFile(conf);
Main.lang = conf; Main.lang = conf;
Main.langFile = lang; Main.langFile = lang;
return conf; return conf;
} }
public YamlConfiguration getLang() { public YamlConfiguration getLang() {
return lang; return lang;
} }
public File getLangFile() { public File getLangFile() {
return langFile; return langFile;
} }
} }
@@ -15,57 +15,57 @@ import com.drtshock.playervaults.util.Lang;
public class Commands implements CommandExecutor { public class Commands implements CommandExecutor {
public static HashMap<String, VaultViewInfo> inVault = new HashMap<String, VaultViewInfo>(); public static HashMap<String, VaultViewInfo> inVault = new HashMap<String, VaultViewInfo>();
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(cmd.getName().equalsIgnoreCase("pv")) { if(cmd.getName().equalsIgnoreCase("pv")) {
if(sender instanceof Player) { if(sender instanceof Player) {
Player p = (Player) sender; Player p = (Player) sender;
switch (args.length) { switch (args.length) {
case 1: case 1:
if(VaultOperations.openOwnVault(p, args[0])) if(VaultOperations.openOwnVault(p, args[0]))
inVault.put(sender.getName(), new VaultViewInfo(sender.getName(), Integer.parseInt(args[0]))); inVault.put(sender.getName(), new VaultViewInfo(sender.getName(), Integer.parseInt(args[0])));
break; break;
case 2: case 2:
if(VaultOperations.openOtherVault(p, args[0], args[1])) if(VaultOperations.openOtherVault(p, args[0], args[1]))
inVault.put(sender.getName(), new VaultViewInfo(args[0], Integer.parseInt(args[1]))); inVault.put(sender.getName(), new VaultViewInfo(args[0], Integer.parseInt(args[1])));
break; break;
default: default:
Feedback.showHelp(sender, Feedback.Type.OPEN); Feedback.showHelp(sender, Feedback.Type.OPEN);
} }
} }
else sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.PLAYER_ONLY); else sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.PLAYER_ONLY);
} else if(cmd.getName().equalsIgnoreCase("pvdel")) { } else if(cmd.getName().equalsIgnoreCase("pvdel")) {
switch (args.length) { switch (args.length) {
case 1: case 1:
if(sender instanceof Player) { if(sender instanceof Player) {
Player p = (Player) sender; Player p = (Player) sender;
VaultOperations.deleteOwnVault(p, args[0]); VaultOperations.deleteOwnVault(p, args[0]);
} }
else { else {
sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.PLAYER_ONLY); sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.PLAYER_ONLY);
} }
break; break;
case 2: case 2:
VaultOperations.deleteOtherVault(sender, args[0], args[1]); VaultOperations.deleteOtherVault(sender, args[0], args[1]);
break; break;
default: default:
Feedback.showHelp(sender, Feedback.Type.DELETE); Feedback.showHelp(sender, Feedback.Type.DELETE);
} }
} else if(cmd.getName().equalsIgnoreCase("workbench")) { } else if(cmd.getName().equalsIgnoreCase("workbench")) {
if(sender.hasPermission("playervaults.workbench")) { if(sender.hasPermission("playervaults.workbench")) {
if(sender instanceof Player) { if(sender instanceof Player) {
Inventory workbench = Bukkit.createInventory(null, InventoryType.WORKBENCH); Inventory workbench = Bukkit.createInventory(null, InventoryType.WORKBENCH);
((Player)sender).openInventory(workbench); ((Player)sender).openInventory(workbench);
sender.sendMessage(Lang.TITLE.toString() + Lang.OPEN_WORKBENCH); sender.sendMessage(Lang.TITLE.toString() + Lang.OPEN_WORKBENCH);
} else { } else {
sender.sendMessage(Lang.TITLE.toString() + Lang.PLAYER_ONLY); sender.sendMessage(Lang.TITLE.toString() + Lang.PLAYER_ONLY);
} }
} else { } else {
sender.sendMessage(Lang.TITLE.toString() + Lang.NO_PERMS); sender.sendMessage(Lang.TITLE.toString() + Lang.NO_PERMS);
} }
} }
return true; return true;
} }
} }
@@ -6,26 +6,26 @@ import com.drtshock.playervaults.util.Lang;
public class Feedback { public class Feedback {
public enum Type { public enum Type {
OPEN, OPEN,
DELETE, DELETE,
WORKBENCH, //For later versions WORKBENCH, //For later versions
FURNACE; FURNACE;
} }
public static void noPerms(CommandSender sender) { public static void noPerms(CommandSender sender) {
sender.sendMessage(Lang.TITLE + "" + Lang.NO_PERMS); sender.sendMessage(Lang.TITLE + "" + Lang.NO_PERMS);
return; return;
} }
public static void showHelp(CommandSender sender, Type t) { public static void showHelp(CommandSender sender, Type t) {
if(t == Type.OPEN) { if(t == Type.OPEN) {
sender.sendMessage(Lang.TITLE + "/pv <number>"); sender.sendMessage(Lang.TITLE + "/pv <number>");
sender.sendMessage(Lang.TITLE + "/pv <player> <number>"); sender.sendMessage(Lang.TITLE + "/pv <player> <number>");
} }
else if(t == Type.DELETE) { else if(t == Type.DELETE) {
sender.sendMessage(Lang.TITLE + "/pvdel <number>"); sender.sendMessage(Lang.TITLE + "/pvdel <number>");
sender.sendMessage(Lang.TITLE + "/pvdel <player> <number>"); sender.sendMessage(Lang.TITLE + "/pvdel <player> <number>");
} }
} }
} }
@@ -13,150 +13,150 @@ import com.drtshock.playervaults.util.VaultManager;
public class VaultOperations { public class VaultOperations {
private static Main plugin; private static Main plugin;
private static VaultManager vm = new VaultManager(plugin); private static VaultManager vm = new VaultManager(plugin);
public static boolean checkPerms(CommandSender cs, int number) { public static boolean checkPerms(CommandSender cs, int number) {
if(cs.hasPermission("playervaults.amount." + String.valueOf(number))) return true; if(cs.hasPermission("playervaults.amount." + String.valueOf(number))) return true;
for(int x = number; x <= 99;x++) { for(int x = number; x <= 99;x++) {
if(cs.hasPermission("playervaults.amount." + String.valueOf(x))) return true; if(cs.hasPermission("playervaults.amount." + String.valueOf(x))) return true;
} }
return false; return false;
} }
/** /**
* Open a player's own vault. * Open a player's own vault.
* Return true if allowed. Otherwise false. * Return true if allowed. Otherwise false.
* @param Sender sender * @param Sender sender
* @param String arg * @param String arg
* @return success * @return success
*/ */
public static boolean openOwnVault(Player sender, String arg) { public static boolean openOwnVault(Player sender, String arg) {
if(arg.matches("^[0-9]{1,2}$")) { if(arg.matches("^[0-9]{1,2}$")) {
int number = 0; int number = 0;
try { try {
number = Integer.parseInt(arg); number = Integer.parseInt(arg);
if(number == 0) if(number == 0)
return false; return false;
} }
catch(NumberFormatException nfe) { catch(NumberFormatException nfe) {
sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER);
return false; return false;
} }
if(checkPerms(sender, number)) { if(checkPerms(sender, number)) {
if(EconomyOperations.payToOpen(sender)) { if(EconomyOperations.payToOpen(sender)) {
vm.loadVault(sender, sender.getName(), number); vm.loadVault(sender, sender.getName(), number);
sender.sendMessage(Lang.TITLE.toString() + Lang.OPEN_VAULT.toString().replace("%v", arg)); sender.sendMessage(Lang.TITLE.toString() + Lang.OPEN_VAULT.toString().replace("%v", arg));
return true; return true;
} else { } else {
sender.sendMessage(Lang.TITLE.toString() + Lang.INSUFFICIENT_FUNDS); sender.sendMessage(Lang.TITLE.toString() + Lang.INSUFFICIENT_FUNDS);
return false; return false;
} }
} else { } else {
Feedback.noPerms(sender); Feedback.noPerms(sender);
} }
} else { } else {
sender.sendMessage(Lang.TITLE.toString() + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + Lang.MUST_BE_NUMBER);
} }
return false; return false;
} }
/** /**
* Open another player's vault. * Open another player's vault.
* Return true if allowed. Otherwise false. * Return true if allowed. Otherwise false.
* @param Sender sender * @param Sender sender
* @param String user * @param String user
* @param String arg * @param String arg
* @return success * @return success
*/ */
public static boolean openOtherVault(Player sender, String user, String arg) { public static boolean openOtherVault(Player sender, String user, String arg) {
if(sender.hasPermission("playervaults.admin")) { if(sender.hasPermission("playervaults.admin")) {
if(arg.matches("^[0-9]{1,2}$")) { if(arg.matches("^[0-9]{1,2}$")) {
int number = 0; int number = 0;
try { try {
number = Integer.parseInt(arg); number = Integer.parseInt(arg);
if(number == 0) if(number == 0)
return false; return false;
} }
catch(NumberFormatException nfe) { catch(NumberFormatException nfe) {
sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER);
} }
vm.loadVault(sender, user, number); vm.loadVault(sender, user, number);
sender.sendMessage(Lang.TITLE.toString() + Lang.OPEN_OTHER_VAULT.toString().replace("%v", arg).replace("%p", user)); sender.sendMessage(Lang.TITLE.toString() + Lang.OPEN_OTHER_VAULT.toString().replace("%v", arg).replace("%p", user));
return true; return true;
} else { } else {
sender.sendMessage(Lang.TITLE.toString() + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + Lang.MUST_BE_NUMBER);
} }
} }
else { else {
Feedback.noPerms(sender); Feedback.noPerms(sender);
} }
return false; return false;
} }
/** /**
* Delete a player's own vault. * Delete a player's own vault.
* Return true if allowed. Otherwise false. * Return true if allowed. Otherwise false.
* @param Sender sender * @param Sender sender
* @param String arg * @param String arg
*/ */
public static void deleteOwnVault(Player sender, String arg) { public static void deleteOwnVault(Player sender, String arg) {
if(arg.matches("^[0-9]{1,2}$")) { if(arg.matches("^[0-9]{1,2}$")) {
int number = 0; int number = 0;
try { try {
number = Integer.parseInt(arg); number = Integer.parseInt(arg);
if(number == 0) if(number == 0)
sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER);
return; return;
} }
catch(NumberFormatException nfe) { catch(NumberFormatException nfe) {
sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER);
} }
try { try {
if(EconomyOperations.refundOnDelete(sender, number)) { if(EconomyOperations.refundOnDelete(sender, number)) {
vm.deleteVault(sender, sender.getName(), number); vm.deleteVault(sender, sender.getName(), number);
return; return;
} }
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_VAULT_ERROR); sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_VAULT_ERROR);
} }
} else { } else {
sender.sendMessage(Lang.TITLE.toString()+ Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString()+ Lang.MUST_BE_NUMBER);
} }
} }
/** /**
* Delete another player's vault. * Delete another player's vault.
* Return true if allowed. Otherwise false. * Return true if allowed. Otherwise false.
* @param Sender sender * @param Sender sender
* @param String user * @param String user
* @param String arg * @param String arg
*/ */
public static void deleteOtherVault(CommandSender sender, String user, String arg) { public static void deleteOtherVault(CommandSender sender, String user, String arg) {
if(sender.hasPermission("playervaults.delete")) { if(sender.hasPermission("playervaults.delete")) {
if(arg.matches("^[0-9]{1,2}$")) { if(arg.matches("^[0-9]{1,2}$")) {
int number = 0; int number = 0;
try { try {
number = Integer.parseInt(arg); number = Integer.parseInt(arg);
if(number == 0) { if(number == 0) {
sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER);
return; return;
} }
} }
catch(NumberFormatException nfe) { catch(NumberFormatException nfe) {
sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.MUST_BE_NUMBER);
} }
try { try {
vm.deleteVault(sender, user, number); vm.deleteVault(sender, user, number);
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_VAULT_ERROR); sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_VAULT_ERROR);
} }
} else { } else {
sender.sendMessage(Lang.TITLE.toString() + Lang.MUST_BE_NUMBER); sender.sendMessage(Lang.TITLE.toString() + Lang.MUST_BE_NUMBER);
} }
} }
else Feedback.noPerms(sender); else Feedback.noPerms(sender);
} }
} }
@@ -2,20 +2,20 @@ package com.drtshock.playervaults.commands;
public class VaultViewInfo { public class VaultViewInfo {
String s; String s;
int i; int i;
public VaultViewInfo(String s, int i) { public VaultViewInfo(String s, int i) {
this.s = s; this.s = s;
this.i = i; this.i = i;
} }
public String getHolder() { public String getHolder() {
return this.s; return this.s;
} }
public int getNumber() { public int getNumber() {
return this.i; return this.i;
} }
} }
@@ -9,27 +9,27 @@ import com.drtshock.playervaults.Main;
public class DropOnDeath { public class DropOnDeath {
public static Main plugin; public static Main plugin;
public DropOnDeath(Main instance) { public DropOnDeath(Main instance) {
DropOnDeath.plugin = instance; DropOnDeath.plugin = instance;
} }
static VaultManager vm = new VaultManager(plugin); static VaultManager vm = new VaultManager(plugin);
/** /**
* Drops all items when a player dies. * Drops all items when a player dies.
* @param player * @param player
*/ */
public static void drop(Player player) { public static void drop(Player player) {
Location loc = player.getLocation(); Location loc = player.getLocation();
for(int count = 1; count <= Main.inventoriesToDrop; count++) { for(int count = 1; count <= Main.inventoriesToDrop; count++) {
Inventory inv = vm.getVault(player, count); Inventory inv = vm.getVault(player, count);
ItemStack[] stack = inv.getContents(); ItemStack[] stack = inv.getContents();
for(ItemStack is : stack) { for(ItemStack is : stack) {
loc.getWorld().dropItemNaturally(loc, is); loc.getWorld().dropItemNaturally(loc, is);
} }
} }
} }
} }
@@ -15,86 +15,86 @@ import com.drtshock.playervaults.Main;
public class EconomyOperations { public class EconomyOperations {
private static File configFile; private static File configFile;
private static YamlConfiguration bukkitConfig = new YamlConfiguration(); private static YamlConfiguration bukkitConfig = new YamlConfiguration();
public static Main plugin; public static Main plugin;
public EconomyOperations(Main instance) throws FileNotFoundException, IOException, InvalidConfigurationException { public EconomyOperations(Main instance) throws FileNotFoundException, IOException, InvalidConfigurationException {
plugin = instance; plugin = instance;
configFile = new File(plugin.getDataFolder(), "config.yml"); configFile = new File(plugin.getDataFolder(), "config.yml");
bukkitConfig.load(configFile); bukkitConfig.load(configFile);
} }
/** /**
* Have a player pay to open a vault. * Have a player pay to open a vault.
* Returns true if successful. Otherwise false. * Returns true if successful. Otherwise false.
* @param player * @param player
* @return transaction success * @return transaction success
*/ */
public static boolean payToOpen(Player player) { public static boolean payToOpen(Player player) {
if(!bukkitConfig.getBoolean("economy.enabled") || /*player.hasPermission("playervaults.free") || */!Main.useVault) if(!bukkitConfig.getBoolean("economy.enabled") || /*player.hasPermission("playervaults.free") || */!Main.useVault)
return true; return true;
double cost = bukkitConfig.getDouble("economy.cost-to-open", 10); double cost = bukkitConfig.getDouble("economy.cost-to-open", 10);
EconomyResponse resp = Main.econ.withdrawPlayer(player.getName(), cost); EconomyResponse resp = Main.econ.withdrawPlayer(player.getName(), cost);
if(resp.transactionSuccess()) { if(resp.transactionSuccess()) {
player.sendMessage(Lang.TITLE.toString() + Lang.COST_TO_OPEN.toString().replaceAll("%price", "" + cost)); player.sendMessage(Lang.TITLE.toString() + Lang.COST_TO_OPEN.toString().replaceAll("%price", "" + cost));
return true; return true;
} }
return false; return false;
} }
/** /**
* Have a player pay to create a vault. * Have a player pay to create a vault.
* Returns true if successful. Otherwise false. * Returns true if successful. Otherwise false.
* @param player * @param player
* @return transaction success * @return transaction success
*/ */
public static boolean payToCreate(Player player) { public static boolean payToCreate(Player player) {
if(!bukkitConfig.getBoolean("economy.enabled") || /*player.hasPermission("playervaults.free") || */!Main.useVault) if(!bukkitConfig.getBoolean("economy.enabled") || /*player.hasPermission("playervaults.free") || */!Main.useVault)
return true; return true;
double cost = bukkitConfig.getDouble("economy.cost-to-create", 100); double cost = bukkitConfig.getDouble("economy.cost-to-create", 100);
EconomyResponse resp = Main.econ.withdrawPlayer(player.getName(), cost); EconomyResponse resp = Main.econ.withdrawPlayer(player.getName(), cost);
if(resp.transactionSuccess()) { if(resp.transactionSuccess()) {
player.sendMessage(Lang.TITLE.toString() + Lang.COST_TO_CREATE.toString().replaceAll("%price", "" + cost)); player.sendMessage(Lang.TITLE.toString() + Lang.COST_TO_CREATE.toString().replaceAll("%price", "" + cost));
return true; return true;
} }
return false; return false;
} }
/** /**
* Have a player get his money back when vault is deleted. * Have a player get his money back when vault is deleted.
* Returns true if successful. Otherwise false. * Returns true if successful. Otherwise false.
* @param player * @param player
* @return transaction success. * @return transaction success.
*/ */
public static boolean refundOnDelete(Player player, int number) { public static boolean refundOnDelete(Player player, int number) {
String directory = "plugins" + File.separator + "PlayerVaults" + File.separator + "vaults"; String directory = "plugins" + File.separator + "PlayerVaults" + File.separator + "vaults";
if(!bukkitConfig.getBoolean("economy.enabled") || player.hasPermission("playervaults.free") || !Main.useVault) if(!bukkitConfig.getBoolean("economy.enabled") || player.hasPermission("playervaults.free") || !Main.useVault)
return true; return true;
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
File file = new File(directory + File.separator + name.toLowerCase() + ".yml"); File file = new File(directory + File.separator + name.toLowerCase() + ".yml");
YamlConfiguration playerFile = YamlConfiguration.loadConfiguration(file); YamlConfiguration playerFile = YamlConfiguration.loadConfiguration(file);
if(file.exists()) { if(file.exists()) {
if(playerFile.getString("vault"+number) == null) { if(playerFile.getString("vault"+number) == null) {
player.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.VAULT_DOES_NOT_EXIST); player.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.VAULT_DOES_NOT_EXIST);
return false; return false;
} }
} }
else { else {
player.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.VAULT_DOES_NOT_EXIST); player.sendMessage(Lang.TITLE.toString() + ChatColor.RED + Lang.VAULT_DOES_NOT_EXIST);
return false; return false;
} }
double cost = bukkitConfig.getDouble("economy.refund-on-delete"); double cost = bukkitConfig.getDouble("economy.refund-on-delete");
EconomyResponse resp = Main.econ.depositPlayer(player.getName(), cost); EconomyResponse resp = Main.econ.depositPlayer(player.getName(), cost);
if(resp.transactionSuccess()) { if(resp.transactionSuccess()) {
player.sendMessage(Lang.TITLE.toString() + Lang.REFUND_AMOUNT.toString().replaceAll("%price", String.valueOf(cost))); player.sendMessage(Lang.TITLE.toString() + Lang.REFUND_AMOUNT.toString().replaceAll("%price", String.valueOf(cost)));
return true; return true;
} }
return false; return false;
} }
} }
@@ -4,48 +4,48 @@ import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
public enum Lang { public enum Lang {
TITLE("title-name", "&4[&fPlayerVaults&4]:"), TITLE("title-name", "&4[&fPlayerVaults&4]:"),
OPEN_VAULT("open-vault", "&fOpening vault &a%v"), OPEN_VAULT("open-vault", "&fOpening vault &a%v"),
OPEN_OTHER_VAULT("open-other-vault", "&fOpening vault &a%v &fof &a%p"), OPEN_OTHER_VAULT("open-other-vault", "&fOpening vault &a%v &fof &a%p"),
OPEN_WORKBENCH("open-workbench", "&fOpening workbench"), OPEN_WORKBENCH("open-workbench", "&fOpening workbench"),
INVALID_ARGS("invalid-args", "&cInvalid args!"), INVALID_ARGS("invalid-args", "&cInvalid args!"),
DELETE_VAULT("delete-vault", "&fDeleted vault &a%v"), DELETE_VAULT("delete-vault", "&fDeleted vault &a%v"),
DELETE_OTHER_VAULT("delete-other-vault", "&fDeleted vault &a%v &fof &a%p"), DELETE_OTHER_VAULT("delete-other-vault", "&fDeleted vault &a%v &fof &a%p"),
PLAYER_ONLY("player-only", "Sorry but that can only be run by a player!"), PLAYER_ONLY("player-only", "Sorry but that can only be run by a player!"),
MUST_BE_NUMBER("must-be-number", "&cYou need to specify a number between 1-99"), MUST_BE_NUMBER("must-be-number", "&cYou need to specify a number between 1-99"),
DELETE_VAULT_ERROR("delete-vault-error", "&cError deleting vault :("), DELETE_VAULT_ERROR("delete-vault-error", "&cError deleting vault :("),
NO_PERMS("no-permissions", "&cYou don''t have permission for that!"), NO_PERMS("no-permissions", "&cYou don''t have permission for that!"),
INSUFFICIENT_FUNDS("insufficient-funds", "&cYou don''t have enough money for that!"), INSUFFICIENT_FUNDS("insufficient-funds", "&cYou don''t have enough money for that!"),
REFUND_AMOUNT("refund-amount", "&fYou were refunded &a%price &ffor deleting that vault."), REFUND_AMOUNT("refund-amount", "&fYou were refunded &a%price &ffor deleting that vault."),
COST_TO_CREATE("cost-to-create", "&fYou were charged &c%price &ffor creating a vault."), COST_TO_CREATE("cost-to-create", "&fYou were charged &c%price &ffor creating a vault."),
COST_TO_OPEN("cost-to-open", "&fYou were charged &c%price &ffor opening that vault."), COST_TO_OPEN("cost-to-open", "&fYou were charged &c%price &ffor opening that vault."),
VAULT_DOES_NOT_EXIST("vault-does-not-exist", "&cThat vault does not exist!"); VAULT_DOES_NOT_EXIST("vault-does-not-exist", "&cThat vault does not exist!");
private String path; private String path;
private String def; // Default string private String def; // Default string
private static YamlConfiguration lang; private static YamlConfiguration lang;
Lang(String path, String start) { Lang(String path, String start) {
this.path = path; this.path = path;
this.def = start; this.def = start;
} }
public static void setFile(YamlConfiguration yc) { public static void setFile(YamlConfiguration yc) {
lang = yc; lang = yc;
} }
@Override @Override
public String toString() { public String toString() {
if(this == TITLE) if(this == TITLE)
return ChatColor.translateAlternateColorCodes('&', lang.getString(this.path, def)) + " "; return ChatColor.translateAlternateColorCodes('&', lang.getString(this.path, def)) + " ";
return ChatColor.translateAlternateColorCodes('&', lang.getString(this.path, def)); return ChatColor.translateAlternateColorCodes('&', lang.getString(this.path, def));
} }
public String getDefault() { public String getDefault() {
return this.def; return this.def;
} }
public String getPath() { public String getPath() {
return this.path; return this.path;
} }
} }
@@ -218,7 +218,7 @@ public class Metrics {
* @return True if statistics measuring is running, otherwise false. * @return True if statistics measuring is running, otherwise false.
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean start() { public boolean start() {
synchronized (optOutLock) { synchronized (optOutLock) {
// Did we opt out? // Did we opt out?
if (isOptOut()) { if (isOptOut()) {
@@ -290,23 +290,23 @@ public class Metrics {
} }
/** /**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
* *
* @throws IOException * @throws IOException
*/ */
public void enable() throws IOException { public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task. // This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) { synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it. // Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) { if (isOptOut()) {
configuration.set("opt-out", false); configuration.set("opt-out", false);
configuration.save(configurationFile); configuration.save(configurationFile);
} }
// Enable Task, if it is not running // Enable Task, if it is not running
if (taskId < 0) { if (taskId < 0) {
start(); start();
} }
} }
} }
@@ -19,12 +19,12 @@ import org.json.JSONObject;
public class Serialization { public class Serialization {
/* /*
* All normal functions * All normal functions
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static Map<String, Object> toMap(JSONObject object) throws JSONException { public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keys = object.keys(); Iterator<String> keys = object.keys();
while (keys.hasNext()) { while (keys.hasNext()) {
@@ -33,7 +33,7 @@ public class Serialization {
} }
return map; return map;
} }
private static Object fromJson(Object json) throws JSONException { private static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) { if (json == JSONObject.NULL) {
return null; return null;
} else if (json instanceof JSONObject) { } else if (json instanceof JSONObject) {
@@ -45,7 +45,7 @@ public class Serialization {
} }
} }
public static List<Object> toList(JSONArray array) throws JSONException { public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>(); List<Object> list = new ArrayList<Object>();
for (int i = 0; i < array.length(); i++) { for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i))); list.add(fromJson(array.get(i)));
@@ -53,45 +53,45 @@ public class Serialization {
return list; return list;
} }
public static List<String> toString(Inventory inv) { public static List<String> toString(Inventory inv) {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<String>();
List<ConfigurationSerializable> items = new ArrayList<ConfigurationSerializable>(); List<ConfigurationSerializable> items = new ArrayList<ConfigurationSerializable>();
for(ItemStack is:inv.getContents()) { for(ItemStack is:inv.getContents()) {
items.add(is); items.add(is);
} }
for(ConfigurationSerializable cs:items) { for(ConfigurationSerializable cs:items) {
if(cs == null) { if(cs == null) {
result.add("null"); result.add("null");
} }
else { else {
result.add(new JSONObject(serialize(cs)).toString()); result.add(new JSONObject(serialize(cs)).toString());
} }
} }
return result; return result;
} }
public static Inventory toInventory(List<String> stringItems, int number) { public static Inventory toInventory(List<String> stringItems, int number) {
Inventory inv = Bukkit.createInventory(null, 54, ChatColor.RED + "Vault #" + number); Inventory inv = Bukkit.createInventory(null, 54, ChatColor.RED + "Vault #" + number);
List<ItemStack> contents = new ArrayList<ItemStack>(); List<ItemStack> contents = new ArrayList<ItemStack>();
for(String piece:stringItems) { for(String piece:stringItems) {
if(piece.equalsIgnoreCase("null")) { if(piece.equalsIgnoreCase("null")) {
contents.add(null); contents.add(null);
} }
else { else {
try { try {
ItemStack item = (ItemStack) deserialize(toMap(new JSONObject(piece))); ItemStack item = (ItemStack) deserialize(toMap(new JSONObject(piece)));
contents.add(item); contents.add(item);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
ItemStack[] items = new ItemStack[contents.size()]; ItemStack[] items = new ItemStack[contents.size()];
for(int x = 0; x < contents.size(); x++) for(int x = 0; x < contents.size(); x++)
items[x] = contents.get(x); items[x] = contents.get(x);
inv.setContents(items); inv.setContents(items);
return inv; return inv;
} }
public static Map<String, Object> serialize(ConfigurationSerializable cs) { public static Map<String, Object> serialize(ConfigurationSerializable cs) {
Map<String, Object> serialized = recreateMap(cs.serialize()); Map<String, Object> serialized = recreateMap(cs.serialize());
@@ -15,65 +15,65 @@ import com.drtshock.playervaults.Main;
public class Updater extends Main { public class Updater extends Main {
SortedMap<String, String> lang = new TreeMap<String, String>(); SortedMap<String, String> lang = new TreeMap<String, String>();
String version; String version;
public Updater(String version) { public Updater(String version) {
this.version = version; this.version = version;
YamlConfiguration langConf = super.getLang(); YamlConfiguration langConf = super.getLang();
for(Lang item:Lang.values()) { for(Lang item:Lang.values()) {
if(langConf.getString(item.getPath()) == null) { if(langConf.getString(item.getPath()) == null) {
langConf.set(item.getPath(), item.getDefault()); langConf.set(item.getPath(), item.getDefault());
} }
} }
try { try {
langConf.save(super.getLangFile()); langConf.save(super.getLangFile());
} catch (IOException e) { } catch (IOException e) {
log.log(Level.WARNING, "PlayerVaults: Failed to save lang.yml."); log.log(Level.WARNING, "PlayerVaults: Failed to save lang.yml.");
log.log(Level.WARNING, "PlayerVaults: Report this stack trace to drtshock and gomeow."); log.log(Level.WARNING, "PlayerVaults: Report this stack trace to drtshock and gomeow.");
e.printStackTrace(); e.printStackTrace();
} }
} }
String newVersion = ""; String newVersion = "";
public String getNewVersion() { public String getNewVersion() {
return this.newVersion; return this.newVersion;
} }
public boolean getUpdate() throws Exception { public boolean getUpdate() throws Exception {
String version = this.version; String version = this.version;
URL url = new URL("http://dev.bukkit.org/server-mods/playervaults/files.rss"); URL url = new URL("http://dev.bukkit.org/server-mods/playervaults/files.rss");
InputStreamReader isr = null; InputStreamReader isr = null;
try { try {
isr = new InputStreamReader(url.openStream()); isr = new InputStreamReader(url.openStream());
} }
catch(UnknownHostException e) { catch(UnknownHostException e) {
return false; //Cannot connect return false; //Cannot connect
} }
BufferedReader in = new BufferedReader(isr); BufferedReader in = new BufferedReader(isr);
String line; String line;
int lineNum = 0; int lineNum = 0;
while((line = in.readLine()) != null) { while((line = in.readLine()) != null) {
if(line.length() != line.replace("<title>", "").length()) { if(line.length() != line.replace("<title>", "").length()) {
line = line.replaceAll("<title>", "").replaceAll("</title>", "").replaceAll(" ", "").substring(1); //Substring 1 for me, takes off the beginning v on my file name "v1.3.2" line = line.replaceAll("<title>", "").replaceAll("</title>", "").replaceAll(" ", "").substring(1); //Substring 1 for me, takes off the beginning v on my file name "v1.3.2"
if(lineNum == 1) { if(lineNum == 1) {
this.newVersion = line; this.newVersion = line;
Integer newVer = Integer.parseInt(line.replace(".", "")); Integer newVer = Integer.parseInt(line.replace(".", ""));
Integer oldVer = Integer.parseInt(version.replace(".", "")); Integer oldVer = Integer.parseInt(version.replace(".", ""));
if(oldVer < newVer) { if(oldVer < newVer) {
return true; //They are using an old version return true; //They are using an old version
} }
else if(oldVer > newVer) { else if(oldVer > newVer) {
return false; //They are using a FUTURE version! return false; //They are using a FUTURE version!
} }
else { else {
return false; //They are up to date! return false; //They are up to date!
} }
} }
lineNum = lineNum + 1; lineNum = lineNum + 1;
} }
} }
in.close(); in.close();
return false; return false;
} }
} }
@@ -17,136 +17,136 @@ import com.drtshock.playervaults.Main;
public class VaultManager { public class VaultManager {
public Main plugin; public Main plugin;
public VaultManager(Main instance) { public VaultManager(Main instance) {
this.plugin = instance; this.plugin = instance;
} }
private final String directory = "plugins" + File.separator + "PlayerVaults" + File.separator + "vaults"; private final String directory = "plugins" + File.separator + "PlayerVaults" + File.separator + "vaults";
/** /**
* Method to save player's vault. * Method to save player's vault.
* Serialize his inventory. * Serialize his inventory.
* Save the vaults.yml * Save the vaults.yml
* @param player * @param player
* @throws IOException * @throws IOException
*/ */
public void saveVault(Inventory inv, String player, int number) throws IOException { public void saveVault(Inventory inv, String player, int number) throws IOException {
YamlConfiguration yaml = playerVaultFile(player); YamlConfiguration yaml = playerVaultFile(player);
yaml.set("vault" + number, null); yaml.set("vault" + number, null);
List<String> list = Serialization.toString(inv); List<String> list = Serialization.toString(inv);
String[] ser = list.toArray(new String[list.size()]); String[] ser = list.toArray(new String[list.size()]);
for(int x = 0; x < ser.length; x++) { for(int x = 0; x < ser.length; x++) {
if(!ser[x].equalsIgnoreCase("null")) if(!ser[x].equalsIgnoreCase("null"))
yaml.set("vault" + number + "." + x, ser[x]); yaml.set("vault" + number + "." + x, ser[x]);
} }
saveFile(player, yaml); saveFile(player, yaml);
} }
/** /**
* Method to load player's vault. * Method to load player's vault.
* Deserialize his inventory * Deserialize his inventory
* *
* TODO: Check to see if the path exists before we get it! * TODO: Check to see if the path exists before we get it!
*/ */
public void loadVault(Player player, String holder, int number) { public void loadVault(Player player, String holder, int number) {
Inventory inv = null; Inventory inv = null;
YamlConfiguration playerFile = playerVaultFile(holder); YamlConfiguration playerFile = playerVaultFile(holder);
if(playerFile.getConfigurationSection("vault" + number) == null) { if(playerFile.getConfigurationSection("vault" + number) == null) {
inv = Bukkit.createInventory(player, 54, ChatColor.DARK_RED + "Vault #" + String.valueOf(number)); inv = Bukkit.createInventory(player, 54, ChatColor.DARK_RED + "Vault #" + String.valueOf(number));
} }
else { else {
List<String> data = new ArrayList<String>(); List<String> data = new ArrayList<String>();
for(int x = 0; x < 54; x++) { for(int x = 0; x < 54; x++) {
String line = playerFile.getString("vault" + number + "." + x); String line = playerFile.getString("vault" + number + "." + x);
if(line != null) { if(line != null) {
data.add(line); data.add(line);
} }
else { else {
data.add("null"); data.add("null");
} }
} }
inv = Serialization.toInventory(data, number); inv = Serialization.toInventory(data, number);
} }
player.openInventory(inv); player.openInventory(inv);
} }
/** /**
* Gets an inventory without opening it. * Gets an inventory without opening it.
* Used for dropping a players inventories on death. * Used for dropping a players inventories on death.
* @param player * @param player
* @param number * @param number
* @return the inventory * @return the inventory
*/ */
public Inventory getVault(Player player, int number) { public Inventory getVault(Player player, int number) {
YamlConfiguration playerFile = playerVaultFile(player.getName()); YamlConfiguration playerFile = playerVaultFile(player.getName());
List<String> data = playerFile.getStringList("vault" + number); List<String> data = playerFile.getStringList("vault" + number);
if(data == null) { if(data == null) {
Inventory inv = Bukkit.createInventory(player, 54, ChatColor.GREEN + "Vault #" + String.valueOf(number)); Inventory inv = Bukkit.createInventory(player, 54, ChatColor.GREEN + "Vault #" + String.valueOf(number));
return inv; return inv;
} else { } else {
Inventory inv = Serialization.toInventory(data, number); Inventory inv = Serialization.toInventory(data, number);
return inv; return inv;
} }
} }
/** /**
* Deletes a players vault. * Deletes a players vault.
* @param sender * @param sender
* @param target * @param target
* @param number * @param number
* @throws IOException * @throws IOException
*/ */
public void deleteVault(CommandSender sender, String target, int number) throws IOException { public void deleteVault(CommandSender sender, String target, int number) throws IOException {
String name = target.toLowerCase(); String name = target.toLowerCase();
File file = new File(directory + File.separator + name.toLowerCase() + ".yml"); File file = new File(directory + File.separator + name.toLowerCase() + ".yml");
FileConfiguration playerFile = YamlConfiguration.loadConfiguration(file); FileConfiguration playerFile = YamlConfiguration.loadConfiguration(file);
if(file.exists()) { if(file.exists()) {
playerFile.set("vault" + number, null); playerFile.set("vault" + number, null);
playerFile.save(file); playerFile.save(file);
} }
if(sender.getName().equalsIgnoreCase(target)) { if(sender.getName().equalsIgnoreCase(target)) {
sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_VAULT.toString().replace("%v", String.valueOf(number))); sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_VAULT.toString().replace("%v", String.valueOf(number)));
} }
else { else {
sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_OTHER_VAULT.toString().replace("%v", String.valueOf(number)).replace("%p", target)); sender.sendMessage(Lang.TITLE.toString() + Lang.DELETE_OTHER_VAULT.toString().replace("%v", String.valueOf(number)).replace("%p", target));
} }
} }
/** /**
* Get the player's vault file. * Get the player's vault file.
* Create if doesn't exist. * Create if doesn't exist.
* @param player * @param player
* @return playerVaultFile file. * @return playerVaultFile file.
*/ */
public YamlConfiguration playerVaultFile(String player) { public YamlConfiguration playerVaultFile(String player) {
File folder = new File(directory); File folder = new File(directory);
if(!folder.exists()) { if(!folder.exists()) {
folder.mkdir(); folder.mkdir();
} }
File file = new File(directory + File.separator + player.toLowerCase() + ".yml"); File file = new File(directory + File.separator + player.toLowerCase() + ".yml");
if(!file.exists()) { if(!file.exists()) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
YamlConfiguration playerFile = YamlConfiguration.loadConfiguration(file); YamlConfiguration playerFile = YamlConfiguration.loadConfiguration(file);
return playerFile; return playerFile;
} }
/** /**
* Save the players vault file. * Save the players vault file.
* @param name * @param name
* @param yaml * @param yaml
* @throws IOException * @throws IOException
*/ */
public void saveFile(String name, YamlConfiguration yaml) throws IOException { public void saveFile(String name, YamlConfiguration yaml) throws IOException {
File file = new File(directory + File.separator + name.toLowerCase() + ".yml"); File file = new File(directory + File.separator + name.toLowerCase() + ".yml");
if (file.exists()) { if (file.exists()) {
file.renameTo(new File(directory + File.separator + "backups" + File.separator + name.toLowerCase() + ".yml")); file.renameTo(new File(directory + File.separator + "backups" + File.separator + name.toLowerCase() + ".yml"));
} }
yaml.save(file); yaml.save(file);
} }
} }
+1 -1
View File
@@ -22,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* This provides static methods to convert comma delimited text into a * This provides static methods to convert comma delimited text into a
+1 -1
View File
@@ -22,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* Convert a web browser cookie specification to a JSONObject and back. * Convert a web browser cookie specification to a JSONObject and back.
+1 -1
View File
@@ -22,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.util.Iterator; import java.util.Iterator;
+145 -145
View File
@@ -34,159 +34,159 @@ import java.util.Iterator;
*/ */
public class HTTP { public class HTTP {
/** Carriage return/line feed. */ /** Carriage return/line feed. */
public static final String CRLF = "\r\n"; public static final String CRLF = "\r\n";
/** /**
* Convert an HTTP header string into a JSONObject. It can be a request * Convert an HTTP header string into a JSONObject. It can be a request
* header or a response header. A request header will contain * header or a response header. A request header will contain
* *
* <pre> * <pre>
* { * {
* Method: "POST" (for example), * Method: "POST" (for example),
* "Request-URI": "/" (for example), * "Request-URI": "/" (for example),
* "HTTP-Version": "HTTP/1.1" (for example) * "HTTP-Version": "HTTP/1.1" (for example)
* } * }
* </pre> * </pre>
* *
* A response header will contain * A response header will contain
* *
* <pre> * <pre>
* { * {
* "HTTP-Version": "HTTP/1.1" (for example), * "HTTP-Version": "HTTP/1.1" (for example),
* "Status-Code": "200" (for example), * "Status-Code": "200" (for example),
* "Reason-Phrase": "OK" (for example) * "Reason-Phrase": "OK" (for example)
* } * }
* </pre> * </pre>
* *
* In addition, the other parameters in the header will be captured, using * In addition, the other parameters in the header will be captured, using
* the HTTP field names as JSON names, so that * the HTTP field names as JSON names, so that
* *
* <pre> * <pre>
* Date: Sun, 26 May 2002 18:06:04 GMT * Date: Sun, 26 May 2002 18:06:04 GMT
* Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
* Cache-Control: no-cache * Cache-Control: no-cache
* </pre> * </pre>
* *
* become * become
* *
* <pre> * <pre>
* {... * {...
* Date: "Sun, 26 May 2002 18:06:04 GMT", * Date: "Sun, 26 May 2002 18:06:04 GMT",
* Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
* "Cache-Control": "no-cache", * "Cache-Control": "no-cache",
* ...} * ...}
* </pre> * </pre>
* *
* It does no further checking or conversion. It does not parse dates. It * It does no further checking or conversion. It does not parse dates. It
* does not do '%' transforms on URLs. * does not do '%' transforms on URLs.
* *
* @param string * @param string
* An HTTP header string. * An HTTP header string.
* @return A JSONObject containing the elements and attributes of the XML * @return A JSONObject containing the elements and attributes of the XML
* string. * string.
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject(); JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string); HTTPTokener x = new HTTPTokener(string);
String token; String token;
token = x.nextToken(); token = x.nextToken();
if (token.toUpperCase().startsWith("HTTP")) { if (token.toUpperCase().startsWith("HTTP")) {
// Response // Response
jo.put("HTTP-Version", token); jo.put("HTTP-Version", token);
jo.put("Status-Code", x.nextToken()); jo.put("Status-Code", x.nextToken());
jo.put("Reason-Phrase", x.nextTo('\0')); jo.put("Reason-Phrase", x.nextTo('\0'));
x.next(); x.next();
} else { } else {
// Request // Request
jo.put("Method", token); jo.put("Method", token);
jo.put("Request-URI", x.nextToken()); jo.put("Request-URI", x.nextToken());
jo.put("HTTP-Version", x.nextToken()); jo.put("HTTP-Version", x.nextToken());
} }
// Fields // Fields
while (x.more()) { while (x.more()) {
String name = x.nextTo(':'); String name = x.nextTo(':');
x.next(':'); x.next(':');
jo.put(name, x.nextTo('\0')); jo.put(name, x.nextTo('\0'));
x.next(); x.next();
} }
return jo; return jo;
} }
/** /**
* Convert a JSONObject into an HTTP header. A request header must contain * Convert a JSONObject into an HTTP header. A request header must contain
* *
* <pre> * <pre>
* { * {
* Method: "POST" (for example), * Method: "POST" (for example),
* "Request-URI": "/" (for example), * "Request-URI": "/" (for example),
* "HTTP-Version": "HTTP/1.1" (for example) * "HTTP-Version": "HTTP/1.1" (for example)
* } * }
* </pre> * </pre>
* *
* A response header must contain * A response header must contain
* *
* <pre> * <pre>
* { * {
* "HTTP-Version": "HTTP/1.1" (for example), * "HTTP-Version": "HTTP/1.1" (for example),
* "Status-Code": "200" (for example), * "Status-Code": "200" (for example),
* "Reason-Phrase": "OK" (for example) * "Reason-Phrase": "OK" (for example)
* } * }
* </pre> * </pre>
* *
* Any other members of the JSONObject will be output as HTTP fields. The * Any other members of the JSONObject will be output as HTTP fields. The
* result will end with two CRLF pairs. * result will end with two CRLF pairs.
* *
* @param jo * @param jo
* A JSONObject * A JSONObject
* @return An HTTP header string. * @return An HTTP header string.
* @throws JSONException * @throws JSONException
* if the object does not contain enough information. * if the object does not contain enough information.
*/ */
public static String toString(JSONObject jo) throws JSONException { public static String toString(JSONObject jo) throws JSONException {
Iterator<?> keys = jo.keys(); Iterator<?> keys = jo.keys();
String string; String string;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {
sb.append(jo.getString("HTTP-Version")); sb.append(jo.getString("HTTP-Version"));
sb.append(' '); sb.append(' ');
sb.append(jo.getString("Status-Code")); sb.append(jo.getString("Status-Code"));
sb.append(' '); sb.append(' ');
sb.append(jo.getString("Reason-Phrase")); sb.append(jo.getString("Reason-Phrase"));
} else if (jo.has("Method") && jo.has("Request-URI")) { } else if (jo.has("Method") && jo.has("Request-URI")) {
sb.append(jo.getString("Method")); sb.append(jo.getString("Method"));
sb.append(' '); sb.append(' ');
sb.append('"'); sb.append('"');
sb.append(jo.getString("Request-URI")); sb.append(jo.getString("Request-URI"));
sb.append('"'); sb.append('"');
sb.append(' '); sb.append(' ');
sb.append(jo.getString("HTTP-Version")); sb.append(jo.getString("HTTP-Version"));
} else { } else {
throw new JSONException("Not enough material for an HTTP header."); throw new JSONException("Not enough material for an HTTP header.");
} }
sb.append(CRLF); sb.append(CRLF);
while (keys.hasNext()) { while (keys.hasNext()) {
string = keys.next().toString(); string = keys.next().toString();
if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string)
&& !"Reason-Phrase".equals(string) && !"Reason-Phrase".equals(string)
&& !"Method".equals(string) && !"Method".equals(string)
&& !"Request-URI".equals(string) && !jo.isNull(string)) { && !"Request-URI".equals(string) && !jo.isNull(string)) {
sb.append(string); sb.append(string);
sb.append(": "); sb.append(": ");
sb.append(jo.getString(string)); sb.append(jo.getString(string));
sb.append(CRLF); sb.append(CRLF);
} }
} }
sb.append(CRLF); sb.append(CRLF);
return sb.toString(); return sb.toString();
} }
} }
+1 -1
View File
@@ -22,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* The HTTPTokener extends the JSONTokener to provide additional methods * The HTTPTokener extends the JSONTokener to provide additional methods
+19 -19
View File
@@ -22,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
@@ -173,7 +173,7 @@ public class JSONArray {
} }
} else { } else {
throw new JSONException( throw new JSONException(
"JSONArray initial value should be a string or collection or array."); "JSONArray initial value should be a string or collection or array.");
} }
} }
@@ -207,11 +207,11 @@ public class JSONArray {
Object object = this.get(index); Object object = this.get(index);
if (object.equals(Boolean.FALSE) || if (object.equals(Boolean.FALSE) ||
(object instanceof String && (object instanceof String &&
((String)object).equalsIgnoreCase("false"))) { ((String)object).equalsIgnoreCase("false"))) {
return false; return false;
} else if (object.equals(Boolean.TRUE) || } else if (object.equals(Boolean.TRUE) ||
(object instanceof String && (object instanceof String &&
((String)object).equalsIgnoreCase("true"))) { ((String)object).equalsIgnoreCase("true"))) {
return true; return true;
} }
throw new JSONException("JSONArray[" + index + "] is not a boolean."); throw new JSONException("JSONArray[" + index + "] is not a boolean.");
@@ -230,11 +230,11 @@ public class JSONArray {
Object object = this.get(index); Object object = this.get(index);
try { try {
return object instanceof Number return object instanceof Number
? ((Number)object).doubleValue() ? ((Number)object).doubleValue()
: Double.parseDouble((String)object); : Double.parseDouble((String)object);
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONArray[" + index + throw new JSONException("JSONArray[" + index +
"] is not a number."); "] is not a number.");
} }
} }
@@ -250,11 +250,11 @@ public class JSONArray {
Object object = this.get(index); Object object = this.get(index);
try { try {
return object instanceof Number return object instanceof Number
? ((Number)object).intValue() ? ((Number)object).intValue()
: Integer.parseInt((String)object); : Integer.parseInt((String)object);
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONArray[" + index + throw new JSONException("JSONArray[" + index +
"] is not a number."); "] is not a number.");
} }
} }
@@ -289,7 +289,7 @@ public class JSONArray {
return (JSONObject)object; return (JSONObject)object;
} }
throw new JSONException("JSONArray[" + index + throw new JSONException("JSONArray[" + index +
"] is not a JSONObject."); "] is not a JSONObject.");
} }
@@ -305,11 +305,11 @@ public class JSONArray {
Object object = this.get(index); Object object = this.get(index);
try { try {
return object instanceof Number return object instanceof Number
? ((Number)object).longValue() ? ((Number)object).longValue()
: Long.parseLong((String)object); : Long.parseLong((String)object);
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONArray[" + index + throw new JSONException("JSONArray[" + index +
"] is not a number."); "] is not a number.");
} }
} }
@@ -379,8 +379,8 @@ public class JSONArray {
*/ */
public Object opt(int index) { public Object opt(int index) {
return (index < 0 || index >= this.length()) return (index < 0 || index >= this.length())
? null ? null
: this.myArrayList.get(index); : this.myArrayList.get(index);
} }
@@ -556,8 +556,8 @@ public class JSONArray {
public String optString(int index, String defaultValue) { public String optString(int index, String defaultValue) {
Object object = this.opt(index); Object object = this.opt(index);
return JSONObject.NULL.equals(object) return JSONObject.NULL.equals(object)
? defaultValue ? defaultValue
: object.toString(); : object.toString();
} }
@@ -900,7 +900,7 @@ public class JSONArray {
writer.write(']'); writer.write(']');
return writer; return writer;
} catch (IOException e) { } catch (IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
} }
} }
+126 -126
View File
@@ -22,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
@@ -97,22 +97,22 @@ public class JSONObject {
/** /**
* The maximum number of keys in the key pool. * The maximum number of keys in the key pool.
*/ */
private static final int keyPoolSize = 100; private static final int keyPoolSize = 100;
/** /**
* Key pooling is like string interning, but without permanently tying up * Key pooling is like string interning, but without permanently tying up
* memory. To help conserve memory, storage of duplicated key strings in * memory. To help conserve memory, storage of duplicated key strings in
* JSONObjects will be avoided by using a key pool to manage unique key * JSONObjects will be avoided by using a key pool to manage unique key
* string objects. This is used by JSONObject.put(string, object). * string objects. This is used by JSONObject.put(string, object).
*/ */
private static HashMap keyPool = new HashMap(keyPoolSize); private static HashMap keyPool = new HashMap(keyPoolSize);
/** /**
* JSONObject.NULL is equivalent to the value that JavaScript calls null, * JSONObject.NULL is equivalent to the value that JavaScript calls null,
* whilst Java's null is equivalent to the value that JavaScript calls * whilst Java's null is equivalent to the value that JavaScript calls
* undefined. * undefined.
*/ */
private static final class Null { private static final class Null {
/** /**
* There is only intended to be a single instance of the NULL object, * There is only intended to be a single instance of the NULL object,
@@ -212,7 +212,7 @@ public class JSONObject {
key = x.nextValue().toString(); key = x.nextValue().toString();
} }
// The key is followed by ':'. We will also tolerate '=' or '=>'. // The key is followed by ':'. We will also tolerate '=' or '=>'.
c = x.nextClean(); c = x.nextClean();
if (c == '=') { if (c == '=') {
@@ -224,7 +224,7 @@ public class JSONObject {
} }
this.putOnce(key, x.nextValue()); this.putOnce(key, x.nextValue());
// Pairs are separated by ','. We will also tolerate ';'. // Pairs are separated by ','. We will also tolerate ';'.
switch (x.nextClean()) { switch (x.nextClean()) {
case ';': case ';':
@@ -339,16 +339,16 @@ public class JSONObject {
ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
Thread.currentThread().getContextClassLoader()); Thread.currentThread().getContextClassLoader());
// Iterate through the keys in the bundle. // Iterate through the keys in the bundle.
Enumeration keys = bundle.getKeys(); Enumeration keys = bundle.getKeys();
while (keys.hasMoreElements()) { while (keys.hasMoreElements()) {
Object key = keys.nextElement(); Object key = keys.nextElement();
if (key instanceof String) { if (key instanceof String) {
// Go through the path, ensuring that there is a nested JSONObject for each // Go through the path, ensuring that there is a nested JSONObject for each
// segment except the last. Add the value using the last segment's name into // segment except the last. Add the value using the last segment's name into
// the deepest nested JSONObject. // the deepest nested JSONObject.
String[] path = ((String)key).split("\\."); String[] path = ((String)key).split("\\.");
int last = path.length - 1; int last = path.length - 1;
@@ -385,15 +385,15 @@ public class JSONObject {
* or if the key is null. * or if the key is null.
*/ */
public JSONObject accumulate( public JSONObject accumulate(
String key, String key,
Object value Object value
) throws JSONException { ) throws JSONException {
testValidity(value); testValidity(value);
Object object = this.opt(key); Object object = this.opt(key);
if (object == null) { if (object == null) {
this.put(key, value instanceof JSONArray this.put(key, value instanceof JSONArray
? new JSONArray().put(value) ? new JSONArray().put(value)
: value); : value);
} else if (object instanceof JSONArray) { } else if (object instanceof JSONArray) {
((JSONArray)object).put(value); ((JSONArray)object).put(value);
} else { } else {
@@ -440,7 +440,7 @@ public class JSONObject {
return "null"; return "null";
} }
// Shave off trailing zeros and decimal point, if possible. // Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d); String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
@@ -488,11 +488,11 @@ public class JSONObject {
Object object = this.get(key); Object object = this.get(key);
if (object.equals(Boolean.FALSE) || if (object.equals(Boolean.FALSE) ||
(object instanceof String && (object instanceof String &&
((String)object).equalsIgnoreCase("false"))) { ((String)object).equalsIgnoreCase("false"))) {
return false; return false;
} else if (object.equals(Boolean.TRUE) || } else if (object.equals(Boolean.TRUE) ||
(object instanceof String && (object instanceof String &&
((String)object).equalsIgnoreCase("true"))) { ((String)object).equalsIgnoreCase("true"))) {
return true; return true;
} }
throw new JSONException("JSONObject[" + quote(key) + throw new JSONException("JSONObject[" + quote(key) +
@@ -511,11 +511,11 @@ public class JSONObject {
Object object = this.get(key); Object object = this.get(key);
try { try {
return object instanceof Number return object instanceof Number
? ((Number)object).doubleValue() ? ((Number)object).doubleValue()
: Double.parseDouble((String)object); : Double.parseDouble((String)object);
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) + throw new JSONException("JSONObject[" + quote(key) +
"] is not a number."); "] is not a number.");
} }
} }
@@ -532,11 +532,11 @@ public class JSONObject {
Object object = this.get(key); Object object = this.get(key);
try { try {
return object instanceof Number return object instanceof Number
? ((Number)object).intValue() ? ((Number)object).intValue()
: Integer.parseInt((String)object); : Integer.parseInt((String)object);
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) + throw new JSONException("JSONObject[" + quote(key) +
"] is not an int."); "] is not an int.");
} }
} }
@@ -589,11 +589,11 @@ public class JSONObject {
Object object = this.get(key); Object object = this.get(key);
try { try {
return object instanceof Number return object instanceof Number
? ((Number)object).longValue() ? ((Number)object).longValue()
: Long.parseLong((String)object); : Long.parseLong((String)object);
} catch (Exception e) { } catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) + throw new JSONException("JSONObject[" + quote(key) +
"] is not a long."); "] is not a long.");
} }
} }
@@ -655,7 +655,7 @@ public class JSONObject {
return (String)object; return (String)object;
} }
throw new JSONException("JSONObject[" + quote(key) + throw new JSONException("JSONObject[" + quote(key) +
"] not a string."); "] not a string.");
} }
@@ -767,7 +767,7 @@ public class JSONObject {
} }
testValidity(number); testValidity(number);
// Shave off trailing zeros and decimal point, if possible. // Shave off trailing zeros and decimal point, if possible.
String string = number.toString(); String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
@@ -981,48 +981,48 @@ public class JSONObject {
private void populateMap(Object bean) { private void populateMap(Object bean) {
Class klass = bean.getClass(); Class klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false. // If klass is a System class then set includeSuperClass to false.
boolean includeSuperClass = klass.getClassLoader() != null; boolean includeSuperClass = klass.getClassLoader() != null;
Method[] methods = includeSuperClass Method[] methods = includeSuperClass
? klass.getMethods() ? klass.getMethods()
: klass.getDeclaredMethods(); : klass.getDeclaredMethods();
for (int i = 0; i < methods.length; i += 1) { for (int i = 0; i < methods.length; i += 1) {
try { try {
Method method = methods[i]; Method method = methods[i];
if (Modifier.isPublic(method.getModifiers())) { if (Modifier.isPublic(method.getModifiers())) {
String name = method.getName(); String name = method.getName();
String key = ""; String key = "";
if (name.startsWith("get")) { if (name.startsWith("get")) {
if ("getClass".equals(name) || if ("getClass".equals(name) ||
"getDeclaringClass".equals(name)) { "getDeclaringClass".equals(name)) {
key = ""; key = "";
} else { } else {
key = name.substring(3); key = name.substring(3);
} }
} else if (name.startsWith("is")) { } else if (name.startsWith("is")) {
key = name.substring(2); key = name.substring(2);
} }
if (key.length() > 0 && if (key.length() > 0 &&
Character.isUpperCase(key.charAt(0)) && Character.isUpperCase(key.charAt(0)) &&
method.getParameterTypes().length == 0) { method.getParameterTypes().length == 0) {
if (key.length() == 1) { if (key.length() == 1) {
key = key.toLowerCase(); key = key.toLowerCase();
} else if (!Character.isUpperCase(key.charAt(1))) { } else if (!Character.isUpperCase(key.charAt(1))) {
key = key.substring(0, 1).toLowerCase() + key = key.substring(0, 1).toLowerCase() +
key.substring(1); key.substring(1);
} }
Object result = method.invoke(bean, (Object[])null); Object result = method.invoke(bean, (Object[])null);
if (result != null) { if (result != null) {
this.map.put(key, wrap(result)); this.map.put(key, wrap(result));
}
}
} }
} catch (Exception ignore) {
} }
} }
} catch (Exception ignore) {
}
}
} }
@@ -1335,12 +1335,12 @@ public class JSONObject {
if (o instanceof Double) { if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException( throw new JSONException(
"JSON does not allow non-finite numbers."); "JSON does not allow non-finite numbers.");
} }
} else if (o instanceof Float) { } else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException( throw new JSONException(
"JSON does not allow non-finite numbers."); "JSON does not allow non-finite numbers.");
} }
} }
} }
@@ -1462,70 +1462,70 @@ public class JSONObject {
return quote(value.toString()); return quote(value.toString());
} }
/** /**
* Wrap an object, if necessary. If the object is null, return the NULL * Wrap an object, if necessary. If the object is null, return the NULL
* object. If it is an array or collection, wrap it in a JSONArray. If * object. If it is an array or collection, wrap it in a JSONArray. If
* it is a map, wrap it in a JSONObject. If it is a standard property * it is a map, wrap it in a JSONObject. If it is a standard property
* (Double, String, et al) then it is already wrapped. Otherwise, if it * (Double, String, et al) then it is already wrapped. Otherwise, if it
* comes from one of the java packages, turn it into a string. And if * comes from one of the java packages, turn it into a string. And if
* it doesn't, try to wrap it in a JSONObject. If the wrapping fails, * it doesn't, try to wrap it in a JSONObject. If the wrapping fails,
* then null is returned. * then null is returned.
* *
* @param object The object to wrap * @param object The object to wrap
* @return The wrapped value * @return The wrapped value
*/ */
public static Object wrap(Object object) { public static Object wrap(Object object) {
try { try {
if (object == null) { if (object == null) {
return NULL; return NULL;
} }
if (object instanceof JSONObject || object instanceof JSONArray || if (object instanceof JSONObject || object instanceof JSONArray ||
NULL.equals(object) || object instanceof JSONString || NULL.equals(object) || object instanceof JSONString ||
object instanceof Byte || object instanceof Character || object instanceof Byte || object instanceof Character ||
object instanceof Short || object instanceof Integer || object instanceof Short || object instanceof Integer ||
object instanceof Long || object instanceof Boolean || object instanceof Long || object instanceof Boolean ||
object instanceof Float || object instanceof Double || object instanceof Float || object instanceof Double ||
object instanceof String) { object instanceof String) {
return object; return object;
} }
if (object instanceof Collection) { if (object instanceof Collection) {
return new JSONArray((Collection)object); return new JSONArray((Collection)object);
} }
if (object.getClass().isArray()) { if (object.getClass().isArray()) {
return new JSONArray(object); return new JSONArray(object);
} }
if (object instanceof Map) { if (object instanceof Map) {
return new JSONObject((Map)object); return new JSONObject((Map)object);
} }
Package objectPackage = object.getClass().getPackage(); Package objectPackage = object.getClass().getPackage();
String objectPackageName = objectPackage != null String objectPackageName = objectPackage != null
? objectPackage.getName() ? objectPackage.getName()
: ""; : "";
if ( if (
objectPackageName.startsWith("java.") || objectPackageName.startsWith("java.") ||
objectPackageName.startsWith("javax.") || objectPackageName.startsWith("javax.") ||
object.getClass().getClassLoader() == null object.getClass().getClassLoader() == null
) { ) {
return object.toString(); return object.toString();
} }
return new JSONObject(object); return new JSONObject(object);
} catch(Exception exception) { } catch(Exception exception) {
return null; return null;
} }
} }
/** /**
* Write the contents of the JSONObject as JSON text to a writer. * Write the contents of the JSONObject as JSON text to a writer.
* For compactness, no whitespace is added. * For compactness, no whitespace is added.
* <p> * <p>
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @return The writer. * @return The writer.
* @throws JSONException * @throws JSONException
*/ */
public Writer write(Writer writer) throws JSONException { public Writer write(Writer writer) throws JSONException {
return this.write(writer, 0, 0); return this.write(writer, 0, 0);
} }
@@ -1624,5 +1624,5 @@ public class JSONObject {
} catch (IOException exception) { } catch (IOException exception) {
throw new JSONException(exception); throw new JSONException(exception);
} }
} }
} }
+1 -1
View File
@@ -22,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import java.io.StringWriter; import java.io.StringWriter;
+28 -28
View File
@@ -29,7 +29,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* A JSONTokener takes a source string and extracts characters and tokens from * A JSONTokener takes a source string and extracts characters and tokens from
@@ -56,8 +56,8 @@ public class JSONTokener {
*/ */
public JSONTokener(Reader reader) { public JSONTokener(Reader reader) {
this.reader = reader.markSupported() this.reader = reader.markSupported()
? reader ? reader
: new BufferedReader(reader); : new BufferedReader(reader);
this.eof = false; this.eof = false;
this.usePrevious = false; this.usePrevious = false;
this.previous = 0; this.previous = 0;
@@ -203,23 +203,23 @@ public class JSONTokener {
* Substring bounds error if there are not * Substring bounds error if there are not
* n characters remaining in the source string. * n characters remaining in the source string.
*/ */
public String next(int n) throws JSONException { public String next(int n) throws JSONException {
if (n == 0) { if (n == 0) {
return ""; return "";
} }
char[] chars = new char[n]; char[] chars = new char[n];
int pos = 0; int pos = 0;
while (pos < n) { while (pos < n) {
chars[pos] = this.next(); chars[pos] = this.next();
if (this.end()) { if (this.end()) {
throw this.syntaxError("Substring bounds error"); throw this.syntaxError("Substring bounds error");
} }
pos += 1; pos += 1;
} }
return new String(chars); return new String(chars);
} }
/** /**
@@ -355,15 +355,15 @@ public class JSONTokener {
String string; String string;
switch (c) { switch (c) {
case '"': case '"':
case '\'': case '\'':
return this.nextString(c); return this.nextString(c);
case '{': case '{':
this.back(); this.back();
return new JSONObject(this); return new JSONObject(this);
case '[': case '[':
this.back(); this.back();
return new JSONArray(this); return new JSONArray(this);
} }
/* /*
@@ -441,6 +441,6 @@ public class JSONTokener {
*/ */
public String toString() { public String toString() {
return " at " + this.index + " [character " + this.character + " line " + return " at " + this.index + " [character " + this.character + " line " +
this.line + "]"; this.line + "]";
} }
} }
+7 -7
View File
@@ -25,7 +25,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
/** /**
* JSONWriter provides a quick and convenient way of producing JSON text. * JSONWriter provides a quick and convenient way of producing JSON text.
@@ -158,8 +158,8 @@ public class JSONWriter {
private JSONWriter end(char mode, char c) throws JSONException { private JSONWriter end(char mode, char c) throws JSONException {
if (this.mode != mode) { if (this.mode != mode) {
throw new JSONException(mode == 'a' throw new JSONException(mode == 'a'
? "Misplaced endArray." ? "Misplaced endArray."
: "Misplaced endObject."); : "Misplaced endObject.");
} }
this.pop(mode); this.pop(mode);
try { try {
@@ -261,10 +261,10 @@ public class JSONWriter {
} }
this.top -= 1; this.top -= 1;
this.mode = this.top == 0 this.mode = this.top == 0
? 'd' ? 'd'
: this.stack[this.top - 1] == null : this.stack[this.top - 1] == null
? 'a' ? 'a'
: 'k'; : 'k';
} }
/** /**