diff --git a/src/cn/citycraft/RealBackpacks/MainCommand.java b/src/cn/citycraft/RealBackpacks/MainCommand.java index 9c3e4b4..fc6cfa2 100644 --- a/src/cn/citycraft/RealBackpacks/MainCommand.java +++ b/src/cn/citycraft/RealBackpacks/MainCommand.java @@ -18,9 +18,9 @@ import org.bukkit.inventory.ItemStack; import cn.citycraft.RealBackpacks.config.FileConfig; import cn.citycraft.RealBackpacks.config.PlayerConfig; -import cn.citycraft.RealBackpacks.util.InvJsonUtils; import cn.citycraft.RealBackpacks.util.MysqlFunctions; import cn.citycraft.RealBackpacks.util.RBUtil; +import cn.citycraft.RealBackpacks.util.Serialization; public class MainCommand implements CommandExecutor { @@ -332,7 +332,7 @@ public class MainCommand implements CommandExecutor { backpack); state.setString( 3, - InvJsonUtils + Serialization .listToString(config .getStringList(backpack + ".Inventory"))); @@ -349,7 +349,7 @@ public class MainCommand implements CommandExecutor { backpack); state.setString( 3, - InvJsonUtils + Serialization .listToString(config .getStringList(backpack + ".Inventory"))); @@ -362,7 +362,7 @@ public class MainCommand implements CommandExecutor { state.setString(2, backpack); state.setString( 3, - InvJsonUtils + Serialization .listToString(config .getStringList(backpack + ".Inventory"))); @@ -449,7 +449,7 @@ public class MainCommand implements CommandExecutor { fullName + "'s " + backpack + " data")); } else { - inv = InvJsonUtils.listToInventory( + inv = Serialization.toInventory( config.getStringList(backpack + ".Inventory"), fullName + "'s " + backpack + " data", diff --git a/src/cn/citycraft/RealBackpacks/json/JSONArray.java b/src/cn/citycraft/RealBackpacks/json/JSONArray.java new file mode 100644 index 0000000..93eea4f --- /dev/null +++ b/src/cn/citycraft/RealBackpacks/json/JSONArray.java @@ -0,0 +1,415 @@ +package cn.citycraft.RealBackpacks.json; + +/* + * Copyright (c) 2002 JSON.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * The Software shall be used for Good, not Evil. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; + +public class JSONArray { + + private final ArrayList myArrayList; + + public JSONArray() { + this.myArrayList = new ArrayList(); + } + + public JSONArray(JSONTokener x) throws JSONException { + this(); + if (x.nextClean() != '[') { + throw x.syntaxError("A JSONArray text must start with '['"); + } + if (x.nextClean() != ']') { + x.back(); + for (;;) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(JSONObject.NULL); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': + return; + default: + throw x.syntaxError("Expected a ',' or ']'"); + } + } + } + } + + public JSONArray(String source) throws JSONException { + this(new JSONTokener(source)); + } + + public JSONArray(Collection collection) { + this.myArrayList = new ArrayList(); + if (collection != null) { + Iterator iter = collection.iterator(); + while (iter.hasNext()) { + this.myArrayList.add(JSONObject.wrap(iter.next())); + } + } + } + + public JSONArray(Object array) throws JSONException { + this(); + if (array.getClass().isArray()) { + int length = Array.getLength(array); + for (int i = 0; i < length; i += 1) { + this.put(JSONObject.wrap(Array.get(array, i))); + } + } else { + throw new JSONException("JSONArray initial value should be a string or collection or array."); + } + } + + public Object get(int index) throws JSONException { + Object object = this.opt(index); + if (object == null) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + return object; + } + + public boolean getBoolean(int index) throws JSONException { + Object object = this.get(index); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONArray[" + index + "] is not a boolean."); + } + + public double getDouble(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + public int getInt(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + public JSONArray getJSONArray(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); + } + + public JSONObject getJSONObject(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); + } + + public long getLong(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + public String getString(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof String) { + return (String) object; + } + throw new JSONException("JSONArray[" + index + "] not a string."); + } + + public boolean isNull(int index) { + return JSONObject.NULL.equals(this.opt(index)); + } + + public String join(String separator) throws JSONException { + int len = this.length(); + StringBuffer sb = new StringBuffer(); + + for (int i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(separator); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i))); + } + return sb.toString(); + } + + public int length() { + return this.myArrayList.size(); + } + + public Object opt(int index) { + return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index); + } + + public boolean optBoolean(int index) { + return this.optBoolean(index, false); + } + + public boolean optBoolean(int index, boolean defaultValue) { + try { + return this.getBoolean(index); + } catch (Exception e) { + return defaultValue; + } + } + + public double optDouble(int index) { + return this.optDouble(index, Double.NaN); + } + + public double optDouble(int index, double defaultValue) { + try { + return this.getDouble(index); + } catch (Exception e) { + return defaultValue; + } + } + + public int optInt(int index) { + return this.optInt(index, 0); + } + + public int optInt(int index, int defaultValue) { + try { + return this.getInt(index); + } catch (Exception e) { + return defaultValue; + } + } + + public JSONArray optJSONArray(int index) { + Object o = this.opt(index); + return o instanceof JSONArray ? (JSONArray) o : null; + } + + public JSONObject optJSONObject(int index) { + Object o = this.opt(index); + return o instanceof JSONObject ? (JSONObject) o : null; + } + + public long optLong(int index) { + return this.optLong(index, 0); + } + + public long optLong(int index, long defaultValue) { + try { + return this.getLong(index); + } catch (Exception e) { + return defaultValue; + } + } + + public String optString(int index) { + return this.optString(index, ""); + } + + public String optString(int index, String defaultValue) { + Object object = this.opt(index); + return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); + } + + public JSONArray put(boolean value) { + this.put(value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + public JSONArray put(Collection value) { + this.put(new JSONArray(value)); + return this; + } + + public JSONArray put(double value) throws JSONException { + Double d = new Double(value); + JSONObject.testValidity(d); + this.put(d); + return this; + } + + public JSONArray put(int value) { + this.put(new Integer(value)); + return this; + } + + public JSONArray put(long value) { + this.put(new Long(value)); + return this; + } + + public JSONArray put(Map value) { + this.put(new JSONObject()); + return this; + } + + public JSONArray put(Object value) { + this.myArrayList.add(value); + return this; + } + + public JSONArray put(int index, boolean value) throws JSONException { + this.put(index, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + public JSONArray put(int index, Collection value) throws JSONException { + this.put(index, new JSONArray(value)); + return this; + } + + public JSONArray put(int index, double value) throws JSONException { + this.put(index, new Double(value)); + return this; + } + + public JSONArray put(int index, int value) throws JSONException { + this.put(index, new Integer(value)); + return this; + } + + public JSONArray put(int index, long value) throws JSONException { + this.put(index, new Long(value)); + return this; + } + + public JSONArray put(int index, Map value) throws JSONException { + this.put(index, new JSONObject(value)); + return this; + } + + public JSONArray put(int index, Object value) throws JSONException { + JSONObject.testValidity(value); + if (index < 0) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + if (index < this.length()) { + this.myArrayList.set(index, value); + } else { + while (index != this.length()) { + this.put(JSONObject.NULL); + } + this.put(value); + } + return this; + } + + public Object remove(int index) { + Object o = this.opt(index); + this.myArrayList.remove(index); + return o; + } + + public JSONObject toJSONObject(JSONArray names) throws JSONException { + if (names == null || names.length() == 0 || this.length() == 0) { + return null; + } + JSONObject jo = new JSONObject(); + for (int i = 0; i < names.length(); i += 1) { + jo.put(names.getString(i), this.opt(i)); + } + return jo; + } + + public String toString() { + try { + return this.toString(0); + } catch (Exception e) { + return null; + } + } + + public String toString(int indentFactor) throws JSONException { + StringWriter sw = new StringWriter(); + synchronized (sw.getBuffer()) { + return this.write(sw, indentFactor, 0).toString(); + } + } + + public Writer write(Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } + + Writer write(Writer writer, int indentFactor, int indent) throws JSONException { + try { + boolean commanate = false; + int length = this.length(); + writer.write('['); + + if (length == 1) { + JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); + } else if (length != 0) { + final int newindent = indent + indentFactor; + + for (int i = 0; i < length; i += 1) { + if (commanate) { + writer.write(','); + } + if (indentFactor > 0) { + writer.write('\n'); + } + JSONObject.indent(writer, newindent); + JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); + commanate = true; + } + if (indentFactor > 0) { + writer.write('\n'); + } + JSONObject.indent(writer, indent); + } + writer.write(']'); + return writer; + } catch (IOException e) { + throw new JSONException(e); + } + } +} \ No newline at end of file diff --git a/src/cn/citycraft/RealBackpacks/json/JSONException.java b/src/cn/citycraft/RealBackpacks/json/JSONException.java new file mode 100644 index 0000000..b09c16d --- /dev/null +++ b/src/cn/citycraft/RealBackpacks/json/JSONException.java @@ -0,0 +1,21 @@ +package cn.citycraft.RealBackpacks.json; + +public class JSONException extends Exception { + + private static final long serialVersionUID = 0; + private Throwable cause; + + public JSONException(final String message) { + super(message); + } + + public JSONException(final Throwable cause) { + super(cause.getMessage()); + this.cause = cause; + } + + @Override + public Throwable getCause() { + return this.cause; + } +} diff --git a/src/cn/citycraft/RealBackpacks/json/JSONObject.java b/src/cn/citycraft/RealBackpacks/json/JSONObject.java new file mode 100644 index 0000000..716762c --- /dev/null +++ b/src/cn/citycraft/RealBackpacks/json/JSONObject.java @@ -0,0 +1,926 @@ +package cn.citycraft.RealBackpacks.json; + +/* + * Copyright (c) 2002 JSON.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * The Software shall be used for Good, not Evil. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.Set; + +public class JSONObject { + + private static final int keyPoolSize = 100; + + @SuppressWarnings("rawtypes") + private static HashMap keyPool = new HashMap(keyPoolSize); + + private static final class Null { + + @Override + protected final Object clone() { + return this; + } + + @Override + public boolean equals(final Object object) { + return object == null || object == this; + } + + @Override + public String toString() { + return "null"; + } + } + + @SuppressWarnings("rawtypes") + private final Map map; + + public static final Object NULL = new Null(); + + @SuppressWarnings("rawtypes") + public JSONObject() { + this.map = new HashMap(); + } + + public JSONObject(final JSONObject jo, final String[] names) { + this(); + for (int i = 0; i < names.length; i += 1) { + try { + this.putOnce(names[i], jo.opt(names[i])); + } catch (final Exception ignore) { + } + } + } + + public JSONObject(final JSONTokener x) throws JSONException { + this(); + char c; + String key; + + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for (;;) { + c = x.nextClean(); + switch (c) { + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); + } + + // The key is followed by ':'. We will also tolerate '=' or '=>'. + + c = x.nextClean(); + if (c == '=') { + if (x.next() != '>') { + x.back(); + } + } else if (c != ':') { + throw x.syntaxError("Expected a ':' after a key"); + } + this.putOnce(key, x.nextValue()); + + // Pairs are separated by ','. We will also tolerate ';'. + + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public JSONObject(final Map map) { + this.map = new HashMap(); + if (map != null) { + final Iterator i = map.entrySet().iterator(); + while (i.hasNext()) { + final Map.Entry e = (Map.Entry) i.next(); + final Object value = e.getValue(); + if (value != null) { + this.map.put(e.getKey(), wrap(value)); + } + } + } + } + + public JSONObject(final Object bean) { + this(); + this.populateMap(bean); + } + + @SuppressWarnings("rawtypes") + public JSONObject(final Object object, final String names[]) { + this(); + final Class c = object.getClass(); + for (int i = 0; i < names.length; i += 1) { + final String name = names[i]; + try { + this.putOpt(name, c.getField(name).get(object)); + } catch (final Exception ignore) { + } + } + } + + public JSONObject(final String source) throws JSONException { + this(new JSONTokener(source)); + } + + @SuppressWarnings("rawtypes") + public JSONObject(final String baseName, final Locale locale) throws JSONException { + this(); + final ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); + + // Iterate through the keys in the bundle. + + final Enumeration keys = bundle.getKeys(); + while (keys.hasMoreElements()) { + final Object key = keys.nextElement(); + if (key instanceof String) { + + // Go through the path, ensuring that there is a nested JSONObject for each + // segment except the last. Add the value using the last segment's name into + // the deepest nested JSONObject. + + final String[] path = ((String) key).split("\\."); + final int last = path.length - 1; + JSONObject target = this; + for (int i = 0; i < last; i += 1) { + final String segment = path[i]; + JSONObject nextTarget = target.optJSONObject(segment); + if (nextTarget == null) { + nextTarget = new JSONObject(); + target.put(segment, nextTarget); + } + target = nextTarget; + } + target.put(path[last], bundle.getString((String) key)); + } + } + } + + public JSONObject accumulate(final String key, final Object value) throws JSONException { + testValidity(value); + final Object object = this.opt(key); + if (object == null) { + this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); + } else if (object instanceof JSONArray) { + ((JSONArray) object).put(value); + } else { + this.put(key, new JSONArray().put(object).put(value)); + } + return this; + } + + public JSONObject append(final String key, final Object value) throws JSONException { + testValidity(value); + final Object object = this.opt(key); + if (object == null) { + this.put(key, new JSONArray().put(value)); + } else if (object instanceof JSONArray) { + this.put(key, ((JSONArray) object).put(value)); + } else { + throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); + } + return this; + } + + public static String doubleToString(final double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { + return "null"; + } + + // Shave off trailing zeros and decimal point, if possible. + + String string = Double.toString(d); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + public Object get(final String key) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + final Object object = this.opt(key); + if (object == null) { + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return object; + } + + public boolean getBoolean(final String key) throws JSONException { + final Object object = this.get(key); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); + } + + public double getDouble(final String key) throws JSONException { + final Object object = this.get(key); + try { + return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + } catch (final Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); + } + } + + public int getInt(final String key) throws JSONException { + final Object object = this.get(key); + try { + return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + } catch (final Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); + } + } + + public JSONArray getJSONArray(final String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); + } + + public JSONObject getJSONObject(final String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); + } + + public long getLong(final String key) throws JSONException { + final Object object = this.get(key); + try { + return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + } catch (final Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); + } + } + + public static String[] getNames(final JSONObject jo) { + final int length = jo.length(); + if (length == 0) { + return null; + } + @SuppressWarnings("rawtypes") + final Iterator iterator = jo.keys(); + final String[] names = new String[length]; + int i = 0; + while (iterator.hasNext()) { + names[i] = (String) iterator.next(); + i += 1; + } + return names; + } + + @SuppressWarnings("rawtypes") + public static String[] getNames(final Object object) { + if (object == null) { + return null; + } + final Class klass = object.getClass(); + final Field[] fields = klass.getFields(); + final int length = fields.length; + if (length == 0) { + return null; + } + final String[] names = new String[length]; + for (int i = 0; i < length; i += 1) { + names[i] = fields[i].getName(); + } + return names; + } + + public String getString(final String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof String) { + return (String) object; + } + throw new JSONException("JSONObject[" + quote(key) + "] not a string."); + } + + public boolean has(final String key) { + return this.map.containsKey(key); + } + + public JSONObject increment(final String key) throws JSONException { + final Object value = this.opt(key); + if (value == null) { + this.put(key, 1); + } else if (value instanceof Integer) { + this.put(key, ((Integer) value).intValue() + 1); + } else if (value instanceof Long) { + this.put(key, ((Long) value).longValue() + 1); + } else if (value instanceof Double) { + this.put(key, ((Double) value).doubleValue() + 1); + } else if (value instanceof Float) { + this.put(key, ((Float) value).floatValue() + 1); + } else { + throw new JSONException("Unable to increment [" + quote(key) + "]."); + } + return this; + } + + public boolean isNull(final String key) { + return JSONObject.NULL.equals(this.opt(key)); + } + + @SuppressWarnings("rawtypes") + public Iterator keys() { + return this.keySet().iterator(); + } + + @SuppressWarnings("rawtypes") + public Set keySet() { + return this.map.keySet(); + } + + public int length() { + return this.map.size(); + } + + public JSONArray names() { + final JSONArray ja = new JSONArray(); + @SuppressWarnings("rawtypes") + final Iterator keys = this.keys(); + while (keys.hasNext()) { + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + public static String numberToString(final Number number) throws JSONException { + if (number == null) { + throw new JSONException("Null pointer"); + } + testValidity(number); + + // Shave off trailing zeros and decimal point, if possible. + + String string = number.toString(); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + public Object opt(final String key) { + return key == null ? null : this.map.get(key); + } + + public boolean optBoolean(final String key) { + return this.optBoolean(key, false); + } + + public boolean optBoolean(final String key, final boolean defaultValue) { + try { + return this.getBoolean(key); + } catch (final Exception e) { + return defaultValue; + } + } + + public double optDouble(final String key) { + return this.optDouble(key, Double.NaN); + } + + public double optDouble(final String key, final double defaultValue) { + try { + return this.getDouble(key); + } catch (final Exception e) { + return defaultValue; + } + } + + public int optInt(final String key) { + return this.optInt(key, 0); + } + + public int optInt(final String key, final int defaultValue) { + try { + return this.getInt(key); + } catch (final Exception e) { + return defaultValue; + } + } + + public JSONArray optJSONArray(final String key) { + final Object o = this.opt(key); + return o instanceof JSONArray ? (JSONArray) o : null; + } + + public JSONObject optJSONObject(final String key) { + final Object object = this.opt(key); + return object instanceof JSONObject ? (JSONObject) object : null; + } + + public long optLong(final String key) { + return this.optLong(key, 0); + } + + public long optLong(final String key, final long defaultValue) { + try { + return this.getLong(key); + } catch (final Exception e) { + return defaultValue; + } + } + + public String optString(final String key) { + return this.optString(key, ""); + } + + public String optString(final String key, final String defaultValue) { + final Object object = this.opt(key); + return NULL.equals(object) ? defaultValue : object.toString(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void populateMap(final Object bean) { + final Class klass = bean.getClass(); + + // If klass is a System class then set includeSuperClass to false. + + final boolean includeSuperClass = klass.getClassLoader() != null; + + final Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i += 1) { + try { + final Method method = methods[i]; + if (Modifier.isPublic(method.getModifiers())) { + final String name = method.getName(); + String key = ""; + if (name.startsWith("get")) { + if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { + key = ""; + } else { + key = name.substring(3); + } + } else if (name.startsWith("is")) { + key = name.substring(2); + } + if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { + if (key.length() == 1) { + key = key.toLowerCase(); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase() + key.substring(1); + } + + final Object result = method.invoke(bean, (Object[]) null); + if (result != null) { + this.map.put(key, wrap(result)); + } + } + } + } catch (final Exception ignore) { + } + } + } + + public JSONObject put(final String key, final boolean value) throws JSONException { + this.put(key, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + @SuppressWarnings("rawtypes") + public JSONObject put(final String key, final Collection value) throws JSONException { + this.put(key, new JSONArray(value)); + return this; + } + + public JSONObject put(final String key, final double value) throws JSONException { + this.put(key, new Double(value)); + return this; + } + + public JSONObject put(final String key, final int value) throws JSONException { + this.put(key, new Integer(value)); + return this; + } + + public JSONObject put(final String key, final long value) throws JSONException { + this.put(key, new Long(value)); + return this; + } + + public JSONObject put(final String key, @SuppressWarnings("rawtypes") final Map value) throws JSONException { + this.put(key, new JSONObject(value)); + return this; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public JSONObject put(String key, final Object value) throws JSONException { + String pooled; + if (key == null) { + throw new JSONException("Null key."); + } + if (value != null) { + testValidity(value); + pooled = (String) keyPool.get(key); + if (pooled == null) { + if (keyPool.size() >= keyPoolSize) { + keyPool = new HashMap(keyPoolSize); + } + keyPool.put(key, key); + } else { + key = pooled; + } + this.map.put(key, value); + } else { + this.remove(key); + } + return this; + } + + public JSONObject putOnce(final String key, final Object value) throws JSONException { + if (key != null && value != null) { + if (this.opt(key) != null) { + throw new JSONException("Duplicate key \"" + key + "\""); + } + this.put(key, value); + } + return this; + } + + public JSONObject putOpt(final String key, final Object value) throws JSONException { + if (key != null && value != null) { + this.put(key, value); + } + return this; + } + + public static String quote(final String string) { + final StringWriter sw = new StringWriter(); + synchronized (sw.getBuffer()) { + try { + return quote(string, sw).toString(); + } catch (final IOException ignored) { + // will never happen - we are writing to a string writer + return ""; + } + } + } + + public static Writer quote(final String string, final Writer w) throws IOException { + if (string == null || string.length() == 0) { + w.write("\"\""); + return w; + } + + char b; + char c = 0; + String hhhh; + int i; + final int len = string.length(); + + w.write('"'); + for (i = 0; i < len; i += 1) { + b = c; + c = string.charAt(i); + switch (c) { + case '\\': + case '"': + w.write('\\'); + w.write(c); + break; + case '/': + if (b == '<') { + w.write('\\'); + } + w.write(c); + break; + case '\b': + w.write("\\b"); + break; + case '\t': + w.write("\\t"); + break; + case '\n': + w.write("\\n"); + break; + case '\f': + w.write("\\f"); + break; + case '\r': + w.write("\\r"); + break; + default: + if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { + w.write("\\u"); + hhhh = Integer.toHexString(c); + w.write("0000", 0, 4 - hhhh.length()); + w.write(hhhh); + } else { + w.write(c); + } + } + } + w.write('"'); + return w; + } + + public Object remove(final String key) { + return this.map.remove(key); + } + + public static Object stringToValue(final String string) { + Double d; + if (string.equals("")) { + return string; + } + if (string.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (string.equalsIgnoreCase("null")) { + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. + * If a number cannot be produced, then the value will just + * be a string. Note that the plus and implied string + * conventions are non-standard. A JSON parser may accept + * non-JSON forms as long as it accepts all correct JSON forms. + */ + + final char b = string.charAt(0); + if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { + try { + if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) { + d = Double.valueOf(string); + if (!d.isInfinite() && !d.isNaN()) { + return d; + } + } else { + final Long myLong = new Long(string); + if (myLong.longValue() == myLong.intValue()) { + return new Integer(myLong.intValue()); + } else { + return myLong; + } + } + } catch (final Exception ignore) { + } + } + return string; + } + + public static void testValidity(final Object o) throws JSONException { + if (o != null) { + if (o instanceof Double) { + if (((Double) o).isInfinite() || ((Double) o).isNaN()) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } else if (o instanceof Float) { + if (((Float) o).isInfinite() || ((Float) o).isNaN()) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } + } + } + + public JSONArray toJSONArray(final JSONArray names) throws JSONException { + if (names == null || names.length() == 0) { + return null; + } + final JSONArray ja = new JSONArray(); + for (int i = 0; i < names.length(); i += 1) { + ja.put(this.opt(names.getString(i))); + } + return ja; + } + + @Override + public String toString() { + try { + return this.toString(0); + } catch (final Exception e) { + return null; + } + } + + public String toString(final int indentFactor) throws JSONException { + final StringWriter w = new StringWriter(); + synchronized (w.getBuffer()) { + return this.write(w, indentFactor, 0).toString(); + } + } + + @SuppressWarnings("rawtypes") + public static String valueToString(final Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString) { + Object object; + try { + object = ((JSONString) value).toJSONString(); + } catch (final Exception e) { + throw new JSONException(e); + } + if (object instanceof String) { + return (String) object; + } + throw new JSONException("Bad value from toJSONString: " + object); + } + if (value instanceof Number) { + return numberToString((Number) value); + } + if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + return new JSONObject((Map) value).toString(); + } + if (value instanceof Collection) { + return new JSONArray((Collection) value).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + return quote(value.toString()); + } + + @SuppressWarnings("rawtypes") + public static Object wrap(final Object object) { + try { + if (object == null) { + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String) { + return object; + } + + if (object instanceof Collection) { + return new JSONArray((Collection) object); + } + if (object.getClass().isArray()) { + return new JSONArray(object); + } + if (object instanceof Map) { + return new JSONObject((Map) object); + } + final Package objectPackage = object.getClass().getPackage(); + final String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null) { + return object.toString(); + } + return new JSONObject(object); + } catch (final Exception exception) { + return null; + } + } + + public Writer write(final Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } + + @SuppressWarnings("rawtypes") + static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException { + if (value == null || value.equals(null)) { + writer.write("null"); + } else if (value instanceof JSONObject) { + ((JSONObject) value).write(writer, indentFactor, indent); + } else if (value instanceof JSONArray) { + ((JSONArray) value).write(writer, indentFactor, indent); + } else if (value instanceof Map) { + new JSONObject((Map) value).write(writer, indentFactor, indent); + } else if (value instanceof Collection) { + new JSONArray((Collection) value).write(writer, indentFactor, indent); + } else if (value.getClass().isArray()) { + new JSONArray(value).write(writer, indentFactor, indent); + } else if (value instanceof Number) { + writer.write(numberToString((Number) value)); + } else if (value instanceof Boolean) { + writer.write(value.toString()); + } else if (value instanceof JSONString) { + Object o; + try { + o = ((JSONString) value).toJSONString(); + } catch (final Exception e) { + throw new JSONException(e); + } + writer.write(o != null ? o.toString() : quote(value.toString())); + } else { + quote(value.toString(), writer); + } + return writer; + } + + static final void indent(final Writer writer, final int indent) throws IOException { + for (int i = 0; i < indent; i += 1) { + writer.write(' '); + } + } + + Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException { + try { + boolean commanate = false; + final int length = this.length(); + @SuppressWarnings("rawtypes") + final Iterator keys = this.keys(); + writer.write('{'); + + if (length == 1) { + final Object key = keys.next(); + writer.write(quote(key.toString())); + writer.write(':'); + if (indentFactor > 0) { + writer.write(' '); + } + writeValue(writer, this.map.get(key), indentFactor, indent); + } else if (length != 0) { + final int newindent = indent + indentFactor; + while (keys.hasNext()) { + final Object key = keys.next(); + if (commanate) { + writer.write(','); + } + if (indentFactor > 0) { + writer.write('\n'); + } + indent(writer, newindent); + writer.write(quote(key.toString())); + writer.write(':'); + if (indentFactor > 0) { + writer.write(' '); + } + writeValue(writer, this.map.get(key), indentFactor, newindent); + commanate = true; + } + if (indentFactor > 0) { + writer.write('\n'); + } + indent(writer, indent); + } + writer.write('}'); + return writer; + } catch (final IOException exception) { + throw new JSONException(exception); + } + } +} diff --git a/src/cn/citycraft/RealBackpacks/json/JSONString.java b/src/cn/citycraft/RealBackpacks/json/JSONString.java new file mode 100644 index 0000000..9eda0e8 --- /dev/null +++ b/src/cn/citycraft/RealBackpacks/json/JSONString.java @@ -0,0 +1,6 @@ +package cn.citycraft.RealBackpacks.json; + +public interface JSONString { + + public String toJSONString(); +} \ No newline at end of file diff --git a/src/cn/citycraft/RealBackpacks/json/JSONTokener.java b/src/cn/citycraft/RealBackpacks/json/JSONTokener.java new file mode 100644 index 0000000..8cf7b97 --- /dev/null +++ b/src/cn/citycraft/RealBackpacks/json/JSONTokener.java @@ -0,0 +1,315 @@ +package cn.citycraft.RealBackpacks.json; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; + +/* + * Copyright (c) 2002 JSON.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * The Software shall be used for Good, not Evil. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +public class JSONTokener { + + private long character; + private boolean eof; + private long index; + private long line; + private char previous; + private final Reader reader; + private boolean usePrevious; + + public JSONTokener(final Reader reader) { + this.reader = reader.markSupported() ? reader : new BufferedReader(reader); + this.eof = false; + this.usePrevious = false; + this.previous = 0; + this.index = 0; + this.character = 1; + this.line = 1; + } + + public JSONTokener(final InputStream inputStream) throws JSONException { + this(new InputStreamReader(inputStream)); + } + + public JSONTokener(final String s) { + this(new StringReader(s)); + } + + public void back() throws JSONException { + if (this.usePrevious || this.index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.index -= 1; + this.character -= 1; + this.usePrevious = true; + this.eof = false; + } + + public static int dehexchar(final char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'A' && c <= 'F') { + return c - ('A' - 10); + } + if (c >= 'a' && c <= 'f') { + return c - ('a' - 10); + } + return -1; + } + + public boolean end() { + return this.eof && !this.usePrevious; + } + + public boolean more() throws JSONException { + this.next(); + if (this.end()) { + return false; + } + this.back(); + return true; + } + + public char next() throws JSONException { + int c; + if (this.usePrevious) { + this.usePrevious = false; + c = this.previous; + } else { + try { + c = this.reader.read(); + } catch (final IOException exception) { + throw new JSONException(exception); + } + + if (c <= 0) { // End of stream + this.eof = true; + c = 0; + } + } + this.index += 1; + if (this.previous == '\r') { + this.line += 1; + this.character = c == '\n' ? 0 : 1; + } else if (c == '\n') { + this.line += 1; + this.character = 0; + } else { + this.character += 1; + } + this.previous = (char) c; + return this.previous; + } + + public char next(final char c) throws JSONException { + final char n = this.next(); + if (n != c) { + throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); + } + return n; + } + + public String next(final int n) throws JSONException { + if (n == 0) { + return ""; + } + + final char[] chars = new char[n]; + int pos = 0; + + while (pos < n) { + chars[pos] = this.next(); + if (this.end()) { + throw this.syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } + + public char nextClean() throws JSONException { + for (;;) { + final char c = this.next(); + if (c == 0 || c > ' ') { + return c; + } + } + } + + public String nextString(final char quote) throws JSONException { + char c; + final StringBuffer sb = new StringBuffer(); + for (;;) { + c = this.next(); + switch (c) { + case 0: + case '\n': + case '\r': + throw this.syntaxError("Unterminated string"); + case '\\': + c = this.next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char) Integer.parseInt(this.next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); + } + break; + default: + if (c == quote) { + return sb.toString(); + } + sb.append(c); + } + } + } + + public String nextTo(final char delimiter) throws JSONException { + final StringBuffer sb = new StringBuffer(); + for (;;) { + final char c = this.next(); + if (c == delimiter || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + public String nextTo(final String delimiters) throws JSONException { + char c; + final StringBuffer sb = new StringBuffer(); + for (;;) { + c = this.next(); + if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + public Object nextValue() throws JSONException { + char c = this.nextClean(); + String string; + + switch (c) { + case '"': + case '\'': + return this.nextString(c); + case '{': + this.back(); + return new JSONObject(this); + case '[': + this.back(); + return new JSONArray(this); + } + + /* + * Handle unquoted text. This could be the values true, false, or + * null, or it can be a number. An implementation (such as this one) + * is allowed to also accept non-standard forms. + * + * Accumulate characters until we reach the end of the text or a + * formatting character. + */ + + final StringBuffer sb = new StringBuffer(); + while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { + sb.append(c); + c = this.next(); + } + this.back(); + + string = sb.toString().trim(); + if ("".equals(string)) { + throw this.syntaxError("Missing value"); + } + return JSONObject.stringToValue(string); + } + + public char skipTo(final char to) throws JSONException { + char c; + try { + final long startIndex = this.index; + final long startCharacter = this.character; + final long startLine = this.line; + this.reader.mark(1000000); + do { + c = this.next(); + if (c == 0) { + this.reader.reset(); + this.index = startIndex; + this.character = startCharacter; + this.line = startLine; + return c; + } + } while (c != to); + } catch (final IOException exc) { + throw new JSONException(exc); + } + + this.back(); + return c; + } + + public JSONException syntaxError(final String message) { + return new JSONException(message + this.toString()); + } + + @Override + public String toString() { + return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; + } +} diff --git a/src/cn/citycraft/RealBackpacks/listeners/InventoryListener.java b/src/cn/citycraft/RealBackpacks/listeners/InventoryListener.java index 25c7323..aeddf08 100644 --- a/src/cn/citycraft/RealBackpacks/listeners/InventoryListener.java +++ b/src/cn/citycraft/RealBackpacks/listeners/InventoryListener.java @@ -16,9 +16,9 @@ import org.bukkit.inventory.meta.ItemMeta; import cn.citycraft.RealBackpacks.RealBackpacks; import cn.citycraft.RealBackpacks.config.PlayerConfig; -import cn.citycraft.RealBackpacks.util.InvJsonUtils; import cn.citycraft.RealBackpacks.util.MysqlFunctions; import cn.citycraft.RealBackpacks.util.RBUtil; +import cn.citycraft.RealBackpacks.util.Serialization; public class InventoryListener implements Listener { @@ -32,8 +32,7 @@ public class InventoryListener implements Listener { public void onInventoryClose(final InventoryCloseEvent e) { final String name = e.getPlayer().getName(); final Inventory inv = e.getView().getTopInventory(); - // final List invString = Serialization.toString(inv); - final List invString = InvJsonUtils.invToList(inv); + final List invString = Serialization.toString(inv); final String backpack = plugin.playerData.get(name); plugin.playerData.remove(name); final String adminBackpack = plugin.adminFullView.get(name); @@ -51,8 +50,7 @@ public class InventoryListener implements Listener { e.printStackTrace(); } } else { - PlayerConfig.getInstance(plugin, name).set( - backpack + ".Inventory", invString); + PlayerConfig.getInstance(plugin, name).set(backpack + ".Inventory", invString); PlayerConfig.save(); } } @@ -71,8 +69,8 @@ public class InventoryListener implements Listener { e.printStackTrace(); } } else { - PlayerConfig.getInstance(plugin, split[1]).set( - split[0] + ".Inventory", invString); + PlayerConfig.getInstance(plugin, split[1]). + set(split[0] + ".Inventory", invString); PlayerConfig.save(); } } diff --git a/src/cn/citycraft/RealBackpacks/listeners/PlayerListener.java b/src/cn/citycraft/RealBackpacks/listeners/PlayerListener.java index 363ffde..c5f7a7b 100644 --- a/src/cn/citycraft/RealBackpacks/listeners/PlayerListener.java +++ b/src/cn/citycraft/RealBackpacks/listeners/PlayerListener.java @@ -22,9 +22,9 @@ import org.bukkit.inventory.ItemStack; import cn.citycraft.RealBackpacks.RealBackpacks; import cn.citycraft.RealBackpacks.config.FileConfig; import cn.citycraft.RealBackpacks.config.PlayerConfig; -import cn.citycraft.RealBackpacks.util.InvJsonUtils; import cn.citycraft.RealBackpacks.util.MysqlFunctions; import cn.citycraft.RealBackpacks.util.RBUtil; +import cn.citycraft.RealBackpacks.util.Serialization; public class PlayerListener implements Listener { @@ -98,8 +98,7 @@ public class PlayerListener implements Listener { if (!config.isSet(backpack + ".Inventory")) { inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3))); } else { - //inv = Serialization.toInventory(config.getStringList(backpack + ".Inventory"), key.get(3), Integer.parseInt(key.get(0))); - inv = InvJsonUtils.listToInventory(config.getStringList(backpack + ".Inventory"), key.get(3), Integer.parseInt(key.get(0))); + inv = Serialization.toInventory(config.getStringList(backpack + ".Inventory"), key.get(3), Integer.parseInt(key.get(0))); } } if (p.getOpenInventory().getTopInventory() != null) { @@ -205,7 +204,7 @@ public class PlayerListener implements Listener { if (config.getStringList(backpack + ".Inventory") == null) { continue; } - binv = InvJsonUtils.listToInventory(config.getStringList(backpack + ".Inventory"), key.get(3), Integer.parseInt(key.get(0))); + binv = Serialization.toInventory(config.getStringList(backpack + ".Inventory"), key.get(3), Integer.parseInt(key.get(0))); } if (plugin.playerData.containsKey(name)) { if (p.getItemOnCursor() != null) { diff --git a/src/cn/citycraft/RealBackpacks/util/InvJsonUtils.java b/src/cn/citycraft/RealBackpacks/util/InvJsonUtils.java deleted file mode 100644 index 48b226d..0000000 --- a/src/cn/citycraft/RealBackpacks/util/InvJsonUtils.java +++ /dev/null @@ -1,124 +0,0 @@ -package cn.citycraft.RealBackpacks.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.ConfigurationSerialization; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import com.google.gson.JsonIOException; - -public class InvJsonUtils { - public static String NullString = "|--空--|"; - public static String SplitString = "|-分割-|"; - - public static String invToJson(Inventory inv) { - List json = invToList(inv); - return JsonUtils.toJson(json); - } - - public static List stringToList(final String listString) { - return Arrays.asList(listString.split(SplitString)); - } - - public static String listToString(final List list) { - String newString = null; - for (final String s : list) { - if (newString == null) { - newString = s; - } else { - newString = newString + SplitString + s; - } - } - return newString; - } - - public static List invToList(final Inventory inv) { - final List result = new ArrayList(); - for (final ConfigurationSerializable item : inv.getContents()) { - if (item == null) { - result.add(NullString); - } else { - result.add(JsonUtils.toJson(serialize(item)).toString()); - } - } - return result; - } - - @SuppressWarnings("unchecked") - public static Inventory jsonToInv(String json ,String invname) { - List list = (List) JsonUtils.toList(json); - int size = list.size(); - Inventory inv = listToInventory(list, invname, size); - return inv; - } - - public static String itemToString(final ItemStack i) { - return JsonUtils.toJson(serialize(i)).toString(); - } - - @SuppressWarnings("unchecked") - public static Inventory listToInventory(final List stringItems, - final String name, final int size) { - final Inventory inv = Bukkit.createInventory(null, size, - ChatColor.translateAlternateColorCodes('&', name)); - final List contents = new ArrayList(); - for (final String piece : stringItems) { - if (piece.equalsIgnoreCase(NullString)) { - contents.add(null); - } else { - try { - final ItemStack item = (ItemStack) deserialize((Map) JsonUtils - .toMap(piece)); - contents.add(item); - } catch (final JsonIOException e) { - - } - } - } - final ItemStack[] items = new ItemStack[contents.size()]; - for (int x = 0; x < contents.size(); x++) { - items[x] = contents.get(x); - } - inv.setContents(items); - return inv; - } - - public static Map serialize(final ConfigurationSerializable cs) { - final Map serialized = recreateMap(cs.serialize()); - for (final Entry entry : serialized.entrySet()) { - if (entry.getValue() instanceof ConfigurationSerializable) { - entry.setValue(serialize((ConfigurationSerializable) entry.getValue())); - } - } - serialized.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(cs.getClass())); - return serialized; - } - - public static Map recreateMap(final Map original) { - final Map map = new HashMap(); - for (final Entry entry : original.entrySet()) { - map.put(entry.getKey(), entry.getValue()); - } - return map; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static ConfigurationSerializable deserialize(final Map map) { - for (final Entry entry : map.entrySet()) { - if (entry.getValue() instanceof Map && ((Map) entry.getValue()).containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { - entry.setValue(deserialize((Map) entry.getValue())); - } - } - return ConfigurationSerialization.deserializeObject(map); - } - -} diff --git a/src/cn/citycraft/RealBackpacks/util/JsonUtils.java b/src/cn/citycraft/RealBackpacks/util/JsonUtils.java deleted file mode 100644 index 5d292bc..0000000 --- a/src/cn/citycraft/RealBackpacks/util/JsonUtils.java +++ /dev/null @@ -1,121 +0,0 @@ -package cn.citycraft.RealBackpacks.util; - -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * Gson类库的封装工具类,专门负责解析json数据
- * 内部实现了Gson对象的单例 - * @author zhiweiofli - * @version 1.0 - * @since 2012-9-18 - */ -public class JsonUtils { - - private static Gson gson = null; - - static { - if (gson == null) { - gson = new Gson(); - } - } - - private JsonUtils() { - - } - - /** - * 将对象转换成json格式 - * - * @param obj - * @return - */ - public static String toJson(Object obj) { - String jsonStr = null; - if (gson != null) { - jsonStr = gson.toJson(obj); - } - return jsonStr; - } - - - /** - * 将json格式转换成list对象 - * - * @param jsonStr - * @return - */ - public static List toList(String jsonStr) { - List objList = null; - if (gson != null) { - Type type = new TypeToken>() {}.getType(); - objList = gson.fromJson(jsonStr, type); - } - return objList; - } - - /** - * 将json格式转换成list对象,并准确指定类型 - * @param jsonStr - * @param type - * @return - */ - public static List toList(String jsonStr, Type type) { - List objList = null; - if (gson != null) { - objList = gson.fromJson(jsonStr, type); - } - return objList; - } - - /** - * 将json格式转换成map对象 - * - * @param jsonStr - * @return - */ - public static Map toMap(String jsonStr) { - Map objMap = null; - if (gson != null) { - Type type = new TypeToken>() { - }.getType(); - objMap = gson.fromJson(jsonStr, type); - } - return objMap; - } - - /** - * 将json转换成bean对象 - * - * @param jsonStr - * @return - */ - public static Object toObject(String jsonStr, Class cl) { - Object obj = null; - if (gson != null) { - obj = gson.fromJson(jsonStr, cl); - } - return obj; - } - - /** - * 根据 - * - * @param jsonStr - * @param key - * @return - */ - public static Object getJsonValue(String jsonStr, String key) { - Object rulsObj = null; - Map rulsMap = toMap(jsonStr); - if (rulsMap != null && rulsMap.size() > 0) { - rulsObj = rulsMap.get(key); - } - return rulsObj; - } - -} \ No newline at end of file diff --git a/src/cn/citycraft/RealBackpacks/util/MysqlFunctions.java b/src/cn/citycraft/RealBackpacks/util/MysqlFunctions.java index 3fd1a44..750a2bd 100644 --- a/src/cn/citycraft/RealBackpacks/util/MysqlFunctions.java +++ b/src/cn/citycraft/RealBackpacks/util/MysqlFunctions.java @@ -16,7 +16,7 @@ import cn.citycraft.RealBackpacks.RealBackpacks; public class MysqlFunctions { - private static RealBackpacks plugin; + private static cn.citycraft.RealBackpacks.RealBackpacks plugin; public static void setMysqlFunc(final RealBackpacks plugin) { MysqlFunctions.plugin = plugin; @@ -56,7 +56,7 @@ public class MysqlFunctions { e.printStackTrace(); } } - + public static void addBackpackData(final String playerName, final String backpack, final List invString) throws SQLException { plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override @@ -75,14 +75,14 @@ public class MysqlFunctions { state = conn.prepareStatement("UPDATE rb_data SET player=?, backpack=?, inventory=? WHERE player=? AND backpack=?;"); state.setString(1, playerName); state.setString(2, backpack); - state.setString(3, InvJsonUtils.listToString(invString)); + state.setString(3, Serialization.listToString(invString)); state.setString(4, playerName); state.setString(5, backpack); } else { state = conn.prepareStatement("INSERT INTO rb_data (player, backpack, inventory) VALUES(?, ?, ?);"); state.setString(1, playerName); state.setString(2, backpack); - state.setString(3, InvJsonUtils.listToString(invString)); + state.setString(3, Serialization.listToString(invString)); } } state.executeUpdate(); @@ -108,7 +108,7 @@ public class MysqlFunctions { if (res.next()) { final String invString = res.getString(1); if (invString != null) { - returnInv = InvJsonUtils.listToInventory(InvJsonUtils.stringToList(invString), ChatColor.translateAlternateColorCodes('&', plugin.backpackData.get(backpack).get(3)), Integer.parseInt(plugin.backpackData.get(backpack).get(0))); + returnInv = Serialization.toInventory(Serialization.stringToList(invString), ChatColor.translateAlternateColorCodes('&', plugin.backpackData.get(backpack).get(3)), Integer.parseInt(plugin.backpackData.get(backpack).get(0))); } else { returnInv = null; } diff --git a/src/cn/citycraft/RealBackpacks/util/Serialization.java b/src/cn/citycraft/RealBackpacks/util/Serialization.java new file mode 100644 index 0000000..63b2bc4 --- /dev/null +++ b/src/cn/citycraft/RealBackpacks/util/Serialization.java @@ -0,0 +1,163 @@ +package cn.citycraft.RealBackpacks.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import cn.citycraft.RealBackpacks.json.JSONArray; +import cn.citycraft.RealBackpacks.json.JSONException; +import cn.citycraft.RealBackpacks.json.JSONObject; + +/** + * Fancy JSON serialization mostly by evilmidget38. + * + * @author evilmidget38, gomeow + * + */ +public class Serialization { + public static String NullString = "|--空--|"; + public static String SplitString = "|-分割-|"; + + @SuppressWarnings("unchecked") + public static Map toMap(final JSONObject object) + throws JSONException { + final Map map = new HashMap(); + final Iterator keys = object.keys(); + while (keys.hasNext()) { + final String key = keys.next(); + map.put(key, fromJson(object.get(key))); + } + return map; + } + + private static Object fromJson(final Object json) throws JSONException { + if (json == JSONObject.NULL) { + return null; + } else if (json instanceof JSONObject) { + return toMap((JSONObject) json); + } else if (json instanceof JSONArray) { + return toList((JSONArray) json); + } else { + return json; + } + } + + public static List toList(final JSONArray array) + throws JSONException { + final List list = new ArrayList(); + for (int i = 0; i < array.length(); i++) { + list.add(fromJson(array.get(i))); + } + return list; + } + + public static List stringToList(final String listString) { + return Arrays.asList(listString.split(SplitString)); + } + + public static String listToString(final List list) { + String newString = null; + for (final String s : list) { + if (newString == null) { + newString = s; + } else { + newString = newString + SplitString + s; + } + } + return newString; + } + + public static List toString(final Inventory inv) { + final List result = new ArrayList(); + final List items = new ArrayList(); + for (final ItemStack is : inv.getContents()) { + items.add(is); + } + for (final ConfigurationSerializable cs : items) { + if (cs == null) { + result.add(NullString); + } else { + result.add(new JSONObject(serialize(cs)).toString()); + } + } + return result; + } + + public static Inventory toInventory(final List stringItems, + final String name, final int size) { + final Inventory inv = Bukkit.createInventory(null, size, + ChatColor.translateAlternateColorCodes('&', name)); + final List contents = new ArrayList(); + for (final String piece : stringItems) { + if (piece.equalsIgnoreCase(NullString)) { + contents.add(null); + } else { + try { + final ItemStack item = (ItemStack) deserialize(toMap(new JSONObject( + piece))); + contents.add(item); + } catch (final JSONException e) { + e.printStackTrace(); + } + } + } + final ItemStack[] items = new ItemStack[contents.size()]; + for (int x = 0; x < contents.size(); x++) { + items[x] = contents.get(x); + } + inv.setContents(items); + return inv; + } + + public static Map serialize( + final ConfigurationSerializable cs) { + final Map serialized = recreateMap(cs.serialize()); + for (final Entry entry : serialized.entrySet()) { + if (entry.getValue() instanceof ConfigurationSerializable) { + entry.setValue(serialize((ConfigurationSerializable) entry + .getValue())); + } + } + serialized.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, + ConfigurationSerialization.getAlias(cs.getClass())); + return serialized; + } + + public static Map recreateMap( + final Map original) { + final Map map = new HashMap(); + for (final Entry entry : original.entrySet()) { + map.put(entry.getKey(), entry.getValue()); + } + return map; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static ConfigurationSerializable deserialize( + final Map map) { + for (final Entry entry : map.entrySet()) { + if (entry.getValue() instanceof Map + && ((Map) entry.getValue()) + .containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { + entry.setValue(deserialize((Map) entry.getValue())); + } + if (entry.getValue() instanceof Double) { + Double db = (Double) entry.getValue(); + int value = db.intValue(); + entry.setValue(value); + } + } + return ConfigurationSerialization.deserializeObject(map); + } +}