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