drtshock loves formatting, so I may as well

This commit is contained in:
gomeow
2013-04-12 10:54:25 -07:00
parent 678f61127e
commit 03a7b52a8e
22 changed files with 677 additions and 793 deletions
@@ -46,7 +46,7 @@ public class Listeners implements Listener {
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());
@@ -127,7 +127,7 @@ public class Listeners implements Listener {
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);
} }
} }
@@ -46,7 +46,7 @@ public class Main extends JavaPlugin {
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();
@@ -72,7 +72,7 @@ public class Main extends JavaPlugin {
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();
} }
} }
@@ -119,7 +119,7 @@ public class Main extends JavaPlugin {
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();
} }
} }
@@ -141,7 +141,7 @@ public class Main extends JavaPlugin {
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");
@@ -57,7 +57,7 @@ public class Commands implements CommandExecutor {
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);
@@ -4,12 +4,11 @@ import org.bukkit.command.CommandSender;
import com.drtshock.playervaults.util.Lang; 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;
} }
@@ -16,10 +16,9 @@ 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;
@@ -39,8 +38,7 @@ public class VaultOperations {
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;
} }
@@ -78,8 +76,7 @@ public class VaultOperations {
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);
@@ -109,8 +106,7 @@ public class VaultOperations {
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 {
@@ -118,11 +114,11 @@ public class VaultOperations {
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);
} }
} }
@@ -143,13 +139,12 @@ public class VaultOperations {
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 {
@@ -10,6 +10,7 @@ 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;
} }
@@ -26,7 +27,7 @@ public class DropOnDeath {
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);
} }
} }
@@ -25,6 +25,7 @@ public class EconomyOperations {
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.
@@ -32,7 +33,7 @@ public class EconomyOperations {
* @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);
@@ -44,6 +45,7 @@ public class EconomyOperations {
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.
@@ -51,7 +53,7 @@ public class EconomyOperations {
* @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);
@@ -79,7 +81,7 @@ public class EconomyOperations {
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;
} }
@@ -6,12 +6,12 @@ package com.drtshock.playervaults.util;
* Redistribution and use in source and binary forms, with or without modification, are * Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met: * permitted provided that the following conditions are met:
* *
* 1. Redistributions of source code must retain the above copyright notice, this list of * 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer. * conditions and the following disclaimer.
* *
* 2. Redistributions in binary form must reproduce the above copyright notice, this list * 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials * of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution. * provided with the distribution.
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
@@ -134,7 +134,7 @@ public class Metrics {
private volatile int taskId = -1; private volatile int taskId = -1;
public Metrics(final Plugin plugin) throws IOException { public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) { if(plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null"); throw new IllegalArgumentException("Plugin cannot be null");
} }
@@ -149,7 +149,7 @@ public class Metrics {
configuration.addDefault("guid", UUID.randomUUID().toString()); configuration.addDefault("guid", UUID.randomUUID().toString());
// Do we need to create the file? // Do we need to create the file?
if (configuration.get("guid", null) == null) { if(configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true); configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile); configuration.save(configurationFile);
} }
@@ -166,7 +166,7 @@ public class Metrics {
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/ */
public Graph createGraph(final String name) { public Graph createGraph(final String name) {
if (name == null) { if(name == null) {
throw new IllegalArgumentException("Graph name cannot be null"); throw new IllegalArgumentException("Graph name cannot be null");
} }
@@ -186,7 +186,7 @@ public class Metrics {
* @param graph The name of the graph * @param graph The name of the graph
*/ */
public void addGraph(final Graph graph) { public void addGraph(final Graph graph) {
if (graph == null) { if(graph == null) {
throw new IllegalArgumentException("Graph cannot be null"); throw new IllegalArgumentException("Graph cannot be null");
} }
@@ -199,7 +199,7 @@ public class Metrics {
* @param plotter The plotter to use to plot custom data * @param plotter The plotter to use to plot custom data
*/ */
public void addCustomData(final Plotter plotter) { public void addCustomData(final Plotter plotter) {
if (plotter == null) { if(plotter == null) {
throw new IllegalArgumentException("Plotter cannot be null"); throw new IllegalArgumentException("Plotter cannot be null");
} }
@@ -221,12 +221,12 @@ public class Metrics {
public boolean start() { public boolean start() {
synchronized (optOutLock) { synchronized (optOutLock) {
// Did we opt out? // Did we opt out?
if (isOptOut()) { if(isOptOut()) {
return false; return false;
} }
// Is metrics already running? // Is metrics already running?
if (taskId >= 0) { if(taskId >= 0) {
return true; return true;
} }
@@ -239,18 +239,20 @@ public class Metrics {
try { try {
// This has to be synchronized or it can collide with the disable method. // This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) { synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out // Disable Task, if it is running and the server owner decided to
if (isOptOut() && taskId > 0) { // opt-out
if(isOptOut() && taskId > 0) {
plugin.getServer().getScheduler().cancelTask(taskId); plugin.getServer().getScheduler().cancelTask(taskId);
taskId = -1; taskId = -1;
// Tell all plotters to stop gathering information. // Tell all plotters to stop gathering information.
for (Graph graph : graphs){ for(Graph graph:graphs) {
graph.onOptOut(); graph.onOptOut();
} }
} }
} }
// We use the inverse of firstPost because if it is the first time we are posting, // We use the inverse of firstPost because if it is the first time we are
// posting,
// it is not a interval ping, so it evaluates to FALSE // it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING! // Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost); postPlugin(!firstPost);
@@ -258,7 +260,7 @@ public class Metrics {
// After the first post we set firstPost to false // After the first post we set firstPost to false
// Each post thereafter will be a ping // Each post thereafter will be a ping
firstPost = false; firstPost = false;
} catch (IOException e) { } catch(IOException e) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
} }
} }
@@ -274,14 +276,14 @@ public class Metrics {
* @return true if metrics should be opted out of it * @return true if metrics should be opted out of it
*/ */
public boolean isOptOut() { public boolean isOptOut() {
synchronized(optOutLock) { synchronized (optOutLock) {
try { try {
// Reload the metrics file // Reload the metrics file
configuration.load(getConfigFile()); configuration.load(getConfigFile());
} catch (IOException ex) { } catch(IOException ex) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
return true; return true;
} catch (InvalidConfigurationException ex) { } catch(InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
return true; return true;
} }
@@ -298,13 +300,13 @@ public class Metrics {
// 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();
} }
} }
@@ -319,13 +321,13 @@ public class Metrics {
// 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", true); configuration.set("opt-out", true);
configuration.save(configurationFile); configuration.save(configurationFile);
} }
// Disable Task, if it is running // Disable Task, if it is running
if (taskId > 0) { if(taskId > 0) {
this.plugin.getServer().getScheduler().cancelTask(taskId); this.plugin.getServer().getScheduler().cancelTask(taskId);
taskId = -1; taskId = -1;
} }
@@ -338,7 +340,8 @@ public class Metrics {
* @return the File object for the config file * @return the File object for the config file
*/ */
public File getConfigFile() { public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins
// to use
// is to abuse the plugin object we already have // is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/ // plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/ // pluginsFolder => base/plugins/
@@ -353,7 +356,8 @@ public class Metrics {
* Generic method that posts a plugin to the metrics website * Generic method that posts a plugin to the metrics website
*/ */
private void postPlugin(final boolean isPing) throws IOException { private void postPlugin(final boolean isPing) throws IOException {
// The plugin's description file containg all of the plugin data such as name, version, author, etc // The plugin's description file containg all of the plugin data such as name, version,
// author, etc
final PluginDescriptionFile description = plugin.getDescription(); final PluginDescriptionFile description = plugin.getDescription();
// Construct the post data // Construct the post data
@@ -365,7 +369,7 @@ public class Metrics {
encodeDataPair(data, "revision", String.valueOf(REVISION)); encodeDataPair(data, "revision", String.valueOf(REVISION));
// If we're pinging, append it // If we're pinging, append it
if (isPing) { if(isPing) {
encodeDataPair(data, "ping", "true"); encodeDataPair(data, "ping", "true");
} }
@@ -377,7 +381,7 @@ public class Metrics {
while (iter.hasNext()) { while (iter.hasNext()) {
final Graph graph = iter.next(); final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) { for(Plotter plotter:graph.getPlotters()) {
// The key name to send to the metrics server // The key name to send to the metrics server
// The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top
// Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME
@@ -401,7 +405,7 @@ public class Metrics {
// Mineshafter creates a socks proxy, so we can safely bypass it // Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it // It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) { if(isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY); connection = url.openConnection(Proxy.NO_PROXY);
} else { } else {
connection = url.openConnection(); connection = url.openConnection();
@@ -422,18 +426,18 @@ public class Metrics {
writer.close(); writer.close();
reader.close(); reader.close();
if (response == null || response.startsWith("ERR")) { if(response == null || response.startsWith("ERR")) {
throw new IOException(response); //Throw the exception throw new IOException(response); // Throw the exception
} else { } else {
// Is this the first update this hour? // Is this the first update this hour?
if (response.contains("OK This is your first update this hour")) { if(response.contains("OK This is your first update this hour")) {
synchronized (graphs) { synchronized (graphs) {
final Iterator<Graph> iter = graphs.iterator(); final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
final Graph graph = iter.next(); final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) { for(Plotter plotter:graph.getPlotters()) {
plotter.reset(); plotter.reset();
} }
} }
@@ -451,7 +455,7 @@ public class Metrics {
try { try {
Class.forName("mineshafter.MineServer"); Class.forName("mineshafter.MineServer");
return true; return true;
} catch (Exception e) { } catch(Exception e) {
return false; return false;
} }
} }
@@ -546,7 +550,7 @@ public class Metrics {
@Override @Override
public boolean equals(final Object object) { public boolean equals(final Object object) {
if (!(object instanceof Graph)) { if(!(object instanceof Graph)) {
return false; return false;
} }
@@ -620,7 +624,7 @@ public class Metrics {
@Override @Override
public boolean equals(final Object object) { public boolean equals(final Object object) {
if (!(object instanceof Plotter)) { if(!(object instanceof Plotter)) {
return false; return false;
} }
@@ -631,4 +635,3 @@ public class Metrics {
} }
} }
@@ -33,12 +33,13 @@ 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) {
return toMap((JSONObject) json); return toMap((JSONObject) json);
} else if (json instanceof JSONArray) { } else if(json instanceof JSONArray) {
return toList((JSONArray) json); return toList((JSONArray) json);
} else { } else {
return json; return json;
@@ -47,7 +48,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)));
} }
return list; return list;
@@ -81,7 +82,7 @@ public class Serialization {
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();
} }
} }
@@ -95,17 +96,18 @@ public class Serialization {
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());
for (Entry<String, Object> entry : serialized.entrySet()) { for(Entry<String, Object> entry:serialized.entrySet()) {
if (entry.getValue() instanceof ConfigurationSerializable) { if(entry.getValue() instanceof ConfigurationSerializable) {
entry.setValue(serialize((ConfigurationSerializable)entry.getValue())); entry.setValue(serialize((ConfigurationSerializable) entry.getValue()));
} }
} }
serialized.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(cs.getClass())); serialized.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(cs.getClass()));
return serialized; return serialized;
} }
public static Map<String, Object> recreateMap(Map<String, Object> original) { public static Map<String, Object> recreateMap(Map<String, Object> original) {
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
for (Entry<String, Object> entry : original.entrySet()) { for(Entry<String, Object> entry:original.entrySet()) {
map.put(entry.getKey(), entry.getValue()); map.put(entry.getKey(), entry.getValue());
} }
return map; return map;
@@ -113,10 +115,11 @@ public class Serialization {
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public static ConfigurationSerializable deserialize(Map<String, Object> map) { public static ConfigurationSerializable deserialize(Map<String, Object> map) {
for (Entry<String, Object> entry : map.entrySet()) { for(Entry<String, Object> entry:map.entrySet()) {
// Check if any of its sub-maps are ConfigurationSerializable. They need to be done first. // Check if any of its sub-maps are ConfigurationSerializable. They need to be done
if (entry.getValue() instanceof Map && ((Map)entry.getValue()).containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { // first.
entry.setValue(deserialize((Map)entry.getValue())); if(entry.getValue() instanceof Map && ((Map) entry.getValue()).containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
entry.setValue(deserialize((Map) entry.getValue()));
} }
} }
return ConfigurationSerialization.deserializeObject(map); return ConfigurationSerialization.deserializeObject(map);
@@ -28,7 +28,7 @@ public class Updater extends Main {
} }
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();
@@ -40,34 +40,47 @@ public class Updater extends Main {
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;
@@ -18,6 +18,7 @@ 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;
} }
@@ -128,7 +129,7 @@ public class VaultManager {
if(!file.exists()) { if(!file.exists()) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch(IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -144,7 +145,7 @@ public class VaultManager {
*/ */
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);
+47 -48
View File
@@ -1,27 +1,27 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org * Copyright (c) 2002 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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.
*/ */
/** /**
@@ -66,12 +66,12 @@ public class CDL {
case '\'': case '\'':
q = c; q = c;
sb = new StringBuffer(); sb = new StringBuffer();
for (;;) { for(;;) {
c = x.next(); c = x.next();
if (c == q) { if(c == q) {
break; break;
} }
if (c == 0 || c == '\n' || c == '\r') { if(c == 0 || c == '\n' || c == '\r') {
throw x.syntaxError("Missing close quote '" + q + "'."); throw x.syntaxError("Missing close quote '" + q + "'.");
} }
sb.append(c); sb.append(c);
@@ -94,24 +94,24 @@ public class CDL {
*/ */
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
JSONArray ja = new JSONArray(); JSONArray ja = new JSONArray();
for (;;) { for(;;) {
String value = getValue(x); String value = getValue(x);
char c = x.next(); char c = x.next();
if (value == null || if(value == null ||
(ja.length() == 0 && value.length() == 0 && c != ',')) { (ja.length() == 0 && value.length() == 0 && c != ',')) {
return null; return null;
} }
ja.put(value); ja.put(value);
for (;;) { for(;;) {
if (c == ',') { if(c == ',') {
break; break;
} }
if (c != ' ') { if(c != ' ') {
if (c == '\n' || c == '\r' || c == 0) { if(c == '\n' || c == '\r' || c == 0) {
return ja; return ja;
} }
throw x.syntaxError("Bad character '" + c + "' (" + throw x.syntaxError("Bad character '" + c + "' (" +
(int)c + ")."); (int) c + ").");
} }
c = x.next(); c = x.next();
} }
@@ -131,7 +131,7 @@ public class CDL {
public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
throws JSONException { throws JSONException {
JSONArray ja = rowToJSONArray(x); JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null; return ja != null ? ja.toJSONObject(names) : null;
} }
/** /**
@@ -143,21 +143,21 @@ public class CDL {
*/ */
public static String rowToString(JSONArray ja) { public static String rowToString(JSONArray ja) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < ja.length(); i += 1) { for(int i = 0; i < ja.length(); i += 1) {
if (i > 0) { if(i > 0) {
sb.append(','); sb.append(',');
} }
Object object = ja.opt(i); Object object = ja.opt(i);
if (object != null) { if(object != null) {
String string = object.toString(); String string = object.toString();
if (string.length() > 0 && (string.indexOf(',') >= 0 || if(string.length() > 0 && (string.indexOf(',') >= 0 ||
string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
string.indexOf(0) >= 0 || string.charAt(0) == '"')) { string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
sb.append('"'); sb.append('"');
int length = string.length(); int length = string.length();
for (int j = 0; j < length; j += 1) { for(int j = 0; j < length; j += 1) {
char c = string.charAt(j); char c = string.charAt(j);
if (c >= ' ' && c != '"') { if(c >= ' ' && c != '"') {
sb.append(c); sb.append(c);
} }
} }
@@ -216,24 +216,23 @@ public class CDL {
*/ */
public static JSONArray toJSONArray(JSONArray names, JSONTokener x) public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
throws JSONException { throws JSONException {
if (names == null || names.length() == 0) { if(names == null || names.length() == 0) {
return null; return null;
} }
JSONArray ja = new JSONArray(); JSONArray ja = new JSONArray();
for (;;) { for(;;) {
JSONObject jo = rowToJSONObject(names, x); JSONObject jo = rowToJSONObject(names, x);
if (jo == null) { if(jo == null) {
break; break;
} }
ja.put(jo); ja.put(jo);
} }
if (ja.length() == 0) { if(ja.length() == 0) {
return null; return null;
} }
return ja; return ja;
} }
/** /**
* Produce a comma delimited text from a JSONArray of JSONObjects. The * Produce a comma delimited text from a JSONArray of JSONObjects. The
* first row will be a list of names obtained by inspecting the first * first row will be a list of names obtained by inspecting the first
@@ -244,9 +243,9 @@ public class CDL {
*/ */
public static String toString(JSONArray ja) throws JSONException { public static String toString(JSONArray ja) throws JSONException {
JSONObject jo = ja.optJSONObject(0); JSONObject jo = ja.optJSONObject(0);
if (jo != null) { if(jo != null) {
JSONArray names = jo.names(); JSONArray names = jo.names();
if (names != null) { if(names != null) {
return rowToString(names) + toString(names, ja); return rowToString(names) + toString(names, ja);
} }
} }
@@ -264,13 +263,13 @@ public class CDL {
*/ */
public static String toString(JSONArray names, JSONArray ja) public static String toString(JSONArray names, JSONArray ja)
throws JSONException { throws JSONException {
if (names == null || names.length() == 0) { if(names == null || names.length() == 0) {
return null; return null;
} }
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < ja.length(); i += 1) { for(int i = 0; i < ja.length(); i += 1) {
JSONObject jo = ja.optJSONObject(i); JSONObject jo = ja.optJSONObject(i);
if (jo != null) { if(jo != null) {
sb.append(rowToString(jo.toJSONArray(names))); sb.append(rowToString(jo.toJSONArray(names)));
} }
} }
+42 -44
View File
@@ -1,27 +1,27 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org * Copyright (c) 2002 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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.
*/ */
/** /**
@@ -45,16 +45,16 @@ public class Cookie {
* @return The escaped result. * @return The escaped result.
*/ */
public static String escape(String string) { public static String escape(String string) {
char c; char c;
String s = string.trim(); String s = string.trim();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
int length = s.length(); int length = s.length();
for (int i = 0; i < length; i += 1) { for(int i = 0; i < length; i += 1) {
c = s.charAt(i); c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { if(c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%'); sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16)); sb.append(Character.forDigit((char) (c & 0x0f), 16));
} else { } else {
sb.append(c); sb.append(c);
} }
@@ -62,7 +62,6 @@ public class Cookie {
return sb.toString(); return sb.toString();
} }
/** /**
* Convert a cookie specification string into a JSONObject. The string * Convert a cookie specification string into a JSONObject. The string
* will contain a name value pair separated by '='. The name and the value * will contain a name value pair separated by '='. The name and the value
@@ -79,9 +78,9 @@ public class Cookie {
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(String string) throws JSONException {
String name; String name;
JSONObject jo = new JSONObject(); JSONObject jo = new JSONObject();
Object value; Object value;
JSONTokener x = new JSONTokener(string); JSONTokener x = new JSONTokener(string);
jo.put("name", x.nextTo('=')); jo.put("name", x.nextTo('='));
x.next('='); x.next('=');
@@ -89,8 +88,8 @@ public class Cookie {
x.next(); x.next();
while (x.more()) { while (x.more()) {
name = unescape(x.nextTo("=;")); name = unescape(x.nextTo("=;"));
if (x.next() != '=') { if(x.next() != '=') {
if (name.equals("secure")) { if(name.equals("secure")) {
value = Boolean.TRUE; value = Boolean.TRUE;
} else { } else {
throw x.syntaxError("Missing '=' in cookie parameter."); throw x.syntaxError("Missing '=' in cookie parameter.");
@@ -104,7 +103,6 @@ public class Cookie {
return jo; return jo;
} }
/** /**
* Convert a JSONObject into a cookie specification string. The JSONObject * Convert a JSONObject into a cookie specification string. The JSONObject
* must contain "name" and "value" members. * must contain "name" and "value" members.
@@ -121,19 +119,19 @@ public class Cookie {
sb.append(escape(jo.getString("name"))); sb.append(escape(jo.getString("name")));
sb.append("="); sb.append("=");
sb.append(escape(jo.getString("value"))); sb.append(escape(jo.getString("value")));
if (jo.has("expires")) { if(jo.has("expires")) {
sb.append(";expires="); sb.append(";expires=");
sb.append(jo.getString("expires")); sb.append(jo.getString("expires"));
} }
if (jo.has("domain")) { if(jo.has("domain")) {
sb.append(";domain="); sb.append(";domain=");
sb.append(escape(jo.getString("domain"))); sb.append(escape(jo.getString("domain")));
} }
if (jo.has("path")) { if(jo.has("path")) {
sb.append(";path="); sb.append(";path=");
sb.append(escape(jo.getString("path"))); sb.append(escape(jo.getString("path")));
} }
if (jo.optBoolean("secure")) { if(jo.optBoolean("secure")) {
sb.append(";secure"); sb.append(";secure");
} }
return sb.toString(); return sb.toString();
@@ -150,15 +148,15 @@ public class Cookie {
public static String unescape(String string) { public static String unescape(String string) {
int length = string.length(); int length = string.length();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) { for(int i = 0; i < length; ++i) {
char c = string.charAt(i); char c = string.charAt(i);
if (c == '+') { if(c == '+') {
c = ' '; c = ' ';
} else if (c == '%' && i + 2 < length) { } else if(c == '%' && i + 2 < length) {
int d = JSONTokener.dehexchar(string.charAt(i + 1)); int d = JSONTokener.dehexchar(string.charAt(i + 1));
int e = JSONTokener.dehexchar(string.charAt(i + 2)); int e = JSONTokener.dehexchar(string.charAt(i + 2));
if (d >= 0 && e >= 0) { if(d >= 0 && e >= 0) {
c = (char)(d * 16 + e); c = (char) (d * 16 + e);
i += 2; i += 2;
} }
} }
+26 -27
View File
@@ -1,27 +1,27 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org * Copyright (c) 2002 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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;
@@ -58,7 +58,6 @@ public class CookieList {
return jo; return jo;
} }
/** /**
* Convert a JSONObject into a cookie list. A cookie list is a sequence * Convert a JSONObject into a cookie list. A cookie list is a sequence
* of name/value pairs. The names are separated from the values by '='. * of name/value pairs. The names are separated from the values by '='.
@@ -69,14 +68,14 @@ public class CookieList {
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONObject jo) throws JSONException { public static String toString(JSONObject jo) throws JSONException {
boolean b = false; boolean b = false;
Iterator keys = jo.keys(); Iterator keys = jo.keys();
String string; String string;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
while (keys.hasNext()) { while (keys.hasNext()) {
string = keys.next().toString(); string = keys.next().toString();
if (!jo.isNull(string)) { if(!jo.isNull(string)) {
if (b) { if(b) {
sb.append(';'); sb.append(';');
} }
sb.append(Cookie.escape(string)); sb.append(Cookie.escape(string));
+25 -25
View File
@@ -1,27 +1,27 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org * Copyright (c) 2002 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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;
@@ -93,7 +93,7 @@ public class HTTP {
String token; String token;
token = x.nextToken(); token = x.nextToken();
if (token.toUpperCase().startsWith("HTTP")) { if(token.toUpperCase().startsWith("HTTP")) {
// Response // Response
@@ -156,13 +156,13 @@ public class HTTP {
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('"');
@@ -176,7 +176,7 @@ public class HTTP {
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)) {
+27 -28
View File
@@ -1,27 +1,27 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org * Copyright (c) 2002 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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.
*/ */
/** /**
@@ -40,7 +40,6 @@ public class HTTPTokener extends JSONTokener {
super(string); super(string);
} }
/** /**
* Get the next token or string. This is used in parsing HTTP headers. * Get the next token or string. This is used in parsing HTTP headers.
* @throws JSONException * @throws JSONException
@@ -53,21 +52,21 @@ public class HTTPTokener extends JSONTokener {
do { do {
c = next(); c = next();
} while (Character.isWhitespace(c)); } while (Character.isWhitespace(c));
if (c == '"' || c == '\'') { if(c == '"' || c == '\'') {
q = c; q = c;
for (;;) { for(;;) {
c = next(); c = next();
if (c < ' ') { if(c < ' ') {
throw syntaxError("Unterminated string."); throw syntaxError("Unterminated string.");
} }
if (c == q) { if(c == q) {
return sb.toString(); return sb.toString();
} }
sb.append(c); sb.append(c);
} }
} }
for (;;) { for(;;) {
if (c == 0 || Character.isWhitespace(c)) { if(c == 0 || Character.isWhitespace(c)) {
return sb.toString(); return sb.toString();
} }
sb.append(c); sb.append(c);
+73 -120
View File
@@ -1,27 +1,27 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org * Copyright (c) 2002 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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;
@@ -81,13 +81,11 @@ import java.util.Map;
*/ */
public class JSONArray { public class JSONArray {
/** /**
* The arrayList where the JSONArray's properties are kept. * The arrayList where the JSONArray's properties are kept.
*/ */
private final ArrayList<Object> myArrayList; private final ArrayList<Object> myArrayList;
/** /**
* Construct an empty JSONArray. * Construct an empty JSONArray.
*/ */
@@ -102,13 +100,13 @@ public class JSONArray {
*/ */
public JSONArray(JSONTokener x) throws JSONException { public JSONArray(JSONTokener x) throws JSONException {
this(); this();
if (x.nextClean() != '[') { if(x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['"); throw x.syntaxError("A JSONArray text must start with '['");
} }
if (x.nextClean() != ']') { if(x.nextClean() != ']') {
x.back(); x.back();
for (;;) { for(;;) {
if (x.nextClean() == ',') { if(x.nextClean() == ',') {
x.back(); x.back();
this.myArrayList.add(JSONObject.NULL); this.myArrayList.add(JSONObject.NULL);
} else { } else {
@@ -118,7 +116,7 @@ public class JSONArray {
switch (x.nextClean()) { switch (x.nextClean()) {
case ';': case ';':
case ',': case ',':
if (x.nextClean() == ']') { if(x.nextClean() == ']') {
return; return;
} }
x.back(); x.back();
@@ -132,7 +130,6 @@ public class JSONArray {
} }
} }
/** /**
* Construct a JSONArray from a source JSON text. * Construct a JSONArray from a source JSON text.
* @param source A string that begins with * @param source A string that begins with
@@ -144,14 +141,13 @@ public class JSONArray {
this(new JSONTokener(source)); this(new JSONTokener(source));
} }
/** /**
* Construct a JSONArray from a Collection. * Construct a JSONArray from a Collection.
* @param collection A Collection. * @param collection A Collection.
*/ */
public JSONArray(Collection<?> collection) { public JSONArray(Collection<?> collection) {
this.myArrayList = new ArrayList<Object>(); this.myArrayList = new ArrayList<Object>();
if (collection != null) { if(collection != null) {
Iterator<?> iter = collection.iterator(); Iterator<?> iter = collection.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
this.myArrayList.add(JSONObject.wrap(iter.next())); this.myArrayList.add(JSONObject.wrap(iter.next()));
@@ -159,16 +155,15 @@ public class JSONArray {
} }
} }
/** /**
* Construct a JSONArray from an array * Construct a JSONArray from an array
* @throws JSONException If not an array. * @throws JSONException If not an array.
*/ */
public JSONArray(Object array) throws JSONException { public JSONArray(Object array) throws JSONException {
this(); this();
if (array.getClass().isArray()) { if(array.getClass().isArray()) {
int length = Array.getLength(array); int length = Array.getLength(array);
for (int i = 0; i < length; i += 1) { for(int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i))); this.put(JSONObject.wrap(Array.get(array, i)));
} }
} else { } else {
@@ -177,7 +172,6 @@ public class JSONArray {
} }
} }
/** /**
* Get the object value associated with an index. * Get the object value associated with an index.
* @param index * @param index
@@ -187,13 +181,12 @@ public class JSONArray {
*/ */
public Object get(int index) throws JSONException { public Object get(int index) throws JSONException {
Object object = this.opt(index); Object object = this.opt(index);
if (object == null) { if(object == null) {
throw new JSONException("JSONArray[" + index + "] not found."); throw new JSONException("JSONArray[" + index + "] not found.");
} }
return object; return object;
} }
/** /**
* Get the boolean value associated with an index. * Get the boolean value associated with an index.
* The string values "true" and "false" are converted to boolean. * The string values "true" and "false" are converted to boolean.
@@ -205,19 +198,18 @@ public class JSONArray {
*/ */
public boolean getBoolean(int index) throws JSONException { public boolean getBoolean(int index) throws JSONException {
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.");
} }
/** /**
* Get the double value associated with an index. * Get the double value associated with an index.
* *
@@ -230,15 +222,14 @@ 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.");
} }
} }
/** /**
* Get the int value associated with an index. * Get the int value associated with an index.
* *
@@ -250,15 +241,14 @@ 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.");
} }
} }
/** /**
* Get the JSONArray associated with an index. * Get the JSONArray associated with an index.
* @param index The index must be between 0 and length() - 1. * @param index The index must be between 0 and length() - 1.
@@ -268,14 +258,13 @@ public class JSONArray {
*/ */
public JSONArray getJSONArray(int index) throws JSONException { public JSONArray getJSONArray(int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
if (object instanceof JSONArray) { if(object instanceof JSONArray) {
return (JSONArray)object; return (JSONArray) object;
} }
throw new JSONException("JSONArray[" + index + throw new JSONException("JSONArray[" + index +
"] is not a JSONArray."); "] is not a JSONArray.");
} }
/** /**
* Get the JSONObject associated with an index. * Get the JSONObject associated with an index.
* @param index subscript * @param index subscript
@@ -285,14 +274,13 @@ public class JSONArray {
*/ */
public JSONObject getJSONObject(int index) throws JSONException { public JSONObject getJSONObject(int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
if (object instanceof JSONObject) { if(object instanceof JSONObject) {
return (JSONObject)object; return (JSONObject) object;
} }
throw new JSONException("JSONArray[" + index + throw new JSONException("JSONArray[" + index +
"] is not a JSONObject."); "] is not a JSONObject.");
} }
/** /**
* Get the long value associated with an index. * Get the long value associated with an index.
* *
@@ -305,15 +293,14 @@ 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.");
} }
} }
/** /**
* Get the string associated with an index. * Get the string associated with an index.
* @param index The index must be between 0 and length() - 1. * @param index The index must be between 0 and length() - 1.
@@ -322,13 +309,12 @@ public class JSONArray {
*/ */
public String getString(int index) throws JSONException { public String getString(int index) throws JSONException {
Object object = this.get(index); Object object = this.get(index);
if (object instanceof String) { if(object instanceof String) {
return (String)object; return (String) object;
} }
throw new JSONException("JSONArray[" + index + "] not a string."); throw new JSONException("JSONArray[" + index + "] not a string.");
} }
/** /**
* Determine if the value is null. * Determine if the value is null.
* @param index The index must be between 0 and length() - 1. * @param index The index must be between 0 and length() - 1.
@@ -338,7 +324,6 @@ public class JSONArray {
return JSONObject.NULL.equals(this.opt(index)); return JSONObject.NULL.equals(this.opt(index));
} }
/** /**
* Make a string from the contents of this JSONArray. The * Make a string from the contents of this JSONArray. The
* <code>separator</code> string is inserted between each element. * <code>separator</code> string is inserted between each element.
@@ -351,8 +336,8 @@ public class JSONArray {
int len = this.length(); int len = this.length();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i += 1) { for(int i = 0; i < len; i += 1) {
if (i > 0) { if(i > 0) {
sb.append(separator); sb.append(separator);
} }
sb.append(JSONObject.valueToString(this.myArrayList.get(i))); sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
@@ -360,7 +345,6 @@ public class JSONArray {
return sb.toString(); return sb.toString();
} }
/** /**
* Get the number of elements in the JSONArray, included nulls. * Get the number of elements in the JSONArray, included nulls.
* *
@@ -370,7 +354,6 @@ public class JSONArray {
return this.myArrayList.size(); return this.myArrayList.size();
} }
/** /**
* Get the optional object value associated with an index. * Get the optional object value associated with an index.
* @param index The index must be between 0 and length() - 1. * @param index The index must be between 0 and length() - 1.
@@ -380,10 +363,9 @@ 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);
} }
/** /**
* Get the optional boolean value associated with an index. * Get the optional boolean value associated with an index.
* It returns false if there is no value at that index, * It returns false if there is no value at that index,
@@ -392,11 +374,10 @@ public class JSONArray {
* @param index The index must be between 0 and length() - 1. * @param index The index must be between 0 and length() - 1.
* @return The truth. * @return The truth.
*/ */
public boolean optBoolean(int index) { public boolean optBoolean(int index) {
return this.optBoolean(index, false); return this.optBoolean(index, false);
} }
/** /**
* Get the optional boolean value associated with an index. * Get the optional boolean value associated with an index.
* It returns the defaultValue if there is no value at that index or if * It returns the defaultValue if there is no value at that index or if
@@ -406,15 +387,14 @@ public class JSONArray {
* @param defaultValue A boolean default. * @param defaultValue A boolean default.
* @return The truth. * @return The truth.
*/ */
public boolean optBoolean(int index, boolean defaultValue) { public boolean optBoolean(int index, boolean defaultValue) {
try { try {
return this.getBoolean(index); return this.getBoolean(index);
} catch (Exception e) { } catch(Exception e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional double value associated with an index. * Get the optional double value associated with an index.
* NaN is returned if there is no value for the index, * NaN is returned if there is no value for the index,
@@ -427,7 +407,6 @@ public class JSONArray {
return this.optDouble(index, Double.NaN); return this.optDouble(index, Double.NaN);
} }
/** /**
* Get the optional double value associated with an index. * Get the optional double value associated with an index.
* The defaultValue is returned if there is no value for the index, * The defaultValue is returned if there is no value for the index,
@@ -440,12 +419,11 @@ public class JSONArray {
public double optDouble(int index, double defaultValue) { public double optDouble(int index, double defaultValue) {
try { try {
return this.getDouble(index); return this.getDouble(index);
} catch (Exception e) { } catch(Exception e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional int value associated with an index. * Get the optional int value associated with an index.
* Zero is returned if there is no value for the index, * Zero is returned if there is no value for the index,
@@ -458,7 +436,6 @@ public class JSONArray {
return this.optInt(index, 0); return this.optInt(index, 0);
} }
/** /**
* Get the optional int value associated with an index. * Get the optional int value associated with an index.
* The defaultValue is returned if there is no value for the index, * The defaultValue is returned if there is no value for the index,
@@ -470,12 +447,11 @@ public class JSONArray {
public int optInt(int index, int defaultValue) { public int optInt(int index, int defaultValue) {
try { try {
return this.getInt(index); return this.getInt(index);
} catch (Exception e) { } catch(Exception e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional JSONArray associated with an index. * Get the optional JSONArray associated with an index.
* @param index subscript * @param index subscript
@@ -484,10 +460,9 @@ public class JSONArray {
*/ */
public JSONArray optJSONArray(int index) { public JSONArray optJSONArray(int index) {
Object o = this.opt(index); Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray)o : null; return o instanceof JSONArray ? (JSONArray) o : null;
} }
/** /**
* Get the optional JSONObject associated with an index. * Get the optional JSONObject associated with an index.
* Null is returned if the key is not found, or null if the index has * Null is returned if the key is not found, or null if the index has
@@ -498,10 +473,9 @@ public class JSONArray {
*/ */
public JSONObject optJSONObject(int index) { public JSONObject optJSONObject(int index) {
Object o = this.opt(index); Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject)o : null; return o instanceof JSONObject ? (JSONObject) o : null;
} }
/** /**
* Get the optional long value associated with an index. * Get the optional long value associated with an index.
* Zero is returned if there is no value for the index, * Zero is returned if there is no value for the index,
@@ -514,7 +488,6 @@ public class JSONArray {
return this.optLong(index, 0); return this.optLong(index, 0);
} }
/** /**
* Get the optional long value associated with an index. * Get the optional long value associated with an index.
* The defaultValue is returned if there is no value for the index, * The defaultValue is returned if there is no value for the index,
@@ -526,12 +499,11 @@ public class JSONArray {
public long optLong(int index, long defaultValue) { public long optLong(int index, long defaultValue) {
try { try {
return this.getLong(index); return this.getLong(index);
} catch (Exception e) { } catch(Exception e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional string value associated with an index. It returns an * Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value * empty string if there is no value at that index. If the value
@@ -544,7 +516,6 @@ public class JSONArray {
return this.optString(index, ""); return this.optString(index, "");
} }
/** /**
* Get the optional string associated with an index. * Get the optional string associated with an index.
* The defaultValue is returned if the key is not found. * The defaultValue is returned if the key is not found.
@@ -557,10 +528,9 @@ public class JSONArray {
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();
} }
/** /**
* Append a boolean value. This increases the array's length by one. * Append a boolean value. This increases the array's length by one.
* *
@@ -572,7 +542,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put a value in the JSONArray, where the value will be a * Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection. * JSONArray which is produced from a Collection.
@@ -584,7 +553,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Append a double value. This increases the array's length by one. * Append a double value. This increases the array's length by one.
* *
@@ -599,7 +567,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Append an int value. This increases the array's length by one. * Append an int value. This increases the array's length by one.
* *
@@ -611,7 +578,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Append an long value. This increases the array's length by one. * Append an long value. This increases the array's length by one.
* *
@@ -623,7 +589,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put a value in the JSONArray, where the value will be a * Put a value in the JSONArray, where the value will be a
* JSONObject which is produced from a Map. * JSONObject which is produced from a Map.
@@ -635,7 +600,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Append an object value. This increases the array's length by one. * Append an object value. This increases the array's length by one.
* @param value An object value. The value should be a * @param value An object value. The value should be a
@@ -648,7 +612,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put or replace a boolean value in the JSONArray. If the index is greater * Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as * than the length of the JSONArray, then null elements will be added as
@@ -663,7 +626,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put a value in the JSONArray, where the value will be a * Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection. * JSONArray which is produced from a Collection.
@@ -678,7 +640,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put or replace a double value. If the index is greater than the length of * Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad * the JSONArray, then null elements will be added as necessary to pad
@@ -694,7 +655,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put or replace an int value. If the index is greater than the length of * Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad * the JSONArray, then null elements will be added as necessary to pad
@@ -709,7 +669,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put or replace a long value. If the index is greater than the length of * Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad * the JSONArray, then null elements will be added as necessary to pad
@@ -724,7 +683,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put a value in the JSONArray, where the value will be a * Put a value in the JSONArray, where the value will be a
* JSONObject that is produced from a Map. * JSONObject that is produced from a Map.
@@ -739,7 +697,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Put or replace an object value in the JSONArray. If the index is greater * Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as * than the length of the JSONArray, then null elements will be added as
@@ -754,10 +711,10 @@ public class JSONArray {
*/ */
public JSONArray put(int index, Object value) throws JSONException { public JSONArray put(int index, Object value) throws JSONException {
JSONObject.testValidity(value); JSONObject.testValidity(value);
if (index < 0) { if(index < 0) {
throw new JSONException("JSONArray[" + index + "] not found."); throw new JSONException("JSONArray[" + index + "] not found.");
} }
if (index < this.length()) { if(index < this.length()) {
this.myArrayList.set(index, value); this.myArrayList.set(index, value);
} else { } else {
while (index != this.length()) { while (index != this.length()) {
@@ -768,7 +725,6 @@ public class JSONArray {
return this; return this;
} }
/** /**
* Remove an index and close the hole. * Remove an index and close the hole.
* @param index The index of the element to be removed. * @param index The index of the element to be removed.
@@ -781,7 +737,6 @@ public class JSONArray {
return o; return o;
} }
/** /**
* Produce a JSONObject by combining a JSONArray of names with the values * Produce a JSONObject by combining a JSONArray of names with the values
* of this JSONArray. * of this JSONArray.
@@ -792,17 +747,16 @@ public class JSONArray {
* @throws JSONException If any of the names are null. * @throws JSONException If any of the names are null.
*/ */
public JSONObject toJSONObject(JSONArray names) throws JSONException { public JSONObject toJSONObject(JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || this.length() == 0) { if(names == null || names.length() == 0 || this.length() == 0) {
return null; return null;
} }
JSONObject jo = new JSONObject(); JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) { for(int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i)); jo.put(names.getString(i), this.opt(i));
} }
return jo; return jo;
} }
/** /**
* Make a JSON text of this JSONArray. For compactness, no * Make a JSON text of this JSONArray. For compactness, no
* unnecessary whitespace is added. If it is not possible to produce a * unnecessary whitespace is added. If it is not possible to produce a
@@ -817,12 +771,11 @@ public class JSONArray {
public String toString() { public String toString() {
try { try {
return this.toString(0); return this.toString(0);
} catch (Exception e) { } catch(Exception e) {
return null; return null;
} }
} }
/** /**
* Make a prettyprinted JSON text of this JSONArray. * Make a prettyprinted JSON text of this JSONArray.
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
@@ -874,17 +827,17 @@ public class JSONArray {
int length = this.length(); int length = this.length();
writer.write('['); writer.write('[');
if (length == 1) { if(length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0), JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent); indentFactor, indent);
} else if (length != 0) { } else if(length != 0) {
final int newindent = indent + indentFactor; final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) { for(int i = 0; i < length; i += 1) {
if (commanate) { if(commanate) {
writer.write(','); writer.write(',');
} }
if (indentFactor > 0) { if(indentFactor > 0) {
writer.write('\n'); writer.write('\n');
} }
JSONObject.indent(writer, newindent); JSONObject.indent(writer, newindent);
@@ -892,14 +845,14 @@ public class JSONArray {
indentFactor, newindent); indentFactor, newindent);
commanate = true; commanate = true;
} }
if (indentFactor > 0) { if(indentFactor > 0) {
writer.write('\n'); writer.write('\n');
} }
JSONObject.indent(writer, indent); JSONObject.indent(writer, indent);
} }
writer.write(']'); writer.write(']');
return writer; return writer;
} catch (IOException e) { } catch(IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
} }
File diff suppressed because it is too large Load Diff
+1
View File
@@ -1,4 +1,5 @@
package org.json; package org.json;
/** /**
* The <code>JSONString</code> interface allows a <code>toJSONString()</code> * The <code>JSONString</code> interface allows a <code>toJSONString()</code>
* method so that a class can change the behavior of * method so that a class can change the behavior of
+21 -21
View File
@@ -1,27 +1,27 @@
package org.json; package org.json;
/* /*
Copyright (c) 2006 JSON.org * Copyright (c) 2006 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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;
+54 -71
View File
@@ -8,27 +8,27 @@ import java.io.Reader;
import java.io.StringReader; import java.io.StringReader;
/* /*
Copyright (c) 2002 JSON.org * Copyright (c) 2002 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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.
*/ */
/** /**
@@ -40,15 +40,14 @@ SOFTWARE.
*/ */
public class JSONTokener { public class JSONTokener {
private long character; private long character;
private boolean eof; private boolean eof;
private long index; private long index;
private long line; private long line;
private char previous; private char previous;
private Reader reader; private Reader reader;
private boolean usePrevious; private boolean usePrevious;
/** /**
* Construct a JSONTokener from a Reader. * Construct a JSONTokener from a Reader.
* *
@@ -57,7 +56,7 @@ 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;
@@ -66,7 +65,6 @@ public class JSONTokener {
this.line = 1; this.line = 1;
} }
/** /**
* Construct a JSONTokener from an InputStream. * Construct a JSONTokener from an InputStream.
*/ */
@@ -74,7 +72,6 @@ public class JSONTokener {
this(new InputStreamReader(inputStream)); this(new InputStreamReader(inputStream));
} }
/** /**
* Construct a JSONTokener from a string. * Construct a JSONTokener from a string.
* *
@@ -84,14 +81,13 @@ public class JSONTokener {
this(new StringReader(s)); this(new StringReader(s));
} }
/** /**
* Back up one character. This provides a sort of lookahead capability, * Back up one character. This provides a sort of lookahead capability,
* so that you can test for a digit or letter before attempting to parse * so that you can test for a digit or letter before attempting to parse
* the next number or identifier. * the next number or identifier.
*/ */
public void back() throws JSONException { public void back() throws JSONException {
if (this.usePrevious || this.index <= 0) { if(this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported"); throw new JSONException("Stepping back two steps is not supported");
} }
this.index -= 1; this.index -= 1;
@@ -100,7 +96,6 @@ public class JSONTokener {
this.eof = false; this.eof = false;
} }
/** /**
* Get the hex value of a character (base16). * Get the hex value of a character (base16).
* @param c A character between '0' and '9' or between 'A' and 'F' or * @param c A character between '0' and '9' or between 'A' and 'F' or
@@ -108,13 +103,13 @@ public class JSONTokener {
* @return An int between 0 and 15, or -1 if c was not a hex digit. * @return An int between 0 and 15, or -1 if c was not a hex digit.
*/ */
public static int dehexchar(char c) { public static int dehexchar(char c) {
if (c >= '0' && c <= '9') { if(c >= '0' && c <= '9') {
return c - '0'; return c - '0';
} }
if (c >= 'A' && c <= 'F') { if(c >= 'A' && c <= 'F') {
return c - ('A' - 10); return c - ('A' - 10);
} }
if (c >= 'a' && c <= 'f') { if(c >= 'a' && c <= 'f') {
return c - ('a' - 10); return c - ('a' - 10);
} }
return -1; return -1;
@@ -124,7 +119,6 @@ public class JSONTokener {
return this.eof && !this.usePrevious; return this.eof && !this.usePrevious;
} }
/** /**
* Determine if the source string still contains characters that next() * Determine if the source string still contains characters that next()
* can consume. * can consume.
@@ -132,14 +126,13 @@ public class JSONTokener {
*/ */
public boolean more() throws JSONException { public boolean more() throws JSONException {
this.next(); this.next();
if (this.end()) { if(this.end()) {
return false; return false;
} }
this.back(); this.back();
return true; return true;
} }
/** /**
* Get the next character in the source string. * Get the next character in the source string.
* *
@@ -147,26 +140,26 @@ public class JSONTokener {
*/ */
public char next() throws JSONException { public char next() throws JSONException {
int c; int c;
if (this.usePrevious) { if(this.usePrevious) {
this.usePrevious = false; this.usePrevious = false;
c = this.previous; c = this.previous;
} else { } else {
try { try {
c = this.reader.read(); c = this.reader.read();
} catch (IOException exception) { } catch(IOException exception) {
throw new JSONException(exception); throw new JSONException(exception);
} }
if (c <= 0) { // End of stream if(c <= 0) { // End of stream
this.eof = true; this.eof = true;
c = 0; c = 0;
} }
} }
this.index += 1; this.index += 1;
if (this.previous == '\r') { if(this.previous == '\r') {
this.line += 1; this.line += 1;
this.character = c == '\n' ? 0 : 1; this.character = c == '\n' ? 0 : 1;
} else if (c == '\n') { } else if(c == '\n') {
this.line += 1; this.line += 1;
this.character = 0; this.character = 0;
} else { } else {
@@ -176,7 +169,6 @@ public class JSONTokener {
return this.previous; return this.previous;
} }
/** /**
* Consume the next character, and check that it matches a specified * Consume the next character, and check that it matches a specified
* character. * character.
@@ -186,14 +178,13 @@ public class JSONTokener {
*/ */
public char next(char c) throws JSONException { public char next(char c) throws JSONException {
char n = this.next(); char n = this.next();
if (n != c) { if(n != c) {
throw this.syntaxError("Expected '" + c + "' and instead saw '" + throw this.syntaxError("Expected '" + c + "' and instead saw '" +
n + "'"); n + "'");
} }
return n; return n;
} }
/** /**
* Get the next n characters. * Get the next n characters.
* *
@@ -204,7 +195,7 @@ public class JSONTokener {
* 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 "";
} }
@@ -213,7 +204,7 @@ public class JSONTokener {
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;
@@ -221,22 +212,20 @@ public class JSONTokener {
return new String(chars); return new String(chars);
} }
/** /**
* Get the next char in the string, skipping whitespace. * Get the next char in the string, skipping whitespace.
* @throws JSONException * @throws JSONException
* @return A character, or 0 if there are no more characters. * @return A character, or 0 if there are no more characters.
*/ */
public char nextClean() throws JSONException { public char nextClean() throws JSONException {
for (;;) { for(;;) {
char c = this.next(); char c = this.next();
if (c == 0 || c > ' ') { if(c == 0 || c > ' ') {
return c; return c;
} }
} }
} }
/** /**
* Return the characters up to the next close quote character. * Return the characters up to the next close quote character.
* Backslash processing is done. The formal JSON format does not * Backslash processing is done. The formal JSON format does not
@@ -251,7 +240,7 @@ public class JSONTokener {
public String nextString(char quote) throws JSONException { public String nextString(char quote) throws JSONException {
char c; char c;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (;;) { for(;;) {
c = this.next(); c = this.next();
switch (c) { switch (c) {
case 0: case 0:
@@ -277,7 +266,7 @@ public class JSONTokener {
sb.append('\r'); sb.append('\r');
break; break;
case 'u': case 'u':
sb.append((char)Integer.parseInt(this.next(4), 16)); sb.append((char) Integer.parseInt(this.next(4), 16));
break; break;
case '"': case '"':
case '\'': case '\'':
@@ -290,7 +279,7 @@ public class JSONTokener {
} }
break; break;
default: default:
if (c == quote) { if(c == quote) {
return sb.toString(); return sb.toString();
} }
sb.append(c); sb.append(c);
@@ -298,7 +287,6 @@ public class JSONTokener {
} }
} }
/** /**
* Get the text up but not including the specified character or the * Get the text up but not including the specified character or the
* end of line, whichever comes first. * end of line, whichever comes first.
@@ -307,10 +295,10 @@ public class JSONTokener {
*/ */
public String nextTo(char delimiter) throws JSONException { public String nextTo(char delimiter) throws JSONException {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (;;) { for(;;) {
char c = this.next(); char c = this.next();
if (c == delimiter || c == 0 || c == '\n' || c == '\r') { if(c == delimiter || c == 0 || c == '\n' || c == '\r') {
if (c != 0) { if(c != 0) {
this.back(); this.back();
} }
return sb.toString().trim(); return sb.toString().trim();
@@ -319,7 +307,6 @@ public class JSONTokener {
} }
} }
/** /**
* Get the text up but not including one of the specified delimiter * Get the text up but not including one of the specified delimiter
* characters or the end of line, whichever comes first. * characters or the end of line, whichever comes first.
@@ -329,11 +316,11 @@ public class JSONTokener {
public String nextTo(String delimiters) throws JSONException { public String nextTo(String delimiters) throws JSONException {
char c; char c;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (;;) { for(;;) {
c = this.next(); c = this.next();
if (delimiters.indexOf(c) >= 0 || c == 0 || if(delimiters.indexOf(c) >= 0 || c == 0 ||
c == '\n' || c == '\r') { c == '\n' || c == '\r') {
if (c != 0) { if(c != 0) {
this.back(); this.back();
} }
return sb.toString().trim(); return sb.toString().trim();
@@ -342,7 +329,6 @@ public class JSONTokener {
} }
} }
/** /**
* Get the next value. The value can be a Boolean, Double, Integer, * Get the next value. The value can be a Boolean, Double, Integer,
* JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
@@ -383,13 +369,12 @@ public class JSONTokener {
this.back(); this.back();
string = sb.toString().trim(); string = sb.toString().trim();
if ("".equals(string)) { if("".equals(string)) {
throw this.syntaxError("Missing value"); throw this.syntaxError("Missing value");
} }
return JSONObject.stringToValue(string); return JSONObject.stringToValue(string);
} }
/** /**
* Skip characters until the next character is the requested character. * Skip characters until the next character is the requested character.
* If the requested character is not found, no characters are skipped. * If the requested character is not found, no characters are skipped.
@@ -406,7 +391,7 @@ public class JSONTokener {
this.reader.mark(1000000); this.reader.mark(1000000);
do { do {
c = this.next(); c = this.next();
if (c == 0) { if(c == 0) {
this.reader.reset(); this.reader.reset();
this.index = startIndex; this.index = startIndex;
this.character = startCharacter; this.character = startCharacter;
@@ -414,7 +399,7 @@ public class JSONTokener {
return c; return c;
} }
} while (c != to); } while (c != to);
} catch (IOException exc) { } catch(IOException exc) {
throw new JSONException(exc); throw new JSONException(exc);
} }
@@ -422,7 +407,6 @@ public class JSONTokener {
return c; return c;
} }
/** /**
* Make a JSONException to signal a syntax error. * Make a JSONException to signal a syntax error.
* *
@@ -433,7 +417,6 @@ public class JSONTokener {
return new JSONException(message + this.toString()); return new JSONException(message + this.toString());
} }
/** /**
* Make a printable string of this JSONTokener. * Make a printable string of this JSONTokener.
* *
+41 -45
View File
@@ -4,27 +4,27 @@ import java.io.IOException;
import java.io.Writer; import java.io.Writer;
/* /*
Copyright (c) 2006 JSON.org * Copyright (c) 2006 JSON.org
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
The Software shall be used for Good, not Evil. * The Software shall be used for Good, not Evil.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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.
*/ */
/** /**
@@ -108,19 +108,19 @@ public class JSONWriter {
* @throws JSONException If the value is out of sequence. * @throws JSONException If the value is out of sequence.
*/ */
private JSONWriter append(String string) throws JSONException { private JSONWriter append(String string) throws JSONException {
if (string == null) { if(string == null) {
throw new JSONException("Null pointer"); throw new JSONException("Null pointer");
} }
if (this.mode == 'o' || this.mode == 'a') { if(this.mode == 'o' || this.mode == 'a') {
try { try {
if (this.comma && this.mode == 'a') { if(this.comma && this.mode == 'a') {
this.writer.write(','); this.writer.write(',');
} }
this.writer.write(string); this.writer.write(string);
} catch (IOException e) { } catch(IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
if (this.mode == 'o') { if(this.mode == 'o') {
this.mode = 'k'; this.mode = 'k';
} }
this.comma = true; this.comma = true;
@@ -139,7 +139,7 @@ public class JSONWriter {
* outermost array or object). * outermost array or object).
*/ */
public JSONWriter array() throws JSONException { public JSONWriter array() throws JSONException {
if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { if(this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
this.push(null); this.push(null);
this.append("["); this.append("[");
this.comma = false; this.comma = false;
@@ -156,15 +156,15 @@ public class JSONWriter {
* @throws JSONException If unbalanced. * @throws JSONException If unbalanced.
*/ */
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 {
this.writer.write(c); this.writer.write(c);
} catch (IOException e) { } catch(IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
this.comma = true; this.comma = true;
@@ -200,13 +200,13 @@ public class JSONWriter {
* do not belong in arrays or if the key is null. * do not belong in arrays or if the key is null.
*/ */
public JSONWriter key(String string) throws JSONException { public JSONWriter key(String string) throws JSONException {
if (string == null) { if(string == null) {
throw new JSONException("Null key."); throw new JSONException("Null key.");
} }
if (this.mode == 'k') { if(this.mode == 'k') {
try { try {
this.stack[this.top - 1].putOnce(string, Boolean.TRUE); this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) { if(this.comma) {
this.writer.write(','); this.writer.write(',');
} }
this.writer.write(JSONObject.quote(string)); this.writer.write(JSONObject.quote(string));
@@ -214,14 +214,13 @@ public class JSONWriter {
this.comma = false; this.comma = false;
this.mode = 'o'; this.mode = 'o';
return this; return this;
} catch (IOException e) { } catch(IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
} }
throw new JSONException("Misplaced key."); throw new JSONException("Misplaced key.");
} }
/** /**
* Begin appending a new object. All keys and values until the balancing * Begin appending a new object. All keys and values until the balancing
* <code>endObject</code> will be appended to this object. The * <code>endObject</code> will be appended to this object. The
@@ -232,10 +231,10 @@ public class JSONWriter {
* outermost array or object). * outermost array or object).
*/ */
public JSONWriter object() throws JSONException { public JSONWriter object() throws JSONException {
if (this.mode == 'i') { if(this.mode == 'i') {
this.mode = 'o'; this.mode = 'o';
} }
if (this.mode == 'o' || this.mode == 'a') { if(this.mode == 'o' || this.mode == 'a') {
this.append("{"); this.append("{");
this.push(new JSONObject()); this.push(new JSONObject());
this.comma = false; this.comma = false;
@@ -245,26 +244,25 @@ public class JSONWriter {
} }
/** /**
* Pop an array or object scope. * Pop an array or object scope.
* @param c The scope to close. * @param c The scope to close.
* @throws JSONException If nesting is wrong. * @throws JSONException If nesting is wrong.
*/ */
private void pop(char c) throws JSONException { private void pop(char c) throws JSONException {
if (this.top <= 0) { if(this.top <= 0) {
throw new JSONException("Nesting error."); throw new JSONException("Nesting error.");
} }
char m = this.stack[this.top - 1] == null ? 'a' : 'k'; char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) { if(m != c) {
throw new JSONException("Nesting error."); throw new JSONException("Nesting error.");
} }
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';
} }
/** /**
@@ -273,7 +271,7 @@ public class JSONWriter {
* @throws JSONException If nesting is too deep. * @throws JSONException If nesting is too deep.
*/ */
private void push(JSONObject jo) throws JSONException { private void push(JSONObject jo) throws JSONException {
if (this.top >= maxdepth) { if(this.top >= maxdepth) {
throw new JSONException("Nesting too deep."); throw new JSONException("Nesting too deep.");
} }
this.stack[this.top] = jo; this.stack[this.top] = jo;
@@ -281,7 +279,6 @@ public class JSONWriter {
this.top += 1; this.top += 1;
} }
/** /**
* Append either the value <code>true</code> or the value * Append either the value <code>true</code> or the value
* <code>false</code>. * <code>false</code>.
@@ -313,7 +310,6 @@ public class JSONWriter {
return this.append(Long.toString(l)); return this.append(Long.toString(l));
} }
/** /**
* Append an object value. * Append an object value.
* @param object The object to append. It can be null, or a Boolean, Number, * @param object The object to append. It can be null, or a Boolean, Number,