pax_global_header00006660000000000000000000000064125562016270014520gustar00rootroot0000000000000052 comment=9bcdf62f6a801bad18afd621cb580076e141d987 json-smart-v2-2.2/000077500000000000000000000000001255620162700140055ustar00rootroot00000000000000json-smart-v2-2.2/.gitignore000066400000000000000000000006261255620162700160010ustar00rootroot00000000000000 /json-smart/target /json-smart/.settings /json-smart/.classpath /json-smart/.project /parent/.project /parent/.settings /json-smart/src/test/java/asm /asm/.classpath /asm/.project /asm/.settings /asm/targetjson-smart-backport/.classpath json-smart-backport/.project json-smart-backport/.settings asm/target/ json-smart-backport/target/ json-smart/target/ **/.project **/bin *.classpath *.project *.prefs json-smart-v2-2.2/README.md000066400000000000000000000026401255620162700152660ustar00rootroot00000000000000# json-smart-v2 == Changelog: == *V 2.2* * rename asm to accessors-smart due to conflict name with asm.ow2.org lib. * fix OSGI error * add support for BigDecimal * improve JSONObject.getAsNumber() helper * add a Field Remaper *V 2.1* * net.minidev.json.mapper renamed to net.minidev.json.writer * Add ACCEPT_TAILLING_SPACE Parssing Flag. * Mapper classes now non static. * Reader mapper are now available in net.minidev.json.reader.JsonReader class * Writer mapper are now available in net.minidev.json.writer.JsonWriter class *V 2.0* * Fix Double Identification [http://code.google.com/p/json-smart/issues/detail?id=44 issue 44] * Fix Collection Interface Serialisation * Fix security Exception in ASM code * Project moved to GitHub * Fix [http://code.google.com/p/json-smart/issues/detail?id=42 issue 42] *V 2.0-RC3* * Add custom data binding inside the ASM layer. * Add Date support * Add \x escape sequence support [http://code.google.com/p/json-smart/issues/detail?id=39 issue 39] * fix issue [http://code.google.com/p/json-smart/issues/detail?id=37 issue 37] *V 2.0-RC2* * Fix critical [http://code.google.com/p/json-smart/issues/detail?id=23 issue 23] * Improve Javadoc in JSONStyle [http://code.google.com/p/json-smart/issues/detail?id=23 issue 24] *V 2.0-RC1* * speed improvement in POJO manipulation * add JSONStyle.LT_COMPRESS predefined generate strct json, but ignoring / escapement. json-smart-v2-2.2/accessors-smart/000077500000000000000000000000001255620162700171165ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/.gitignore000066400000000000000000000000111255620162700210760ustar00rootroot00000000000000/target/ json-smart-v2-2.2/accessors-smart/pom.xml000066400000000000000000000040511255620162700204330ustar00rootroot00000000000000 4.0.0 accessors-smart bundle 1.1 net.minidev minidev-parent 2.2 ../parent/pom.xml ASM based accessors helper used by json-smart Java reflect give poor performance on getter setter an constructor calls, accessors-smart use ASM to speed up those calls. junit junit test org.ow2.asm asm 5.0.3 org.apache.felix maven-bundle-plugin 2.3.7 true ${project.groupId}.${project.artifactId} ${project.artifactId} ${project.version} net.minidev.asm, net.minidev.asm.ex asm;groupId=org.ow2.asm;inline=true json-smart-v2-2.2/accessors-smart/src/000077500000000000000000000000001255620162700177055ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/main/000077500000000000000000000000001255620162700206315ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/main/java/000077500000000000000000000000001255620162700215525ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/main/java/net/000077500000000000000000000000001255620162700223405ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/000077500000000000000000000000001255620162700237735ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/000077500000000000000000000000001255620162700245535ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/ASMUtil.java000066400000000000000000000172071255620162700267030ustar00rootroot00000000000000package net.minidev.asm; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static org.objectweb.asm.Opcodes.CHECKCAST; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; import java.lang.reflect.Field; import java.util.HashMap; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; /** * ASM Utils used to simplify class generation * * @author uriel Chemouni */ public class ASMUtil { /** * Append the call of proper autoboxing method for the given primitif type. */ public static void autoBoxing(MethodVisitor mv, Class clz) { autoBoxing(mv, Type.getType(clz)); } /** * Extract all Accessor for the field of the given class. * * @param type * @return all Accessor available */ static public Accessor[] getAccessors(Class type, FieldFilter filter) { Class nextClass = type; HashMap map = new HashMap(); if (filter == null) filter = BasicFiledFilter.SINGLETON; while (nextClass != Object.class) { Field[] declaredFields = nextClass.getDeclaredFields(); for (Field field : declaredFields) { String fn = field.getName(); if (map.containsKey(fn)) continue; Accessor acc = new Accessor(nextClass, field, filter); if (!acc.isUsable()) continue; map.put(fn, acc); } nextClass = nextClass.getSuperclass(); } return map.values().toArray(new Accessor[map.size()]); } /** * Append the call of proper autoboxing method for the given primitif type. */ protected static void autoBoxing(MethodVisitor mv, Type fieldType) { switch (fieldType.getSort()) { case Type.BOOLEAN: mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); break; case Type.BYTE: mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); break; case Type.CHAR: mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); break; case Type.SHORT: mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); break; case Type.INT: mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); break; case Type.FLOAT: mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); break; case Type.LONG: mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); break; case Type.DOUBLE: mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); break; } } /** * Append the call of proper extract primitive type of an boxed object. */ protected static void autoUnBoxing1(MethodVisitor mv, Type fieldType) { switch (fieldType.getSort()) { case Type.BOOLEAN: mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"); break; case Type.BYTE: mv.visitTypeInsn(CHECKCAST, "java/lang/Byte"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B"); break; case Type.CHAR: mv.visitTypeInsn(CHECKCAST, "java/lang/Character"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C"); break; case Type.SHORT: mv.visitTypeInsn(CHECKCAST, "java/lang/Short"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S"); break; case Type.INT: mv.visitTypeInsn(CHECKCAST, "java/lang/Integer"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I"); break; case Type.FLOAT: mv.visitTypeInsn(CHECKCAST, "java/lang/Float"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F"); break; case Type.LONG: mv.visitTypeInsn(CHECKCAST, "java/lang/Long"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J"); break; case Type.DOUBLE: mv.visitTypeInsn(CHECKCAST, "java/lang/Double"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D"); break; case Type.ARRAY: mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); break; default: mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); } } /** * Append the call of proper extract primitive type of an boxed object. this * methode use Number interface to unbox object */ protected static void autoUnBoxing2(MethodVisitor mv, Type fieldType) { switch (fieldType.getSort()) { case Type.BOOLEAN: mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"); break; case Type.BYTE: mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "byteValue", "()B"); break; case Type.CHAR: mv.visitTypeInsn(CHECKCAST, "java/lang/Character"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C"); break; case Type.SHORT: mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "shortValue", "()S"); break; case Type.INT: mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "intValue", "()I"); break; case Type.FLOAT: mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "floatValue", "()F"); break; case Type.LONG: mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "longValue", "()J"); break; case Type.DOUBLE: mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "doubleValue", "()D"); break; case Type.ARRAY: mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); break; default: mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); } } /** * return a array of new Label (used for switch/case generation) * * @param cnt * number of label to return */ public static Label[] newLabels(int cnt) { Label[] r = new Label[cnt]; for (int i = 0; i < cnt; i++) r[i] = new Label(); return r; } public static String getSetterName(String key) { int len = key.length(); char[] b = new char[len + 3]; b[0] = 's'; b[1] = 'e'; b[2] = 't'; char c = key.charAt(0); if (c >= 'a' && c <= 'z') c += 'A' - 'a'; b[3] = c; for (int i = 1; i < len; i++) { b[i + 3] = key.charAt(i); } return new String(b); } public static String getGetterName(String key) { int len = key.length(); char[] b = new char[len + 3]; b[0] = 'g'; b[1] = 'e'; b[2] = 't'; char c = key.charAt(0); if (c >= 'a' && c <= 'z') c += 'A' - 'a'; b[3] = c; for (int i = 1; i < len; i++) { b[i + 3] = key.charAt(i); } return new String(b); } public static String getIsName(String key) { int len = key.length(); char[] b = new char[len + 2]; b[0] = 'i'; b[1] = 's'; char c = key.charAt(0); if (c >= 'a' && c <= 'z') c += 'A' - 'a'; b[2] = c; for (int i = 1; i < len; i++) { b[i + 2] = key.charAt(i); } return new String(b); } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/Accessor.java000066400000000000000000000075131255620162700271660ustar00rootroot00000000000000package net.minidev.asm; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; /** * Contains all information needed to access a java field. * * field, getter setter * * this object is used internally by BeansAcces * * @see BeansAccess * * @author Uriel Chemouni */ public class Accessor { /** * Field to access */ protected Field field; /** * Setter Methods if available */ protected Method setter; /** * getter Methods if available */ protected Method getter; /** * Filed index in object */ protected int index; /** * Filed Class */ protected Class type; /** * Filed Type using JDK 5+ generics if available */ protected Type genericType; protected String fieldName; /** * getter for index * @return Index */ public int getIndex() { return index; } /** * is the field access using Field access type * @return if Accessor is public */ public boolean isPublic() { return setter == null; } /** * is the field is an enum field * @return if Accessor return an Enum Class */ public boolean isEnum() { return type.isEnum(); } /** * return the field name * @return the field name */ public String getName() { return fieldName; } /** * return field Class * @return field Class */ public Class getType() { return type; } /** * return generics field Type. * @return generics field Type. */ public Type getGenericType() { return genericType; } /** * @return true if the field can be read or write */ public boolean isUsable() { return field != null || getter != null || setter != null; } /** * @return true if the field can be read */ public boolean isReadable() { return field != null || getter != null; } /** * @return true if the field can be write */ public boolean isWritable() { return field != null || getter != null; } /** * build accessor for a field * * @param c * the handled class * @param field * the field to access */ public Accessor(Class c, Field field, FieldFilter filter) { this.fieldName = field.getName(); int m = field.getModifiers(); if ((m & (Modifier.STATIC | Modifier.TRANSIENT)) > 0) return; if ((m & Modifier.PUBLIC) > 0) this.field = field; String name = ASMUtil.getSetterName(field.getName()); try { setter = c.getDeclaredMethod(name, field.getType()); } catch (Exception e) { } boolean isBool = field.getType().equals(Boolean.TYPE); if (isBool) { name = ASMUtil.getIsName(field.getName()); } else { name = ASMUtil.getGetterName(field.getName()); } try { getter = c.getDeclaredMethod(name); } catch (Exception e) { } if (getter == null && isBool) { try { getter = c.getDeclaredMethod(ASMUtil.getGetterName(field.getName())); } catch (Exception e) { } } if (this.field == null && getter == null && setter == null) return; if (getter != null && !filter.canUse(field, getter)) getter = null; if (setter != null && !filter.canUse(field, setter)) setter = null; // disable if (getter == null && setter == null && this.field == null) return; this.type = field.getType(); this.genericType = field.getGenericType(); } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/BasicFiledFilter.java000066400000000000000000000010021255620162700305420ustar00rootroot00000000000000package net.minidev.asm; import java.lang.reflect.Field; import java.lang.reflect.Method; public class BasicFiledFilter implements FieldFilter { public final static BasicFiledFilter SINGLETON = new BasicFiledFilter(); @Override public boolean canUse(Field field) { return true; } @Override public boolean canUse(Field field, Method method) { return true; } @Override public boolean canRead(Field field) { return true; } @Override public boolean canWrite(Field field) { return true; } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/BeansAccess.java000066400000000000000000000123331255620162700275720ustar00rootroot00000000000000package net.minidev.asm; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.HashMap; import java.util.LinkedList; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; /** * Allow access reflect field using runtime generated accessor. BeansAccessor is * faster than java.lang.reflect.Method.invoke() * * @author uriel Chemouni */ public abstract class BeansAccess { private HashMap map; private Accessor[] accs; protected void setAccessor(Accessor[] accs) { int i = 0; this.accs = accs; map = new HashMap(); for (Accessor acc : accs) { acc.index = i++; map.put(acc.getName(), acc); } } public HashMap getMap() { return map; } public Accessor[] getAccessors() { return accs; } /** * cache used to store built BeansAccess */ private static ConcurrentHashMap, BeansAccess> cache = new ConcurrentHashMap, BeansAccess>(); // private final static ConcurrentHashMap> cache; /** * return the BeansAccess corresponding to a type * * @param type * to be access * @return the BeansAccess */ static public

BeansAccess

get(Class

type) { return get(type, null); } /** * return the BeansAccess corresponding to a type * * @param type * to be access * @return the BeansAccess */ static public

BeansAccess

get(Class

type, FieldFilter filter) { { @SuppressWarnings("unchecked") BeansAccess

access = (BeansAccess

) cache.get(type); if (access != null) return access; } // extract all access methodes Accessor[] accs = ASMUtil.getAccessors(type, filter); // create new class name String className = type.getName(); String accessClassName; if (className.startsWith("java.util.")) accessClassName = "net.minidev.asm." + className + "AccAccess"; else accessClassName = className.concat("AccAccess"); // extend class base loader DynamicClassLoader loader = new DynamicClassLoader(type.getClassLoader()); // try to load existing class Class accessClass = null; try { accessClass = loader.loadClass(accessClassName); } catch (ClassNotFoundException ignored) { } LinkedList> parentClasses = getParents(type); // if the class do not exists build it if (accessClass == null) { BeansAccessBuilder builder = new BeansAccessBuilder(type, accs, loader); for (Class c : parentClasses) builder.addConversion(BeansAccessConfig.classMapper.get(c)); accessClass = builder.bulid(); } try { @SuppressWarnings("unchecked") BeansAccess

access = (BeansAccess

) accessClass.newInstance(); access.setAccessor(accs); cache.putIfAbsent(type, access); // add fieldname alias for (Class c : parentClasses) addAlias(access, BeansAccessConfig.classFiledNameMapper.get(c)); return access; } catch (Exception ex) { throw new RuntimeException("Error constructing accessor class: " + accessClassName, ex); } } private static LinkedList> getParents(Class type) { LinkedList> m = new LinkedList>(); while (type != null && !type.equals(Object.class)) { m.addLast(type); for (Class c : type.getInterfaces()) m.addLast(c); type = type.getSuperclass(); } m.addLast(Object.class); return m; } /** * */ private static void addAlias(BeansAccess access, HashMap m) { // HashMap m = // BeansAccessConfig.classFiledNameMapper.get(type); if (m == null) return; HashMap changes = new HashMap(); for (Entry e : m.entrySet()) { Accessor a1 = access.map.get(e.getValue()); if (a1 != null) changes.put(e.getValue(), a1); } access.map.putAll(changes); } /** * set field value by field index */ abstract public void set(T object, int methodIndex, Object value); /** * get field value by field index */ abstract public Object get(T object, int methodIndex); /** * create a new targeted object */ abstract public T newInstance(); /** * set field value by fieldname */ public void set(T object, String methodName, Object value) { int i = getIndex(methodName); if (i == -1) throw new net.minidev.asm.ex.NoSuchFieldException(methodName + " in " + object.getClass() + " to put value : " + value); set(object, i, value); } /** * get field value by fieldname */ public Object get(T object, String methodName) { return get(object, getIndex(methodName)); } /** * Returns the index of the field accessor. */ public int getIndex(String name) { Accessor ac = map.get(name); if (ac == null) return -1; return ac.index; } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/BeansAccessBuilder.java000066400000000000000000000354361255620162700311120ustar00rootroot00000000000000package net.minidev.asm; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACONST_NULL; import static org.objectweb.asm.Opcodes.ALOAD; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.ASTORE; import static org.objectweb.asm.Opcodes.ATHROW; import static org.objectweb.asm.Opcodes.BIPUSH; import static org.objectweb.asm.Opcodes.CHECKCAST; import static org.objectweb.asm.Opcodes.DUP; import static org.objectweb.asm.Opcodes.F_SAME; import static org.objectweb.asm.Opcodes.GETFIELD; import static org.objectweb.asm.Opcodes.ICONST_1; import static org.objectweb.asm.Opcodes.ICONST_2; import static org.objectweb.asm.Opcodes.ICONST_3; import static org.objectweb.asm.Opcodes.ICONST_4; import static org.objectweb.asm.Opcodes.ICONST_5; import static org.objectweb.asm.Opcodes.IFEQ; import static org.objectweb.asm.Opcodes.IFNE; import static org.objectweb.asm.Opcodes.IFNULL; import static org.objectweb.asm.Opcodes.IF_ICMPNE; import static org.objectweb.asm.Opcodes.ILOAD; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; import static org.objectweb.asm.Opcodes.NEW; import static org.objectweb.asm.Opcodes.PUTFIELD; import static org.objectweb.asm.Opcodes.RETURN; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class BeansAccessBuilder { static private String METHOD_ACCESS_NAME = Type.getInternalName(BeansAccess.class); final Class type; final Accessor[] accs; final DynamicClassLoader loader; final String className; final String accessClassName; final String accessClassNameInternal; final String classNameInternal; final HashMap, Method> convMtds = new HashMap, Method>(); // Class exeptionClass = net.minidev.asm.ex.NoSuchFieldException.class; Class exeptionClass = NoSuchFieldException.class; /** * Build reflect bytecode from accessor list. * * @param type * type to be access * @param accs * used accessor * @param loader * Loader used to store the generated class */ public BeansAccessBuilder(Class type, Accessor[] accs, DynamicClassLoader loader) { this.type = type; this.accs = accs; this.loader = loader; this.className = type.getName(); if (className.startsWith("java.")) this.accessClassName = "net.minidev.asm." + className + "AccAccess"; else this.accessClassName = className.concat("AccAccess"); this.accessClassNameInternal = accessClassName.replace('.', '/'); this.classNameInternal = className.replace('.', '/'); } public void addConversion(Iterable> conv) { if (conv == null) return; for (Class c : conv) addConversion(c); } public void addConversion(Class conv) { if (conv == null) return; for (Method mtd : conv.getMethods()) { if ((mtd.getModifiers() & Modifier.STATIC) == 0) continue; Class[] param = mtd.getParameterTypes(); if (param.length != 1) continue; if (!param[0].equals(Object.class)) continue; Class rType = mtd.getReturnType(); if (rType.equals(Void.TYPE)) continue; convMtds.put(rType, mtd); } } public Class bulid() { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); MethodVisitor mv; boolean USE_HASH = accs.length > 10; int HASH_LIMIT = 14; String signature = "Lnet/minidev/asm/BeansAccess;"; cw.visit(Opcodes.V1_6, ACC_PUBLIC + Opcodes.ACC_SUPER, accessClassNameInternal, signature, METHOD_ACCESS_NAME, null); // init { mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, METHOD_ACCESS_NAME, "", "()V"); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } // set(Object object, int methodIndex, Object value) mv = cw.visitMethod(ACC_PUBLIC, "set", "(Ljava/lang/Object;ILjava/lang/Object;)V", null, null); mv.visitCode(); // if no Field simply return if (accs.length == 0) { // // mv.visitInsn(RETURN); } else if (accs.length > HASH_LIMIT) { // lots of field Use Switch Statement mv.visitVarInsn(ILOAD, 2); Label[] labels = ASMUtil.newLabels(accs.length); Label defaultLabel = new Label(); mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels); int i = 0; for (Accessor acc : accs) { mv.visitLabel(labels[i++]); if (!acc.isWritable()) { mv.visitInsn(RETURN); continue; } internalSetFiled(mv, acc); } mv.visitLabel(defaultLabel); } else { Label[] labels = ASMUtil.newLabels(accs.length); int i = 0; for (Accessor acc : accs) { ifNotEqJmp(mv, 2, i, labels[i]); internalSetFiled(mv, acc); mv.visitLabel(labels[i]); mv.visitFrame(F_SAME, 0, null, 0, null); i++; } } if (exeptionClass != null) throwExIntParam(mv, exeptionClass); else mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); // public Object get(Object object, int fieldId) mv = cw.visitMethod(ACC_PUBLIC, "get", "(Ljava/lang/Object;I)Ljava/lang/Object;", null, null); mv.visitCode(); // if (USE_HASH) if (accs.length == 0) { mv.visitFrame(F_SAME, 0, null, 0, null); } else if (accs.length > HASH_LIMIT) { mv.visitVarInsn(ILOAD, 2); Label[] labels = ASMUtil.newLabels(accs.length); Label defaultLabel = new Label(); mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels); int i = 0; for (Accessor acc : accs) { mv.visitLabel(labels[i++]); mv.visitFrame(F_SAME, 0, null, 0, null); if (!acc.isReadable()) { mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); continue; } mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, classNameInternal); Type fieldType = Type.getType(acc.getType()); if (acc.isPublic()) { mv.visitFieldInsn(GETFIELD, classNameInternal, acc.getName(), fieldType.getDescriptor()); } else { String sig = Type.getMethodDescriptor(acc.getter); mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, acc.getter.getName(), sig); } ASMUtil.autoBoxing(mv, fieldType); mv.visitInsn(ARETURN); } mv.visitLabel(defaultLabel); mv.visitFrame(F_SAME, 0, null, 0, null); } else { Label[] labels = ASMUtil.newLabels(accs.length); int i = 0; for (Accessor acc : accs) { ifNotEqJmp(mv, 2, i, labels[i]); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, classNameInternal); Type fieldType = Type.getType(acc.getType()); if (acc.isPublic()) { mv.visitFieldInsn(GETFIELD, classNameInternal, acc.getName(), fieldType.getDescriptor()); } else { if (acc.getter == null) throw new RuntimeException("no Getter for field " + acc.getName() + " in class " + this.className); String sig = Type.getMethodDescriptor(acc.getter); mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, acc.getter.getName(), sig); } ASMUtil.autoBoxing(mv, fieldType); mv.visitInsn(ARETURN); mv.visitLabel(labels[i]); mv.visitFrame(F_SAME, 0, null, 0, null); i++; } } if (exeptionClass != null) throwExIntParam(mv, exeptionClass); else { mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); } mv.visitMaxs(0, 0); mv.visitEnd(); if (!USE_HASH) { // Object get(Object object, String methodName) mv = cw.visitMethod(ACC_PUBLIC, "set", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V", null, null); mv.visitCode(); Label[] labels = ASMUtil.newLabels(accs.length); int i = 0; for (Accessor acc : accs) { mv.visitVarInsn(ALOAD, 2); mv.visitLdcInsn(acc.fieldName); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z"); mv.visitJumpInsn(IFEQ, labels[i]); internalSetFiled(mv, acc); mv.visitLabel(labels[i]); mv.visitFrame(F_SAME, 0, null, 0, null); i++; } if (exeptionClass != null) throwExStrParam(mv, exeptionClass); else mv.visitInsn(RETURN); mv.visitMaxs(0, 0); // 2,4 mv.visitEnd(); } if (!USE_HASH) { // get(Object object, String methodName) mv = cw.visitMethod(ACC_PUBLIC, "get", "(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;", null, null); mv.visitCode(); Label[] labels = ASMUtil.newLabels(accs.length); int i = 0; for (Accessor acc : accs) { mv.visitVarInsn(ALOAD, 2); // methodName mv.visitLdcInsn(acc.fieldName); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z"); mv.visitJumpInsn(IFEQ, labels[i]); mv.visitVarInsn(ALOAD, 1); // object mv.visitTypeInsn(CHECKCAST, classNameInternal); Type fieldType = Type.getType(acc.getType()); if (acc.isPublic()) { mv.visitFieldInsn(GETFIELD, classNameInternal, acc.getName(), fieldType.getDescriptor()); } else { String sig = Type.getMethodDescriptor(acc.getter); mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, acc.getter.getName(), sig); } ASMUtil.autoBoxing(mv, fieldType); mv.visitInsn(ARETURN); mv.visitLabel(labels[i]); mv.visitFrame(F_SAME, 0, null, 0, null); i++; } if (exeptionClass != null) throwExStrParam(mv, exeptionClass); else { mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); } mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "newInstance", "()Ljava/lang/Object;", null, null); mv.visitCode(); mv.visitTypeInsn(NEW, classNameInternal); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, classNameInternal, "", "()V"); mv.visitInsn(ARETURN); mv.visitMaxs(2, 1); mv.visitEnd(); } cw.visitEnd(); byte[] data = cw.toByteArray(); // dumpDebug(data, "/tmp/debug-" + accessClassName + ".txt"); return loader.defineClass(accessClassName, data); } /** * Dump Generate Code */ @SuppressWarnings("unused") private void dumpDebug(byte[] data, String destFile) { // try { // File debug = new File(destFile); // int flags = ClassReader.SKIP_DEBUG; // ClassReader cr = new ClassReader(new ByteArrayInputStream(data)); // cr.accept(new ASMifierClassVisitor(new PrintWriter(debug)), // ASMifierClassVisitor.getDefaultAttributes(), // flags); // } catch (Exception e) { // } } /** * Dump Set Field Code * * @param mv * @param acc */ private void internalSetFiled(MethodVisitor mv, Accessor acc) { /** * FNC params * * 1 -> object to alter * * 2 -> id of field * * 3 -> new value */ mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, classNameInternal); // get VELUE mv.visitVarInsn(ALOAD, 3); Type fieldType = Type.getType(acc.getType()); Class type = acc.getType(); String destClsName = Type.getInternalName(type); Method conMtd = convMtds.get(type); if (conMtd != null) { // external converion String clsSig = Type.getInternalName(conMtd.getDeclaringClass()); String mtdName = conMtd.getName(); String mtdSig = Type.getMethodDescriptor(conMtd); mv.visitMethodInsn(INVOKESTATIC, clsSig, mtdName, mtdSig); } else if (acc.isEnum()) { // builtIn Enum Conversion Label isNull = new Label(); mv.visitJumpInsn(IFNULL, isNull); mv.visitVarInsn(ALOAD, 3); // mv.visitTypeInsn(CHECKCAST, "java/lang/String"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;"); mv.visitMethodInsn(INVOKESTATIC, destClsName, "valueOf", "(Ljava/lang/String;)L" + destClsName + ";"); mv.visitVarInsn(ASTORE, 3); mv.visitLabel(isNull); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, this.classNameInternal); // "net/minidev/asm/bean/BEnumPriv" mv.visitVarInsn(ALOAD, 3); mv.visitTypeInsn(CHECKCAST, destClsName); } else if (type.equals(String.class)) { // built In String Conversion Label isNull = new Label(); mv.visitJumpInsn(IFNULL, isNull); mv.visitVarInsn(ALOAD, 3); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;"); mv.visitVarInsn(ASTORE, 3); mv.visitLabel(isNull); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, this.classNameInternal); mv.visitVarInsn(ALOAD, 3); mv.visitTypeInsn(CHECKCAST, destClsName); } else { // just check Cast mv.visitTypeInsn(CHECKCAST, destClsName); } if (acc.isPublic()) { mv.visitFieldInsn(PUTFIELD, classNameInternal, acc.getName(), fieldType.getDescriptor()); } else { String sig = Type.getMethodDescriptor(acc.setter); mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, acc.setter.getName(), sig); } mv.visitInsn(RETURN); } /** * add Throws statement with int param 2 */ private void throwExIntParam(MethodVisitor mv, Class exCls) { String exSig = Type.getInternalName(exCls); mv.visitTypeInsn(NEW, exSig); mv.visitInsn(DUP); mv.visitLdcInsn("mapping " + this.className + " failed to map field:"); mv.visitVarInsn(ILOAD, 2); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "toString", "(I)Ljava/lang/String;"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "concat", "(Ljava/lang/String;)Ljava/lang/String;"); mv.visitMethodInsn(INVOKESPECIAL, exSig, "", "(Ljava/lang/String;)V"); mv.visitInsn(ATHROW); } /** * add Throws statement with String param 2 */ private void throwExStrParam(MethodVisitor mv, Class exCls) { String exSig = Type.getInternalName(exCls); mv.visitTypeInsn(NEW, exSig); mv.visitInsn(DUP); mv.visitLdcInsn("mapping " + this.className + " failed to map field:"); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "concat", "(Ljava/lang/String;)Ljava/lang/String;"); mv.visitMethodInsn(INVOKESPECIAL, exSig, "", "(Ljava/lang/String;)V"); mv.visitInsn(ATHROW); } /** * dump a Jump if not EQ */ private void ifNotEqJmp(MethodVisitor mv, int param, int value, Label label) { mv.visitVarInsn(ILOAD, param); if (value == 0) { /* notest forvalue 0 */ mv.visitJumpInsn(IFNE, label); } else if (value == 1) { mv.visitInsn(ICONST_1); mv.visitJumpInsn(IF_ICMPNE, label); } else if (value == 2) { mv.visitInsn(ICONST_2); mv.visitJumpInsn(IF_ICMPNE, label); } else if (value == 3) { mv.visitInsn(ICONST_3); mv.visitJumpInsn(IF_ICMPNE, label); } else if (value == 4) { mv.visitInsn(ICONST_4); mv.visitJumpInsn(IF_ICMPNE, label); } else if (value == 5) { mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPNE, label); } else if (value >= 6) { mv.visitIntInsn(BIPUSH, value); mv.visitJumpInsn(IF_ICMPNE, label); } else { throw new RuntimeException("non supported negative values"); } } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/BeansAccessConfig.java000066400000000000000000000036341255620162700307240ustar00rootroot00000000000000package net.minidev.asm; import java.util.HashMap; import java.util.LinkedHashSet; public class BeansAccessConfig { /** * Field type convertor for all classes * * Convertor classes should contains mapping method Prototyped as: * * public static DestinationType Method(Object data); * * @see DefaultConverter */ //static protected LinkedHashSet> globalMapper = new LinkedHashSet>(); /** * Field type convertor for custom Class * * Convertor classes should contains mapping method Prototyped as: * * public static DestinationType Method(Object data); * * @see DefaultConverter */ static protected HashMap, LinkedHashSet>> classMapper = new HashMap, LinkedHashSet>>(); /** * FiledName remapper for a specific class or interface */ static protected HashMap, HashMap> classFiledNameMapper = new HashMap, HashMap>(); static { addTypeMapper(Object.class, DefaultConverter.class); addTypeMapper(Object.class, ConvertDate.class); } // /** // * Field type convertor for all classes // * // * Convertor classes should contains mapping method Prototyped as: // * // * public static DestinationType Method(Object data); // * // * @see DefaultConverter // */ // public static void addGlobalTypeMapper(Class mapper) { // synchronized (globalMapper) { // globalMapper.add(mapper); // } // } /** * Field type convertor for all classes * * Convertor classes should contains mapping method Prototyped as: * * public static DestinationType Method(Object data); * * @see DefaultConverter */ public static void addTypeMapper(Class clz, Class mapper) { synchronized (classMapper) { LinkedHashSet> h = classMapper.get(clz); if (h == null) { h = new LinkedHashSet>(); classMapper.put(clz, h); } h.add(mapper); } } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/ConvertDate.java000066400000000000000000000170721255620162700276430ustar00rootroot00000000000000package net.minidev.asm; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Locale; import java.util.StringTokenizer; import java.util.TreeMap; public class ConvertDate { static TreeMap monthsTable = new TreeMap(new StringCmpNS()); // StringCmpNS.COMP static TreeMap daysTable = new TreeMap(new StringCmpNS()); // StringCmpNS.COMP private static HashSet voidData = new HashSet(); public static class StringCmpNS implements Comparator { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } } public static Integer getMonth(String month) { return monthsTable.get(month); } private static Integer parseMonth(String s1) { if (Character.isDigit(s1.charAt(0))) { return Integer.parseInt(s1) - 1; } else { Integer month = monthsTable.get(s1); if (month == null) throw new NullPointerException("can not parse " + s1 + " as month"); return month.intValue(); } } static { voidData.add("CET"); voidData.add("MEZ"); voidData.add("Uhr"); voidData.add("h"); voidData.add("pm"); voidData.add("PM"); voidData.add("o'clock"); // for (int c = 1; c <= 31; c++) { // String s = Integer.toString(c); // if (c < 10) // daysTable.put("0".concat(s), c - 1); // daysTable.put(s, c - 1); // } // for (int c = 1; c <= 12; c++) { // String s = Integer.toString(c); // if (c < 10) // monthsTable.put("0".concat(s), c - 1); // monthsTable.put(s, c - 1); // } for (Locale locale : DateFormatSymbols.getAvailableLocales()) { if ("ja".equals(locale.getLanguage())) continue; if ("ko".equals(locale.getLanguage())) continue; if ("zh".equals(locale.getLanguage())) continue; DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale); String[] keys = dfs.getMonths(); for (int i = 0; i < keys.length; i++) { if (keys[i].length() == 0) continue; fillMap(monthsTable, keys[i], Integer.valueOf(i)); } keys = dfs.getShortMonths(); for (int i = 0; i < keys.length; i++) { String s = keys[i]; if (s.length() == 0) continue; if (Character.isDigit(s.charAt(s.length() - 1))) continue; fillMap(monthsTable, keys[i], Integer.valueOf(i)); fillMap(monthsTable, keys[i].replace(".", ""), Integer.valueOf(i)); } keys = dfs.getWeekdays(); for (int i = 0; i < keys.length; i++) { String s = keys[i]; if (s.length() == 0) continue; fillMap(daysTable, s, Integer.valueOf(i)); fillMap(daysTable, s.replace(".", ""), Integer.valueOf(i)); } keys = dfs.getShortWeekdays(); for (int i = 0; i < keys.length; i++) { String s = keys[i]; if (s.length() == 0) continue; fillMap(daysTable, s, Integer.valueOf(i)); fillMap(daysTable, s.replace(".", ""), Integer.valueOf(i)); } } } private static void fillMap(TreeMap map, String key, Integer value) { map.put(key, value); key = key.replace("é", "e"); key = key.replace("û", "u"); map.put(key, value); } /** * try read a Date from a Object */ public static Date convertToDate(Object obj) { if (obj == null) return null; if (obj instanceof Date) return (Date) obj; if (obj instanceof String) { StringTokenizer st = new StringTokenizer((String) obj, " -/:,.+"); String s1 = ""; if (!st.hasMoreTokens()) return null; s1 = st.nextToken(); if (s1.length() == 4 && Character.isDigit(s1.charAt(0))) return getYYYYMMDD(st, s1); // skip Day if present. if (daysTable.containsKey(s1)) { if (!st.hasMoreTokens()) return null; s1 = st.nextToken(); } if (monthsTable.containsKey(s1)) return getMMDDYYYY(st, s1); if (Character.isDigit(s1.charAt(0))) return getDDMMYYYY(st, s1); return null; } throw new RuntimeException("Primitive: Can not convert " + obj.getClass().getName() + " to int"); } private static Date getYYYYMMDD(StringTokenizer st, String s1) { GregorianCalendar cal = new GregorianCalendar(2000, 0, 0, 0, 0, 0); cal.setTimeInMillis(0); int year = Integer.parseInt(s1); cal.set(Calendar.YEAR, year); if (!st.hasMoreTokens()) return cal.getTime(); s1 = st.nextToken(); cal.set(Calendar.MONTH, parseMonth(s1)); if (!st.hasMoreTokens()) return cal.getTime(); s1 = st.nextToken(); if (Character.isDigit(s1.charAt(0))) { if (s1.length()==5 && s1.charAt(2) == 'T') { // TIME + TIMEZONE int day = Integer.parseInt(s1.substring(0,2)); cal.set(Calendar.DAY_OF_MONTH, day); return addHour(st, cal, s1.substring(3)); } int day = Integer.parseInt(s1); cal.set(Calendar.DAY_OF_MONTH, day); return addHour(st, cal, null); } return cal.getTime(); } private static int getYear(String s1) { int year = Integer.parseInt(s1); // CET ? if (year < 100) { if (year > 23) year += 2000; else year += 1900; } return year; } private static Date getMMDDYYYY(StringTokenizer st, String s1) { GregorianCalendar cal = new GregorianCalendar(2000, 0, 0, 0, 0, 0); Integer month = monthsTable.get(s1); if (month == null) throw new NullPointerException("can not parse " + s1 + " as month"); cal.set(Calendar.MONTH, month); if (!st.hasMoreTokens()) return null; s1 = st.nextToken(); // DAY int day = Integer.parseInt(s1); cal.set(Calendar.DAY_OF_MONTH, day); if (!st.hasMoreTokens()) return null; s1 = st.nextToken(); if (Character.isLetter(s1.charAt(0))) { if (!st.hasMoreTokens()) return null; s1 = st.nextToken(); } cal.set(Calendar.YEAR, getYear(s1)); // /if (st.hasMoreTokens()) // return null; // s1 = st.nextToken(); return addHour(st, cal, null); // return cal.getTime(); } private static Date getDDMMYYYY(StringTokenizer st, String s1) { GregorianCalendar cal = new GregorianCalendar(2000, 0, 0, 0, 0, 0); int day = Integer.parseInt(s1); cal.set(Calendar.DAY_OF_MONTH, day); if (!st.hasMoreTokens()) return null; s1 = st.nextToken(); cal.set(Calendar.MONTH, parseMonth(s1)); if (!st.hasMoreTokens()) return null; s1 = st.nextToken(); cal.set(Calendar.YEAR, getYear(s1)); return addHour(st, cal, null); } private static Date addHour(StringTokenizer st, Calendar cal, String s1) { // String s1; if (s1 == null) { if (!st.hasMoreTokens()) return cal.getTime(); s1 = st.nextToken(); } cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s1)); if (!st.hasMoreTokens()) return cal.getTime(); s1 = st.nextToken(); s1 = trySkip(st, s1, cal); if (s1 == null) return cal.getTime(); // if (s1.equalsIgnoreCase("h")) { // if (!st.hasMoreTokens()) // return cal.getTime(); // s1 = st.nextToken(); // } cal.set(Calendar.MINUTE, Integer.parseInt(s1)); if (!st.hasMoreTokens()) return cal.getTime(); s1 = st.nextToken(); s1 = trySkip(st, s1, cal); if (s1 == null) return cal.getTime(); cal.set(Calendar.SECOND, Integer.parseInt(s1)); if (!st.hasMoreTokens()) return cal.getTime(); s1 = st.nextToken(); s1 = trySkip(st, s1, cal); if (s1 == null) return cal.getTime(); // TODO ADD TIME ZONE s1 = trySkip(st, s1, cal); // if (s1.equalsIgnoreCase("pm")) // cal.add(Calendar.HOUR_OF_DAY, 12); return cal.getTime(); } private static String trySkip(StringTokenizer st, String s1, Calendar cal) { while (voidData.contains(s1)) { if (s1.equalsIgnoreCase("pm")) cal.add(Calendar.HOUR_OF_DAY, 12); if (!st.hasMoreTokens()) return null; s1 = st.nextToken(); } return s1; } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/DefaultConverter.java000066400000000000000000000131341255620162700306740ustar00rootroot00000000000000package net.minidev.asm; import net.minidev.asm.ex.ConvertException; public class DefaultConverter { public static int convertToint(Object obj) { if (obj == null) return 0; if (obj instanceof Number) return ((Number) obj).intValue(); if (obj instanceof String) return Integer.parseInt((String) obj); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to int"); } public static Integer convertToInt(Object obj) { if (obj == null) return null; Class c = obj.getClass(); if (c == Integer.class) return (Integer) obj; if (obj instanceof Number) return Integer.valueOf(((Number) obj).intValue()); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Integer"); } public static short convertToshort(Object obj) { if (obj == null) return 0; if (obj instanceof Number) return ((Number) obj).shortValue(); if (obj instanceof String) return Short.parseShort((String) obj); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to short"); } public static Short convertToShort(Object obj) { if (obj == null) return null; Class c = obj.getClass(); if (c == Short.class) return (Short) obj; if (obj instanceof Number) return Short.valueOf(((Number) obj).shortValue()); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Short"); } public static long convertTolong(Object obj) { if (obj == null) return 0; if (obj instanceof Number) return ((Number) obj).longValue(); if (obj instanceof String) return Long.parseLong((String) obj); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to long"); } public static Long convertToLong(Object obj) { if (obj == null) return null; Class c = obj.getClass(); if (c == Long.class) return (Long) obj; if (obj instanceof Number) return Long.valueOf(((Number) obj).longValue()); throw new ConvertException("Primitive: Can not convert value '" + obj+ "' As " + obj.getClass().getName() + " to Long"); } public static byte convertTobyte(Object obj) { if (obj == null) return 0; if (obj instanceof Number) return ((Number) obj).byteValue(); if (obj instanceof String) return Byte.parseByte((String) obj); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to byte"); } public static Byte convertToByte(Object obj) { if (obj == null) return null; Class c = obj.getClass(); if (c == Byte.class) return (Byte) obj; if (obj instanceof Number) return Byte.valueOf(((Number) obj).byteValue()); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Byte"); } public static float convertTofloat(Object obj) { if (obj == null) return 0f; if (obj instanceof Number) return ((Number) obj).floatValue(); if (obj instanceof String) return Float.parseFloat((String) obj); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to float"); } public static Float convertToFloat(Object obj) { if (obj == null) return null; Class c = obj.getClass(); if (c == Float.class) return (Float) obj; if (obj instanceof Number) return Float.valueOf(((Number) obj).floatValue()); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Float"); } public static double convertTodouble(Object obj) { if (obj == null) return 0.0; if (obj instanceof Number) return ((Number) obj).doubleValue(); if (obj instanceof String) return Double.parseDouble((String) obj); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to float"); } public static Double convertToDouble(Object obj) { if (obj == null) return null; Class c = obj.getClass(); if (c == Double.class) return (Double) obj; if (obj instanceof Number) return Double.valueOf(((Number) obj).doubleValue()); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Float"); } public static char convertTochar(Object obj) { if (obj == null) return ' '; if (obj instanceof String) if (((String) obj).length() > 0) return ((String) obj).charAt(0); else return ' '; throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to char"); } public static Character convertToChar(Object obj) { if (obj == null) return null; Class c = obj.getClass(); if (c == Character.class) return (Character) obj; if (obj instanceof String) if (((String) obj).length() > 0) return ((String) obj).charAt(0); else return ' '; throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Character"); } public static boolean convertTobool(Object obj) { if (obj == null) return false; if (obj.getClass() == Boolean.class) return ((Boolean) obj).booleanValue(); if (obj instanceof String) return Boolean.parseBoolean((String) obj); if (obj instanceof Number) { if (obj.toString().equals("0")) return false; else return true; } throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to boolean"); } public static Boolean convertToBool(Object obj) { if (obj == null) return null; Class c = obj.getClass(); if (c == Boolean.class) return (Boolean) obj; if (obj instanceof String) return Boolean.parseBoolean((String) obj); throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Boolean"); } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/DynamicClassLoader.java000066400000000000000000000055441255620162700311270ustar00rootroot00000000000000package net.minidev.asm; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Method; /** * Simple extension from ClassLoader overiding the loadClass(String name, * boolean resolve) method and allowing to register new classes * * @author uriel * */ class DynamicClassLoader extends ClassLoader { DynamicClassLoader(ClassLoader parent) { super(parent); } private final static String BEAN_AC = BeansAccess.class.getName(); /** * Predefined define defineClass method signature (name, bytes, offset, * length) */ private final static Class[] DEF_CLASS_SIG = new Class[] { String.class, byte[].class, int.class, int.class }; /** * * @param parent used to choose the ClassLoader * @param clsName C * @param clsData * @return */ public static Class directLoad(Class parent, String clsName, byte[] clsData) { DynamicClassLoader loader = new DynamicClassLoader(parent.getClassLoader()); @SuppressWarnings("unchecked") Class clzz = (Class) loader.defineClass(clsName, clsData); return clzz; } public static T directInstance(Class parent, String clsName, byte[] clsData) throws InstantiationException, IllegalAccessException { Class clzz = directLoad(parent, clsName, clsData); return clzz.newInstance(); } @Override protected synchronized java.lang.Class loadClass(String name, boolean resolve) throws ClassNotFoundException { /* * check class by fullname as String. */ if (name.equals(BEAN_AC)) return BeansAccess.class; /* * Use default class loader */ return super.loadClass(name, resolve); } /** * Call defineClass into the parent classLoader using the * method.setAccessible(boolean) hack * * @see ClassLoader#defineClass(String, byte[], int, int) */ Class defineClass(String name, byte[] bytes) throws ClassFormatError { try { // Attempt to load the access class in the same loader, which makes // protected and default access members accessible. Method method = ClassLoader.class.getDeclaredMethod("defineClass", DEF_CLASS_SIG); method.setAccessible(true); return (Class) method.invoke(getParent(), new Object[] { name, bytes, Integer.valueOf(0), Integer.valueOf(bytes.length) }); } catch (Exception ignored) { } return defineClass(name, bytes, 0, bytes.length); } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/FieldFilter.java000066400000000000000000000007071255620162700276130ustar00rootroot00000000000000package net.minidev.asm; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * allow to control read/write access to field * */ public interface FieldFilter { /** * NOT Implemented YET */ public boolean canUse(Field field); public boolean canUse(Field field, Method method); /** * NOT Implemented YET */ public boolean canRead(Field field); /** * NOT Implemented YET */ public boolean canWrite(Field field); } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/ex/000077500000000000000000000000001255620162700251675ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/ex/ConvertException.java000066400000000000000000000003701255620162700313310ustar00rootroot00000000000000package net.minidev.asm.ex; public class ConvertException extends RuntimeException { private static final long serialVersionUID = 1L; public ConvertException() { super(); } public ConvertException(String message) { super(message); } } json-smart-v2-2.2/accessors-smart/src/main/java/net/minidev/asm/ex/NoSuchFieldException.java000066400000000000000000000005631255620162700320600ustar00rootroot00000000000000package net.minidev.asm.ex; /** * Same exception as java.lang.NoSuchFieldException but extends RuntimException * * @author uriel * */ public class NoSuchFieldException extends RuntimeException { private static final long serialVersionUID = 1L; public NoSuchFieldException() { super(); } public NoSuchFieldException(String message) { super(message); } } json-smart-v2-2.2/accessors-smart/src/test/000077500000000000000000000000001255620162700206645ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/test/java/000077500000000000000000000000001255620162700216055ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/test/java/net/000077500000000000000000000000001255620162700223735ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/000077500000000000000000000000001255620162700240265ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/000077500000000000000000000000001255620162700246065ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/ASMTest.java000066400000000000000000000057051255620162700267400ustar00rootroot00000000000000package net.minidev.asm; import java.util.HashMap; import junit.framework.TestCase; import net.minidev.asm.bean.BTest; public class ASMTest extends TestCase { @SuppressWarnings({ "unused" }) public void testGet() throws Exception { long T1; BeansAccess acBT = BeansAccess.get(BTest.class); // BeansAccess acHand = new BTestBeansAccessB(); HashMap m = new HashMap(); m.put("A", "ab"); m.put("B", "Bc"); m.put("C", "cD"); m.put("D", "de"); m.put("E", "ef"); // String clsPath = FastMap1Builder.getName(m.size()); // String clsName = clsPath.replace("/", "."); byte[] data; // data = FastMap1Builder.dump(m.size()); // data = FastMap2Builder.dump(m); // data = FastMapTestDump.dump(clsPath); // DynamicClassLoader loader = new // DynamicClassLoader(BTest.class.getClassLoader()); // byte[] data = BTestBeansAccessDump.dump(); // Class cls = (Class) loader.defineClass(clsName, // data); // Constructor c = (Constructor) // cls.getConstructors()[0]; // FastMap f = c.newInstance(m); // f = new FastMapTest_2(m); // f = new FastMapTest_3(); // f = new FastMapTest_2(m); // f = new FastMapTest_3(); // System.out.println(m.get("A")); // 4 entré // map => 1.279 // fastMap => 3.323 // FastMapTest_1 3.323 // FastMapTest_2 3.323 // FastMapTest_3 0.015 // 3 entry // map => 0.983 // fastmap => 1.014 // 2 entry // map => 0,920 // fastMap => 0,608 // 7 entry // f 2.667 // m 0,640 // 6 entree // f 2.215 // m 0,608 // 4 entree // f 0.032 // m 0,593 // 5 entree // f // m 0.609 // V2 2.402 // V3 2.247 // for (int i = 0; i < 20000; i++) { // f.get("A"); // f.get("B"); // f.get("C"); // f.get("D"); // f.get("E"); // f.get("F"); // f.get("G"); // f.get("H"); // f.get("I"); // } // System.gc(); // long T = System.nanoTime(); // for (int i = 0; i < 20000000; i++) { // m.get("A"); // m.get("B"); // m.get("C"); // m.get("D"); // m.get("E"); // m.get("F"); // m.get("G"); // m.get("H"); // m.get("I"); // } // T = System.nanoTime() - T; // System.out.println(NumberFormat.getInstance().format(T)); // 10 774 968 // 596 295 451 // 2 321 087 341 BeansAccess ac; ac = acBT; // ac = acHand; // ac = acASMHand; subtext(ac); // T1 = System.currentTimeMillis(); // for (int i = 0; i < 2000000; i++) // subtext(ac); // T1 = System.currentTimeMillis() - T1; // System.out.println("// Time: " + T1); } private void subtext(BeansAccess acc) { BTest t = new BTest(); acc.set(t, "pubBoolValue", true); acc.set(t, "pubIntValue", 13); acc.set(t, "pubStrValue", "Test"); acc.set(t, "privIntValue", 16); acc.set(t, "privStrValue", "test Priv"); assertEquals(Integer.valueOf(13), acc.get(t, "pubIntValue")); acc.set(t, "pubIntValue", 14); assertEquals(Integer.valueOf(14), acc.get(t, "pubIntValue")); } }json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/BTestBeansAccessB.java000066400000000000000000000116441255620162700306750ustar00rootroot00000000000000package net.minidev.asm; import net.minidev.asm.bean.BTest; import net.minidev.asm.bean.TEnum; @SuppressWarnings("rawtypes") public class BTestBeansAccessB extends BeansAccess { public BTestBeansAccessB() { Accessor[] accs = ASMUtil.getAccessors(BTest.class, null); super.setAccessor(accs); } /** * set field value by fieldname */ @Override public void set(Object object, String methodName, Object value) { if ("privIntValue".equals(methodName)) { ((BTest) object).setPrivIntValue(DefaultConverter.convertToint(value)); return; } if ("privStrValue".equals(methodName)) { if (value != null) value = value.toString(); ((BTest) object).setPrivStrValue((String) value); return; } if ("pubStrValue".equals(methodName)) { if (value != null) value = value.toString(); ((BTest) object).pubStrValue = (String) value; return; } if ("pubIntValue".equals(methodName)) { ((BTest) object).pubIntValue = DefaultConverter.convertToint(value); return; } if ("pubBoolValue".equals(methodName)) { ((BTest) object).pubBoolValue = DefaultConverter.convertTobool(value); return; } if ("pubIntegerValue".equals(methodName)) { ((BTest) object).pubIntegerValue = DefaultConverter.convertToInt(value); return; } if ("pubTEnum".equals(methodName)) { ((BTest) object).pubTEnum = TEnum.valueOf((String) value); return; } } /** * get field value by fieldname */ @Override public Object get(Object object, String methodName) { if ("privIntValue".equals(methodName)) return ((BTest) object).getPrivIntValue(); if ("privStrValue".equals(methodName)) return ((BTest) object).getPrivStrValue(); if ("pubStrValue".equals(methodName)) return ((BTest) object).pubStrValue; if ("pubIntValue".equals(methodName)) return ((BTest) object).pubIntValue; if ("privStrValue".equals(methodName)) return ((BTest) object).pubBoolValue; if ("pubIntegerValue".equals(methodName)) return ((BTest) object).pubIntegerValue; if ("pubTEnum".equals(methodName)) return ((BTest) object).pubTEnum; return null; } @Override public void set(Object object, int methodIndex, Object value) { switch (methodIndex) { case 0: // privIntValue; ((BTest) object).setPrivIntValue(((Number) value).intValue()); break; case 1: // privStrValue; ((BTest) object).setPrivStrValue((String) value); break; case 2: // pubStrValue; ((BTest) object).pubStrValue = (String) value; break; case 3: // pubIntValue; ((BTest) object).pubIntValue = ((Number) value).intValue(); break; case 4: // pubBoolValue; ((BTest) object).pubBoolValue = ((Boolean) value).booleanValue(); break; case 5: ((BTest) object).pubIntegerValue = DefaultConverter.convertToInt(value); break; case 6: ((BTest) object).pubTEnum = TEnum.valueOf((String) value); break; default: break; } } public void setInt(Object object, int methodIndex, Object value) { if (methodIndex == 0) { ((BTest) object).setPrivIntValue(((Number) value).intValue()); return; } if (methodIndex == 1) { ((BTest) object).setPrivStrValue((String) value); return; } if (methodIndex == 2) { ((BTest) object).pubStrValue = (String) value; return; } if (methodIndex == 3) { ((BTest) object).pubIntValue = ((Number) value).intValue(); return; } if (methodIndex == 4) { ((BTest) object).pubBoolValue = ((Boolean) value).booleanValue(); return; } if (methodIndex == 5) { ((BTest) object).pubBoolValue = ((Boolean) value).booleanValue(); return; } if (methodIndex == 0) { ((BTest) object).pubBoolValue = ((Boolean) value).booleanValue(); return; } if (methodIndex == 7) { ((BTest) object).pubBoolValue = ((Boolean) value).booleanValue(); return; } if (methodIndex == 8) { ((BTest) object).pubBoolValue = ((Boolean) value).booleanValue(); return; } } @Override public Object get(Object object, int methodIndex) { switch (methodIndex) { case 0: // privIntValue; return ((BTest) object).getPrivIntValue(); case 1: // privStrValue; return ((BTest) object).getPrivStrValue(); case 2: // pubStrValue; return ((BTest) object).pubStrValue; case 3: // pubIntValue; return ((BTest) object).pubIntValue; case 4: // privStrValue; return ((BTest) object).pubBoolValue; case 5: // privStrValue; return ((BTest) object).pubIntegerValue; case 6: // privStrValue; return ((BTest) object).pubTEnum; default: break; } return null; } // public Object getInt(Object object, int methodIndex) { // if (methodIndex == 0) // return ((BTest) object).getPrivIntValue(); // if (methodIndex == 1) // return ((BTest) object).getPrivStrValue(); // if (methodIndex == 2) // return ((BTest) object).pubStrValue; // if (methodIndex == 3) // return ((BTest) object).pubIntValue; // if (methodIndex == 4) // return ((BTest) object).pubBoolValue; // return null; // } @Override public Object newInstance() { return new BTest(); } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/TestDateConvert.java000066400000000000000000000046701255620162700305360ustar00rootroot00000000000000package net.minidev.asm; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import junit.framework.TestCase; public class TestDateConvert extends TestCase { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); public void testDateFR() throws Exception { String expectedDateText = "23/01/2012 13:42:12"; ArrayList tests = new ArrayList(); tests.add("23 janvier 2012 13:42:12"); tests.add("lundi 23 janvier 2012 13:42:12"); tests.add("2012-01-23 13:42:12"); // for (String testDate : tests) { Date parsed = null; try { parsed = ConvertDate.convertToDate(testDate); } catch (Exception e) { System.err.println("can not parse:" + testDate); e.printStackTrace(); } assertEquals(expectedDateText, sdf.format(parsed)); } } public void testAdvanceTimeStamp() throws Exception { String testDate = "2014-08-27T12:53:10+02:00"; ConvertDate.convertToDate(testDate); } public void testDateUS() throws Exception { testDateLocalized(Locale.US); } public void testDateFRANCE() throws Exception { testDateLocalized(Locale.FRANCE); } public void testDateCANADA() throws Exception { testDateLocalized(Locale.CANADA); } public void testDateGERMANY() throws Exception { testDateLocalized(Locale.GERMANY); } public void testDateITALY() throws Exception { testDateLocalized(Locale.ITALY); } // MISSING JAPAN / CHINA public void testDateLocalized(Locale locale) throws Exception { // PM fullTestDate(sdf.parse("23/01/2012 13:42:59"), locale); // AM fullTestDate(sdf.parse("23/01/2012 01:42:59"), locale); } public void fullTestDate(Date expectedDate, Locale locale) throws Exception { String expectedDateText = sdf.format(expectedDate); int[] types = new int[] { DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL }; for (int frm : types) { DateFormat FormatEN = DateFormat.getDateTimeInstance(frm, frm, locale); String testDate = FormatEN.format(expectedDate); Date parse = null; try { parse = ConvertDate.convertToDate(testDate); } catch (Exception e) { System.err.println("can not parse:" + testDate + " - DateFormat." + frm); e.printStackTrace(); } String resultStr = sdf.format(parse); //System.err.println("TEST: " + testDate + " readed as: " + resultStr); if (testDate.contains("59")) assertEquals(expectedDateText, resultStr); } } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/TestNewInstance.java000066400000000000000000000004411255620162700305260ustar00rootroot00000000000000package net.minidev.asm; import java.util.TreeMap; import junit.framework.TestCase; public class TestNewInstance extends TestCase { public void testLangUtilPkg() { @SuppressWarnings("rawtypes") BeansAccess acTm = BeansAccess.get(TreeMap.class); acTm.newInstance(); } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/000077500000000000000000000000001255620162700255135ustar00rootroot00000000000000json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BBoolPriv.java000066400000000000000000000003031255620162700302100ustar00rootroot00000000000000package net.minidev.asm.bean; public class BBoolPriv { private boolean value; public boolean isValue() { return value; } public void setValue(boolean value) { this.value = value; } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BBoolPub.java000066400000000000000000000001201255620162700300130ustar00rootroot00000000000000package net.minidev.asm.bean; public class BBoolPub { public boolean value; } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BBooleanPriv.java000066400000000000000000000003071255620162700307000ustar00rootroot00000000000000package net.minidev.asm.bean; public class BBooleanPriv { private Boolean value; public Boolean getValue() { return value; } public void setValue(Boolean value) { this.value = value; } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BBooleanPub.java000066400000000000000000000001231255620162700305020ustar00rootroot00000000000000package net.minidev.asm.bean; public class BBooleanPub { public Boolean value; } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BEnumPriv.java000066400000000000000000000002761255620162700302320ustar00rootroot00000000000000package net.minidev.asm.bean; public class BEnumPriv { private TEnum value; public TEnum getValue() { return value; } public void setValue(TEnum value) { this.value = value; } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BEnumPrivAc.java000066400000000000000000000030671255620162700304770ustar00rootroot00000000000000package net.minidev.asm.bean; import net.minidev.asm.BeansAccess; @SuppressWarnings("rawtypes") public class BEnumPrivAc extends BeansAccess { @Override public void set(Object object, int methodIndex, Object value) { if (methodIndex == 0) { if (value != null) // value = TEnum.valueOf((String) value); value = TEnum.valueOf(value.toString()); ((BEnumPriv) object).setValue((TEnum) value); return; } throw new net.minidev.asm.ex.NoSuchFieldException("mapping BEnumPriv failed to map field:".concat(Integer.toString(methodIndex))); } @Override public Object get(Object object, int methodIndex) { if (methodIndex == 0) { return ((BEnumPriv) object).getValue(); } throw new net.minidev.asm.ex.NoSuchFieldException("mapping BEnumPriv failed to map field:".concat(Integer.toString(methodIndex))); } @Override public void set(Object object, String methodIndex, Object value) { if (methodIndex.equals("value")) { if (value != null) // value = TEnum.valueOf((String) value); value = TEnum.valueOf(value.toString()); ((BEnumPriv) object).setValue((TEnum) value); return; } throw new net.minidev.asm.ex.NoSuchFieldException("mapping BEnumPriv failed to map field:".concat(methodIndex)); } @Override public Object get(Object object, String methodIndex) { if (methodIndex.equals("value")) { return ((BEnumPriv) object).getValue(); } throw new net.minidev.asm.ex.NoSuchFieldException("mapping BEnumPriv failed to map field:".concat(methodIndex)); } @Override public Object newInstance() { return new BEnumPriv(); } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BEnumPub.java000066400000000000000000000001161255620162700300310ustar00rootroot00000000000000package net.minidev.asm.bean; public class BEnumPub { public TEnum value; } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BLongPriv.java000066400000000000000000000002731255620162700302220ustar00rootroot00000000000000package net.minidev.asm.bean; public class BLongPriv { private Long value; public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BLongPrivAc.java000066400000000000000000000017351255620162700304720ustar00rootroot00000000000000package net.minidev.asm.bean; import net.minidev.asm.BeansAccess; import net.minidev.asm.DefaultConverter; @SuppressWarnings("rawtypes") public class BLongPrivAc extends BeansAccess { @Override public void set(Object object, int methodIndex, Object value) { if (methodIndex == 0) { ((BLongPriv) object).setValue(DefaultConverter.convertToLong(value)); return; } } @Override public Object get(Object object, int methodIndex) { if (methodIndex == 0) { return ((BLongPriv) object).getValue(); } return null; } @Override public void set(Object object, String methodIndex, Object value) { if (methodIndex.equals("value")) { ((BLongPriv) object).setValue(DefaultConverter.convertToLong(value)); return; } } @Override public Object get(Object object, String methodIndex) { if (methodIndex.equals("value")) { return ((BLongPriv) object).getValue(); } return null; } @Override public Object newInstance() { return new BLongPriv(); } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BLongPub.java000066400000000000000000000001151255620162700300230ustar00rootroot00000000000000package net.minidev.asm.bean; public class BLongPub { public Long value; } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BLongPubAc.java000066400000000000000000000017111255620162700302720ustar00rootroot00000000000000package net.minidev.asm.bean; import net.minidev.asm.BeansAccess; import net.minidev.asm.DefaultConverter; @SuppressWarnings("rawtypes") public class BLongPubAc extends BeansAccess { @Override public void set(Object object, int methodIndex, Object value) { if (methodIndex == 0) { ((BLongPub) object).value = DefaultConverter.convertToLong(value); return; } } @Override public Object get(Object object, int methodIndex) { if (methodIndex == 0) { return ((BLongPub) object).value; } return null; } @Override public void set(Object object, String methodIndex, Object value) { if (methodIndex.equals("value")) { ((BLongPub) object).value = DefaultConverter.convertToLong(value); return; } } @Override public Object get(Object object, String methodIndex) { if (methodIndex.equals("value")) { return ((BLongPub) object).value; } return null; } @Override public Object newInstance() { return new BLongPub(); } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BObjectPriv.java000066400000000000000000000003031255620162700305230ustar00rootroot00000000000000package net.minidev.asm.bean; public class BObjectPriv { private Object value; public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BObjectPub.java000066400000000000000000000001211255620162700303270ustar00rootroot00000000000000package net.minidev.asm.bean; public class BObjectPub { public Object value; } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BStrPriv.java000066400000000000000000000003011255620162700300630ustar00rootroot00000000000000package net.minidev.asm.bean; public class BStrPriv { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BStrPrivAc.java000066400000000000000000000017501255620162700303400ustar00rootroot00000000000000package net.minidev.asm.bean; import net.minidev.asm.BeansAccess; @SuppressWarnings("rawtypes") public class BStrPrivAc extends BeansAccess { @Override public void set(Object object, int methodIndex, Object value) { if (methodIndex == 0) { if (value != null) value = value.toString(); ((BStrPriv) object).setValue((String) value); return; } } @Override public Object get(Object object, int methodIndex) { if (methodIndex == 0) { return ((BStrPriv) object).getValue(); } return null; } @Override public void set(Object object, String methodIndex, Object value) { if (methodIndex.equals("value")) { if (value != null) value = value.toString(); ((BStrPriv) object).setValue((String) value); return; } } @Override public Object get(Object object, String methodIndex) { if (methodIndex.equals("value")) { return ((BStrPriv) object).getValue(); } return null; } @Override public Object newInstance() { return new BStrPriv(); } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BStrPub.java000066400000000000000000000001161255620162700276750ustar00rootroot00000000000000package net.minidev.asm.bean; public class BStrPub { public String value; } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BStrPubAc.java000066400000000000000000000017231255620162700301460ustar00rootroot00000000000000package net.minidev.asm.bean; import net.minidev.asm.BeansAccess; @SuppressWarnings("rawtypes") public class BStrPubAc extends BeansAccess { @Override public void set(Object object, int methodIndex, Object value) { if (methodIndex == 0) { if (value != null) value = value.toString(); ((BStrPub)object).value = (String) value; return; } } @Override public Object get(Object object, int methodIndex) { if (methodIndex == 0) { return ((BStrPub)object).value; } return null; } @Override public void set(Object object, String methodIndex, Object value) { if (methodIndex.equals("value")) { if (value != null) value = value.toString(); ((BStrPub) object).value = (String) value; return; } } @Override public Object get(Object object, String methodIndex) { if (methodIndex.equals("value")) { return ((BStrPub) object).value; } return null; } @Override public BStrPub newInstance() { return new BStrPub(); } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/BTest.java000066400000000000000000000013361255620162700274020ustar00rootroot00000000000000package net.minidev.asm.bean; public class BTest { public int pubIntValue; public String pubStrValue; private int privIntValue; private String privStrValue; public boolean pubBoolValue; public Integer pubIntegerValue; public TEnum pubTEnum; public void setPrivIntValue(int privIntValue) { this.privIntValue = privIntValue; } public int getPrivIntValue() { return privIntValue; } public void setPrivStrValue(String privStrValue) { this.privStrValue = privStrValue; } public String getPrivStrValue() { return privStrValue; } public String toString() { return "Public(i:" + pubIntValue + " s:" + pubStrValue + "B: " + pubBoolValue + ") Private(i:" + privIntValue + " s:" + privStrValue + ")"; } } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/TEnum.java000066400000000000000000000001011255620162700273760ustar00rootroot00000000000000package net.minidev.asm.bean; public enum TEnum { V1, V2, V3 } json-smart-v2-2.2/accessors-smart/src/test/java/net/minidev/asm/bean/TestAsmAtom.java000066400000000000000000000053541255620162700305660ustar00rootroot00000000000000package net.minidev.asm.bean; import junit.framework.TestCase; import net.minidev.asm.BeansAccess; public class TestAsmAtom extends TestCase { public void testpub() throws Exception { // int fieldID = 0; String fieldID = "value"; { BeansAccess ac = BeansAccess.get(BStrPub.class); BStrPub p = ac.newInstance(); String val = "toto"; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BLongPub.class); BLongPub p = ac.newInstance(); Long val = 123L; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BBooleanPub.class); BBooleanPub p = ac.newInstance(); Boolean val = Boolean.TRUE; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BBoolPub.class); BBoolPub p = ac.newInstance(); Boolean val = Boolean.TRUE; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BEnumPriv.class); BEnumPriv p = ac.newInstance(); TEnum val = TEnum.V2; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BObjectPriv.class); BObjectPriv p = ac.newInstance(); TEnum val = TEnum.V2; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } } public void testPriv() throws Exception { // int fieldID = 0; String fieldID = "value"; { BeansAccess ac = BeansAccess.get(BStrPriv.class); BStrPriv p = ac.newInstance(); String val = "toto"; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BLongPriv.class); BLongPriv p = ac.newInstance(); Long val = 123L; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BBooleanPriv.class); BBooleanPriv p = ac.newInstance(); Boolean val = Boolean.TRUE; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BBoolPriv.class); BBoolPriv p = ac.newInstance(); Boolean val = Boolean.TRUE; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BEnumPub.class); BEnumPub p = ac.newInstance(); TEnum val = TEnum.V2; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } { BeansAccess ac = BeansAccess.get(BObjectPub.class); BObjectPub p = ac.newInstance(); TEnum val = TEnum.V2; ac.set(p, fieldID, val); assertEquals(val, ac.get(p, fieldID)); } } }json-smart-v2-2.2/json-smart-backport/000077500000000000000000000000001255620162700177055ustar00rootroot00000000000000json-smart-v2-2.2/json-smart-backport/pom.xml000066400000000000000000000030411255620162700212200ustar00rootroot00000000000000 4.0.0 json-smart-backport bundle 2.1.1 net.minidev parent 2.1.0 ../parent/pom.xml Json smart Back Port Contains Backported port from versions before 2.1.0 junit junit test net.minidev json-smart org.apache.felix maven-bundle-plugin 2.3.7 true ${project.groupId}.${project.artifactId} ${project.artifactId} ${project.version} net.minidev.json.mapper json-smart-v2-2.2/json-smart/000077500000000000000000000000001255620162700161025ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/ChangeLog.txt000066400000000000000000000003261255620162700204730ustar00rootroot00000000000000Version 1.0.4 (2011/05/02) * First Public version Version 1.0.4-1 (2011/05/03) * Performance Improvement Version 1.0.4-2 (2011/05/06) * add support for non protected string starting with digits. * add Junit tests json-smart-v2-2.2/json-smart/LICENSE.txt000066400000000000000000000261351255620162700177340ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.json-smart-v2-2.2/json-smart/pom.xml000066400000000000000000000044131255620162700174210ustar00rootroot00000000000000 4.0.0 json-smart bundle net.minidev minidev-parent 2.2 ../parent/pom.xml JSON Small and Fast Parser JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. junit junit test net.minidev accessors-smart org.apache.felix maven-bundle-plugin 2.3.7 true ${project.groupId}.${project.artifactId} ${project.artifactId} ${project.version} net.minidev.json, net.minidev.json.annotate, net.minidev.json.parser, net.minidev.json.reader, net.minidev.json.writer accessors-smart;groupId=net.minidev;inline=true json-smart-v2-2.2/json-smart/readme.txt000066400000000000000000000000521255620162700200750ustar00rootroot00000000000000@see: http://code.google.com/p/json-smart/json-smart-v2-2.2/json-smart/src/000077500000000000000000000000001255620162700166715ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/000077500000000000000000000000001255620162700176155ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/000077500000000000000000000000001255620162700205365ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/net/000077500000000000000000000000001255620162700213245ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/net/minidev/000077500000000000000000000000001255620162700227575ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/000077500000000000000000000000001255620162700237305ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONArray.java000066400000000000000000000066151255620162700263530ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.minidev.json.reader.JsonWriter; /** * A JSON array. JSONObject supports java.util.List interface. * * @author FangYidong * @author Uriel Chemouni */ public class JSONArray extends ArrayList implements List, JSONAwareEx, JSONStreamAwareEx { private static final long serialVersionUID = 9106884089231309568L; public static String toJSONString(List list) { return toJSONString(list, JSONValue.COMPRESSION); } /** * Convert a list to JSON text. The result is a JSON array. If this list is * also a JSONAware, JSONAware specific behaviours will be omitted at this * top level. * * @see net.minidev.json.JSONValue#toJSONString(Object) * * @param list * @param compression * Indicate compression level * @return JSON text, or "null" if list is null. */ public static String toJSONString(List list, JSONStyle compression) { StringBuilder sb = new StringBuilder(); try { writeJSONString(list, sb, compression); } catch (IOException e) { // Can not append on a string builder } return sb.toString(); } /** * Encode a list into JSON text and write it to out. If this list is also a * JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific * behaviours will be ignored at this top level. * * @see JSONValue#writeJSONString(Object, Appendable) * * @param list * @param out */ public static void writeJSONString(Iterable list, Appendable out, JSONStyle compression) throws IOException { if (list == null) { out.append("null"); return; } JsonWriter.JSONIterableWriter.writeJSONString(list, out, compression); } public static void writeJSONString(List list, Appendable out) throws IOException { writeJSONString(list, out, JSONValue.COMPRESSION); } public void merge(Object o2) { JSONObject.merge(this, o2); } /** * Explicitely Serialize Object as JSon String */ public String toJSONString() { return toJSONString(this, JSONValue.COMPRESSION); } public String toJSONString(JSONStyle compression) { return toJSONString(this, compression); } /** * Override natif toStirng() */ public String toString() { return toJSONString(); } /** * JSONAwareEx inferface * * @param compression * compression param */ public String toString(JSONStyle compression) { return toJSONString(compression); } public void writeJSONString(Appendable out) throws IOException { writeJSONString(this, out, JSONValue.COMPRESSION); } public void writeJSONString(Appendable out, JSONStyle compression) throws IOException { writeJSONString(this, out, compression); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONAware.java000066400000000000000000000015361255620162700263310ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Beans that support customized output of JSON text shall implement this * interface. * * @author FangYidong */ public interface JSONAware { /** * @return JSON text */ String toJSONString(); } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONAwareEx.java000066400000000000000000000016651255620162700266310ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Beans that support advanced output of JSON text shall implement this interface. * * Adding compressions and formating features * * @author Uriel Chemouni */ public interface JSONAwareEx extends JSONAware{ /** * @return JSON text */ String toJSONString(JSONStyle compression); } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONNavi.java000066400000000000000000000364421255620162700261730ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Stack; import net.minidev.json.writer.JsonReaderI; /** * A JQuery like Json editor, accessor. * * @since 1.0.9 * * @author Uriel Chemouni */ public class JSONNavi { private JsonReaderI mapper; private T root; private Stack stack = new Stack(); private Stack path = new Stack(); private Object current; private boolean failure = false; private String failureMessage; private boolean readonly = false; private Object missingKey = null; public static JSONNavi newInstance() { return new JSONNavi(JSONValue.defaultReader.DEFAULT_ORDERED); } public static JSONNavi newInstanceObject() { JSONNavi o = new JSONNavi(JSONValue.defaultReader.getMapper(JSONObject.class)); o.object(); return o; } public static JSONNavi newInstanceArray() { JSONNavi o = new JSONNavi(JSONValue.defaultReader.getMapper(JSONArray.class)); o.array(); return o; } public JSONNavi(JsonReaderI mapper) { this.mapper = mapper; } @SuppressWarnings("unchecked") public JSONNavi(String json) { this.root = (T) JSONValue.parse(json); this.current = this.root; readonly = true; } public JSONNavi(String json, JsonReaderI mapper) { this.root = JSONValue.parse(json, mapper); this.mapper = mapper; this.current = this.root; readonly = true; } public JSONNavi(String json, Class mapTo) { this.root = JSONValue.parse(json, mapTo); this.mapper = JSONValue.defaultReader.getMapper(mapTo); this.current = this.root; readonly = true; } /** * return to root node */ public JSONNavi root() { this.current = this.root; this.stack.clear(); this.path.clear(); this.failure = false; this.missingKey = null; this.failureMessage = null; return this; } public boolean hasFailure() { return failure; } public Object getCurrentObject() { return current; } @SuppressWarnings({ "unchecked", "rawtypes" }) public Collection getKeys() { if (current instanceof Map) return ((Map) current).keySet(); return null; } public int getSize() { if (current == null) return 0; if (isArray()) return ((List) current).size(); if (isObject()) return ((Map) current).size(); return 1; } public String getString(String key) { String v = null; if (!hasKey(key)) return v; at(key); v = asString(); up(); return v; } public int getInt(String key) { int v = 0; if (!hasKey(key)) return v; at(key); v = asInt(); up(); return v; } public Integer getInteger(String key) { Integer v = null; if (!hasKey(key)) return v; at(key); v = asIntegerObj(); up(); return v; } public double getDouble(String key) { double v = 0; if (!hasKey(key)) return v; at(key); v = asDouble(); up(); return v; } public boolean hasKey(String key) { if (!isObject()) return false; return o(current).containsKey(key); } public JSONNavi at(String key) { if (failure) return this; if (!isObject()) object(); if (!(current instanceof Map)) return failure("current node is not an Object", key); if (!o(current).containsKey(key)) { if (readonly) return failure("current Object have no key named " + key, key); stack.add(current); path.add(key); current = null; missingKey = key; return this; } Object next = o(current).get(key); stack.add(current); path.add(key); current = next; return this; } public Object get(String key) { if (failure) return this; if (!isObject()) object(); if (!(current instanceof Map)) return failure("current node is not an Object", key); return o(current).get(key); } public Object get(int index) { if (failure) return this; if (!isArray()) array(); if (!(current instanceof List)) return failure("current node is not an List", index); return a(current).get(index); } public JSONNavi set(String key, String value) { object(); if (failure) return this; o(current).put(key, value); return this; } public JSONNavi set(String key, Number value) { object(); if (failure) return this; o(current).put(key, value); return this; } /** * write an value in the current object * * @param key * key to access * @param value * new value * @return this */ public JSONNavi set(String key, long value) { return set(key, Long.valueOf(value)); } /** * write an value in the current object * * @param key * key to access * @param value * new value * @return this */ public JSONNavi set(String key, int value) { return set(key, Integer.valueOf(value)); } /** * write an value in the current object * * @param key * key to access * @param value * new value * @return this */ public JSONNavi set(String key, double value) { return set(key, Double.valueOf(value)); } /** * write an value in the current object * * @param key * key to access * @param value * new value * @return this */ public JSONNavi set(String key, float value) { return set(key, Float.valueOf(value)); } /** * add value to the current arrays * * @param values * to add * @return this */ public JSONNavi add(Object... values) { array(); if (failure) return this; List list = a(current); for (Object o : values) list.add(o); return this; } /** * get the current object value as String if the current Object is null * return null. */ public String asString() { if (current == null) return null; if (current instanceof String) return (String) current; return current.toString(); } /** * get the current value as double if the current Object is null return * Double.NaN */ public double asDouble() { if (current instanceof Number) return ((Number) current).doubleValue(); return Double.NaN; } /** * get the current object value as Double if the current Double can not be * cast as Integer return null. */ public Double asDoubleObj() { if (current == null) return null; if (current instanceof Number) { if (current instanceof Double) return (Double) current; return Double.valueOf(((Number) current).doubleValue()); } return Double.NaN; } /** * get the current value as float if the current Object is null return * Float.NaN */ public double asFloat() { if (current instanceof Number) return ((Number) current).floatValue(); return Float.NaN; } /** * get the current object value as Float if the current Float can not be * cast as Integer return null. */ public Float asFloatObj() { if (current == null) return null; if (current instanceof Number) { if (current instanceof Float) return (Float) current; return Float.valueOf(((Number) current).floatValue()); } return Float.NaN; } /** * get the current value as int if the current Object is null return 0 */ public int asInt() { if (current instanceof Number) return ((Number) current).intValue(); return 0; } /** * get the current object value as Integer if the current Object can not be * cast as Integer return null. */ public Integer asIntegerObj() { if (current == null) return null; if (current instanceof Number) { if (current instanceof Integer) return (Integer) current; if (current instanceof Long) { Long l = (Long) current; if (l.longValue() == l.intValue()) { return Integer.valueOf(l.intValue()); } } return null; } return null; } /** * get the current value as long if the current Object is null return 0 */ public long asLong() { if (current instanceof Number) return ((Number) current).longValue(); return 0L; } /** * get the current object value as Long if the current Object can not be * cast as Long return null. */ public Long asLongObj() { if (current == null) return null; if (current instanceof Number) { if (current instanceof Long) return (Long) current; if (current instanceof Integer) return Long.valueOf(((Number) current).longValue()); return null; } return null; } /** * get the current value as boolean if the current Object is null or is not * a boolean return false */ public boolean asBoolean() { if (current instanceof Boolean) return ((Boolean) current).booleanValue(); return false; } /** * get the current object value as Boolean if the current Object is not a * Boolean return null. */ public Boolean asBooleanObj() { if (current == null) return null; if (current instanceof Boolean) return (Boolean) current; return null; } /** * Set current value as Json Object You can also skip this call, Objects can * be create automatically. */ @SuppressWarnings("unchecked") public JSONNavi object() { if (failure) return this; if (current == null && readonly) failure("Can not create Object child in readonly", null); if (current != null) { if (isObject()) return this; if (isArray()) failure("can not use Object feature on Array.", null); failure("Can not use current possition as Object", null); } else { current = mapper.createObject(); } if (root == null) root = (T) current; else store(); return this; } /** * Set current value as Json Array You can also skip this call Arrays can be * create automatically. */ @SuppressWarnings("unchecked") public JSONNavi array() { if (failure) return this; if (current == null && readonly) failure("Can not create Array child in readonly", null); if (current != null) { if (isArray()) return this; if (isObject()) failure("can not use Object feature on Array.", null); failure("Can not use current possition as Object", null); } else { current = mapper.createArray(); } if (root == null) root = (T) current; else store(); return this; } /** * set current value as Number */ public JSONNavi set(Number num) { if (failure) return this; current = num; store(); return this; } /** * set current value as Boolean */ public JSONNavi set(Boolean bool) { if (failure) return this; current = bool; store(); return this; } /** * set current value as String */ public JSONNavi set(String text) { if (failure) return this; current = text; store(); return this; } public T getRoot() { return root; } /** * internal store current Object in current non existing localization */ private void store() { Object parent = stack.peek(); if (isObject(parent)) o(parent).put((String) missingKey, current); else if (isArray(parent)) { int index = ((Number) missingKey).intValue(); List lst = a(parent); while (lst.size() <= index) lst.add(null); lst.set(index, current); } } /** * is the current node is an array */ public boolean isArray() { return isArray(current); } /** * is the current node is an object */ public boolean isObject() { return isObject(current); } /** * check if Object is an Array */ private boolean isArray(Object obj) { if (obj == null) return false; return (obj instanceof List); } /** * check if Object is an Map */ private boolean isObject(Object obj) { if (obj == null) return false; return (obj instanceof Map); } /** * internal cast to List */ @SuppressWarnings("unchecked") private List a(Object obj) { return (List) obj; } /** * internal cast to Map */ @SuppressWarnings("unchecked") private Map o(Object obj) { return (Map) obj; } /** * Access to the index position. * * If index is less than 0 access element index from the end like in python. * * @param index * 0 based desired position in Array */ public JSONNavi at(int index) { if (failure) return this; if (!(current instanceof List)) return failure("current node is not an Array", index); @SuppressWarnings("unchecked") List lst = ((List) current); if (index < 0) { index = lst.size() + index; if (index < 0) index = 0; } if (index >= lst.size()) if (readonly) return failure("Out of bound exception for index", index); else { stack.add(current); path.add(index); current = null; missingKey = index; return this; } Object next = lst.get(index); stack.add(current); path.add(index); current = next; return this; } /** * Access to last + 1 the index position. * * this method can only be used in writing mode. */ public JSONNavi atNext() { if (failure) return this; if (!(current instanceof List)) return failure("current node is not an Array", null); @SuppressWarnings("unchecked") List lst = ((List) current); return at(lst.size()); } /** * call up() level times. * * @param level * number of parent move. */ public JSONNavi up(int level) { while (level-- > 0) { if (stack.size() > 0) { current = stack.pop(); path.pop(); } else break; } return this; } /** * Move one level up in Json tree. if no more level up is available the * statement had no effect. */ public JSONNavi up() { if (stack.size() > 0) { current = stack.pop(); path.pop(); } return this; } private final static JSONStyle ERROR_COMPRESS = new JSONStyle(JSONStyle.FLAG_PROTECT_4WEB); /** * return the Object as a Json String */ public String toString() { if (failure) return JSONValue.toJSONString(failureMessage, ERROR_COMPRESS); return JSONValue.toJSONString(root); } /** * return the Object as a Json String * * @param compression */ public String toString(JSONStyle compression) { if (failure) return JSONValue.toJSONString(failureMessage, compression); return JSONValue.toJSONString(root, compression); } /** * Internally log errors. */ private JSONNavi failure(String err, Object jPathPostfix) { failure = true; StringBuilder sb = new StringBuilder(); sb.append("Error: "); sb.append(err); sb.append(" at "); sb.append(getJPath()); if (jPathPostfix != null) if (jPathPostfix instanceof Integer) sb.append('[').append(jPathPostfix).append(']'); else sb.append('/').append(jPathPostfix); this.failureMessage = sb.toString(); return this; } /** * @return JPath to the current position */ public String getJPath() { StringBuilder sb = new StringBuilder(); for (Object o : path) { if (o instanceof String) sb.append('/').append(o.toString()); else sb.append('[').append(o.toString()).append(']'); } return sb.toString(); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONObject.java000066400000000000000000000157021255620162700265000ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.HashMap; import java.util.Map; import net.minidev.json.reader.JsonWriter; /** * A JSON object. Key value pairs are unordered. JSONObject supports * java.util.Map interface. * * @author FangYidong * @author Uriel Chemouni */ public class JSONObject extends HashMap implements JSONAware, JSONAwareEx, JSONStreamAwareEx { private static final long serialVersionUID = -503443796854799292L; public JSONObject() { super(); } // /** // * Allow simply casting to Map // */ // @SuppressWarnings("unchecked") // public T cast() { // return (T) this; // } /** * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters * (U+0000 through U+001F). It's the same as JSONValue.escape() only for * compatibility here. * * @see JSONValue#escape(String) */ public static String escape(String s) { return JSONValue.escape(s); } public static String toJSONString(Map map) { return toJSONString(map, JSONValue.COMPRESSION); } /** * Convert a map to JSON text. The result is a JSON object. If this map is * also a JSONAware, JSONAware specific behaviours will be omitted at this * top level. * * @see net.minidev.json.JSONValue#toJSONString(Object) * * @param map * @return JSON text, or "null" if map is null. */ public static String toJSONString(Map map, JSONStyle compression) { StringBuilder sb = new StringBuilder(); try { writeJSON(map, sb, compression); } catch (IOException e) { // can not append on a StringBuilder } return sb.toString(); } /** * Write a Key : value entry to a stream */ public static void writeJSONKV(String key, Object value, Appendable out, JSONStyle compression) throws IOException { if (key == null) out.append("null"); else if (!compression.mustProtectKey(key)) out.append(key); else { out.append('"'); JSONValue.escape(key, out, compression); out.append('"'); } out.append(':'); if (value instanceof String) compression.writeString(out, (String) value); else JSONValue.writeJSONString(value, out, compression); } /** * A Simple Helper object to String * * @return a value.toString() or null */ public String getAsString(String key) { Object obj = this.get(key); if (obj == null) return null; return obj.toString(); } /** * A Simple Helper cast an Object to an Number * * @see JSONParserBase.parseNumber(String s) * @return a Number or null */ public Number getAsNumber(String key) { Object obj = this.get(key); if (obj == null) return null; if (obj instanceof Number) return (Number)obj; return Long.valueOf(obj.toString()); } // /** // * return a Key:value entry as stream // */ // public static String toString(String key, Object value) { // return toString(key, value, JSONValue.COMPRESSION); // } // /** // * return a Key:value entry as stream // */ // public static String toString(String key, Object value, JSONStyle // compression) { // StringBuilder sb = new StringBuilder(); // try { // writeJSONKV(key, value, sb, compression); // } catch (IOException e) { // // can not append on a StringBuilder // } // return sb.toString(); // } /** * Allows creation of a JSONObject from a Map. After that, both the * generated JSONObject and the Map can be modified independently. */ public JSONObject(Map map) { super(map); } public static void writeJSON(Map map, Appendable out) throws IOException { writeJSON(map, out, JSONValue.COMPRESSION); } /** * Encode a map into JSON text and write it to out. If this map is also a * JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific * behaviours will be ignored at this top level. * * @see JSONValue#writeJSONString(Object, Appendable) */ public static void writeJSON(Map map, Appendable out, JSONStyle compression) throws IOException { if (map == null) { out.append("null"); return; } JsonWriter.JSONMapWriter.writeJSONString(map, out, compression); } /** * serialize Object as json to an stream */ public void writeJSONString(Appendable out) throws IOException { writeJSON(this, out, JSONValue.COMPRESSION); } /** * serialize Object as json to an stream */ public void writeJSONString(Appendable out, JSONStyle compression) throws IOException { writeJSON(this, out, compression); } public void merge(Object o2) { merge(this, o2); } protected static JSONObject merge(JSONObject o1, Object o2) { if (o2 == null) return o1; if (o2 instanceof JSONObject) return merge(o1, (JSONObject) o2); throw new RuntimeException("JSON megre can not merge JSONObject with " + o2.getClass()); } private static JSONObject merge(JSONObject o1, JSONObject o2) { if (o2 == null) return o1; for (String key : o1.keySet()) { Object value1 = o1.get(key); Object value2 = o2.get(key); if (value2 == null) continue; if (value1 instanceof JSONArray) { o1.put(key, merge((JSONArray) value1, value2)); continue; } if (value1 instanceof JSONObject) { o1.put(key, merge((JSONObject) value1, value2)); continue; } if (value1.equals(value2)) continue; if (value1.getClass() .equals(value2.getClass())) throw new RuntimeException("JSON merge can not merge two " + value1.getClass().getName() + " Object together"); throw new RuntimeException("JSON merge can not merge " + value1.getClass().getName() + " with " + value2.getClass().getName()); } for (String key : o2.keySet()) { if (o1.containsKey(key)) continue; o1.put(key, o2.get(key)); } return o1; } protected static JSONArray merge(JSONArray o1, Object o2) { if (o2 == null) return o1; if (o1 instanceof JSONArray) return merge(o1, (JSONArray) o2); o1.add(o2); return o1; } private static JSONArray merge(JSONArray o1, JSONArray o2) { o1.addAll(o2); return o1; } public String toJSONString() { return toJSONString(this, JSONValue.COMPRESSION); } public String toJSONString(JSONStyle compression) { return toJSONString(this, compression); } public String toString(JSONStyle compression) { return toJSONString(this, compression); } public String toString() { return toJSONString(this, JSONValue.COMPRESSION); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONStreamAware.java000066400000000000000000000016671255620162700275120ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; /** * Beans that support customized output of JSON text to a writer shall implement * this interface. * * @author FangYidong */ public interface JSONStreamAware { /** * write JSON string to out. */ void writeJSONString(Appendable out) throws IOException; } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONStreamAwareEx.java000066400000000000000000000017501255620162700300000ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; /** * Beans that support customized output of JSON text to a writer shall implement * this interface. * * @author FangYidong */ public interface JSONStreamAwareEx extends JSONStreamAware { /** * write JSON string to out. */ void writeJSONString(Appendable out, JSONStyle compression) throws IOException; } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONStyle.java000066400000000000000000000107261255620162700263730ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import net.minidev.json.JStylerObj.MustProtect; import net.minidev.json.JStylerObj.StringProtector; /** * JSONStyle object configure JSonSerializer reducing output size * * @author Uriel Chemouni */ public class JSONStyle { /** * for advanced usage sample see * * @see net.minidev.json.test.TestCompressorFlags */ public final static int FLAG_PROTECT_KEYS = 1; public final static int FLAG_PROTECT_4WEB = 2; public final static int FLAG_PROTECT_VALUES = 4; /** * AGRESSIVE have no effect without PROTECT_KEYS or PROTECT_VALUE * * AGRESSIVE mode allows Json-smart to not protect String containing * special chars */ public final static int FLAG_AGRESSIVE = 8; /** * @since 2.1 */ public final static int FLAG_IGNORE_NULL = 16; public final static JSONStyle NO_COMPRESS = new JSONStyle(0); public final static JSONStyle MAX_COMPRESS = new JSONStyle(-1); /** * @since 1.0.9.1 */ public final static JSONStyle LT_COMPRESS = new JSONStyle(FLAG_PROTECT_4WEB); private boolean _protectKeys; private boolean _protect4Web; private boolean _protectValues; private boolean _ignore_null; private MustProtect mpKey; private MustProtect mpValue; private StringProtector esc; public JSONStyle(int FLAG) { _protectKeys = (FLAG & FLAG_PROTECT_KEYS) == 0; _protectValues = (FLAG & FLAG_PROTECT_VALUES) == 0; _protect4Web = (FLAG & FLAG_PROTECT_4WEB) == 0; _ignore_null = (FLAG & FLAG_IGNORE_NULL) > 0; MustProtect mp; if ((FLAG & FLAG_AGRESSIVE) > 0) mp = JStylerObj.MP_AGGRESIVE; else mp = JStylerObj.MP_SIMPLE; if (_protectValues) mpValue = JStylerObj.MP_TRUE; else mpValue = mp; if (_protectKeys) mpKey = JStylerObj.MP_TRUE; else mpKey = mp; if (_protect4Web) esc = JStylerObj.ESCAPE4Web; else esc = JStylerObj.ESCAPE_LT; } public JSONStyle() { this(0); } public boolean protectKeys() { return _protectKeys; } public boolean protectValues() { return _protectValues; } public boolean protect4Web() { return _protect4Web; } public boolean ignoreNull() { return _ignore_null; } public boolean indent() { return false; } public boolean mustProtectKey(String s) { return mpKey.mustBeProtect(s); } public boolean mustProtectValue(String s) { return mpValue.mustBeProtect(s); } public void writeString(Appendable out, String value) throws IOException { if (!this.mustProtectValue(value)) out.append(value); else { out.append('"'); JSONValue.escape(value, out, this); out.append('"'); } } public void escape(String s, Appendable out) { esc.escape(s, out); } /** * begin Object */ public void objectStart(Appendable out) throws IOException { out.append('{'); } /** * terminate Object */ public void objectStop(Appendable out) throws IOException { out.append('}'); } /** * Start the first Obeject element */ public void objectFirstStart(Appendable out) throws IOException { } /** * Start a new Object element */ public void objectNext(Appendable out) throws IOException { out.append(','); } /** * End Of Object element */ public void objectElmStop(Appendable out) throws IOException { } /** * end of Key in json Object */ public void objectEndOfKey(Appendable out) throws IOException { out.append(':'); } /** * Array start */ public void arrayStart(Appendable out) throws IOException { out.append('['); } /** * Array Done */ public void arrayStop(Appendable out) throws IOException { out.append(']'); } /** * Start the first Array element */ public void arrayfirstObject(Appendable out) throws IOException { } /** * Start a new Array element */ public void arrayNextElm(Appendable out) throws IOException { out.append(','); } /** * End of an Array element */ public void arrayObjectEnd(Appendable out) throws IOException { } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONUtil.java000066400000000000000000000172171255620162700262120ustar00rootroot00000000000000package net.minidev.json; import java.lang.reflect.Field; import java.lang.reflect.Method; import net.minidev.asm.FieldFilter; import net.minidev.json.annotate.JsonIgnore; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class JSONUtil { @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object convertToStrict(Object obj, Class dest) { if (obj == null) return null; if (dest.isAssignableFrom(obj.getClass())) return obj; if (dest.isPrimitive()) { if (dest == int.class) if (obj instanceof Number) return ((Number) obj).intValue(); else return Integer.valueOf(obj.toString()); else if (dest == short.class) if (obj instanceof Number) return ((Number) obj).shortValue(); else return Short.valueOf(obj.toString()); else if (dest == long.class) if (obj instanceof Number) return ((Number) obj).longValue(); else return Long.valueOf(obj.toString()); else if (dest == byte.class) if (obj instanceof Number) return ((Number) obj).byteValue(); else return Byte.valueOf(obj.toString()); else if (dest == float.class) if (obj instanceof Number) return ((Number) obj).floatValue(); else return Float.valueOf(obj.toString()); else if (dest == double.class) if (obj instanceof Number) return ((Number) obj).doubleValue(); else return Double.valueOf(obj.toString()); else if (dest == char.class) { String asString = dest.toString(); if (asString.length() > 0) return Character.valueOf(asString.charAt(0)); } else if (dest == boolean.class) { return (Boolean) obj; } throw new RuntimeException("Primitive: Can not convert " + obj.getClass().getName() + " to " + dest.getName()); } else { if (dest.isEnum()) return Enum.valueOf((Class) dest, obj.toString()); if (dest == Integer.class) if (obj instanceof Number) return Integer.valueOf(((Number) obj).intValue()); else return Integer.valueOf(obj.toString()); if (dest == Long.class) if (obj instanceof Number) return Long.valueOf(((Number) obj).longValue()); else return Long.valueOf(obj.toString()); if (dest == Short.class) if (obj instanceof Number) return Short.valueOf(((Number) obj).shortValue()); else return Short.valueOf(obj.toString()); if (dest == Byte.class) if (obj instanceof Number) return Byte.valueOf(((Number) obj).byteValue()); else return Byte.valueOf(obj.toString()); if (dest == Float.class) if (obj instanceof Number) return Float.valueOf(((Number) obj).floatValue()); else return Float.valueOf(obj.toString()); if (dest == Double.class) if (obj instanceof Number) return Double.valueOf(((Number) obj).doubleValue()); else return Double.valueOf(obj.toString()); if (dest == Character.class) { String asString = dest.toString(); if (asString.length() > 0) return Character.valueOf(asString.charAt(0)); } throw new RuntimeException("Object: Can not Convert " + obj.getClass().getName() + " to " + dest.getName()); } } @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object convertToX(Object obj, Class dest) { if (obj == null) return null; if (dest.isAssignableFrom(obj.getClass())) return obj; if (dest.isPrimitive()) { if (obj instanceof Number) return obj; if (dest == int.class) return Integer.valueOf(obj.toString()); else if (dest == short.class) return Short.valueOf(obj.toString()); else if (dest == long.class) return Long.valueOf(obj.toString()); else if (dest == byte.class) return Byte.valueOf(obj.toString()); else if (dest == float.class) return Float.valueOf(obj.toString()); else if (dest == double.class) return Double.valueOf(obj.toString()); else if (dest == char.class) { String asString = dest.toString(); if (asString.length() > 0) return Character.valueOf(asString.charAt(0)); } else if (dest == boolean.class) { return (Boolean) obj; } throw new RuntimeException("Primitive: Can not convert " + obj.getClass().getName() + " to " + dest.getName()); } else { if (dest.isEnum()) return Enum.valueOf((Class) dest, obj.toString()); if (dest == Integer.class) if (obj instanceof Number) return Integer.valueOf(((Number) obj).intValue()); else return Integer.valueOf(obj.toString()); if (dest == Long.class) if (obj instanceof Number) return Long.valueOf(((Number) obj).longValue()); else return Long.valueOf(obj.toString()); if (dest == Short.class) if (obj instanceof Number) return Short.valueOf(((Number) obj).shortValue()); else return Short.valueOf(obj.toString()); if (dest == Byte.class) if (obj instanceof Number) return Byte.valueOf(((Number) obj).byteValue()); else return Byte.valueOf(obj.toString()); if (dest == Float.class) if (obj instanceof Number) return Float.valueOf(((Number) obj).floatValue()); else return Float.valueOf(obj.toString()); if (dest == Double.class) if (obj instanceof Number) return Double.valueOf(((Number) obj).doubleValue()); else return Double.valueOf(obj.toString()); if (dest == Character.class) { String asString = dest.toString(); if (asString.length() > 0) return Character.valueOf(asString.charAt(0)); } throw new RuntimeException("Object: Can not Convert " + obj.getClass().getName() + " to " + dest.getName()); } } public final static JsonSmartFieldFilter JSON_SMART_FIELD_FILTER = new JsonSmartFieldFilter(); public static class JsonSmartFieldFilter implements FieldFilter { @Override public boolean canUse(Field field) { JsonIgnore ignore = field.getAnnotation(JsonIgnore.class); if (ignore != null && ignore.value()) return false; return true; } @Override public boolean canUse(Field field, Method method) { JsonIgnore ignore = method.getAnnotation(JsonIgnore.class); if (ignore != null && ignore.value()) return false; return true; } @Override public boolean canRead(Field field) { return true; } @Override public boolean canWrite(Field field) { return true; } } public static String getSetterName(String key) { int len = key.length(); char[] b = new char[len + 3]; b[0] = 's'; b[1] = 'e'; b[2] = 't'; char c = key.charAt(0); if (c >= 'a' && c <= 'z') c += 'A' - 'a'; b[3] = c; for (int i = 1; i < len; i++) { b[i + 3] = key.charAt(i); } return new String(b); } public static String getGetterName(String key) { int len = key.length(); char[] b = new char[len + 3]; b[0] = 'g'; b[1] = 'e'; b[2] = 't'; char c = key.charAt(0); if (c >= 'a' && c <= 'z') c += 'A' - 'a'; b[3] = c; for (int i = 1; i < len; i++) { b[i + 3] = key.charAt(i); } return new String(b); } public static String getIsName(String key) { int len = key.length(); char[] b = new char[len + 2]; b[0] = 'i'; b[1] = 's'; char c = key.charAt(0); if (c >= 'a' && c <= 'z') c += 'A' - 'a'; b[2] = c; for (int i = 1; i < len; i++) { b[i + 2] = key.charAt(i); } return new String(b); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JSONValue.java000066400000000000000000000416151255620162700263500ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static net.minidev.json.parser.JSONParser.DEFAULT_PERMISSIVE_MODE; import static net.minidev.json.parser.JSONParser.MODE_RFC4627; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.List; import java.util.Map; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; import net.minidev.json.reader.JsonWriter; import net.minidev.json.reader.JsonWriterI; import net.minidev.json.writer.CompessorMapper; import net.minidev.json.writer.FakeMapper; import net.minidev.json.writer.JsonReader; import net.minidev.json.writer.JsonReaderI; import net.minidev.json.writer.UpdaterMapper; /** * JSONValue is the helper class In most of case you should use those static * methode to user JSON-smart * * * The most commonly use methode are {@link #parse(String)} * {@link #toJSONString(Object)} * * @author Uriel Chemouni */ public class JSONValue { /** * Global default compression type */ public static JSONStyle COMPRESSION = JSONStyle.NO_COMPRESS; /** * Parse JSON text into java object from the input source. Please use * parseWithException() if you don't want to ignore the exception. if you * want strict input check use parseStrict() * * @see JSONParser#parse(Reader) * @see #parseWithException(Reader) * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null * */ public static Object parse(InputStream in) { try { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in); } catch (Exception e) { return null; } } /** * Parse JSON text into java object from the input source. Please use * parseWithException() if you don't want to ignore the exception. if you * want strict input check use parseStrict() * * @see JSONParser#parse(Reader) * @see #parseWithException(Reader) * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null * */ public static Object parse(byte[] in) { try { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in); } catch (Exception e) { return null; } } /** * Parse input json as a mapTo class * * mapTo can be a bean * * @since 2.0 */ public static T parse(InputStream in, Class mapTo) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, defaultReader.getMapper(mapTo)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse JSON text into java object from the input source. Please use * parseWithException() if you don't want to ignore the exception. if you * want strict input check use parseStrict() * * @see JSONParser#parse(Reader) * @see #parseWithException(Reader) * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null * */ public static Object parse(Reader in) { try { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in); } catch (Exception e) { return null; } } /** * Parse input json as a mapTo class * * mapTo can be a bean * * @since 2.0 */ public static T parse(byte[] in, Class mapTo) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, defaultReader.getMapper(mapTo)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse input json as a mapTo class * * mapTo can be a bean * * @since 2.0 */ public static T parse(Reader in, Class mapTo) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, defaultReader.getMapper(mapTo)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse input json as a mapTo class * * mapTo can be a bean * * @since 2.0 */ public static T parse(Reader in, T toUpdate) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, new UpdaterMapper(defaultReader, toUpdate)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse input json as a mapTo class * * @since 2.0 */ protected static T parse(Reader in, JsonReaderI mapper) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, mapper); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse input json as a mapTo class * * mapTo can be a bean * * @since 2.0 */ public static T parse(String in, Class mapTo) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, defaultReader.getMapper(mapTo)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse input json as a mapTo class * * mapTo can be a bean * * @since 2.0 */ public static T parse(InputStream in, T toUpdate) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, new UpdaterMapper(defaultReader, toUpdate)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse input json as a mapTo class * * mapTo can be a bean * * @since 2.0 */ public static T parse(String in, T toUpdate) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, new UpdaterMapper(defaultReader, toUpdate)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse input json as a mapTo class * * @since 2.0 */ protected static T parse(byte[] in, JsonReaderI mapper) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, mapper); } catch (Exception e) { return null; } } /** * Parse input json as a mapTo class * * @since 2.0 */ protected static T parse(String in, JsonReaderI mapper) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, mapper); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Parse JSON text into java object from the input source. Please use * parseWithException() if you don't want to ignore the exception. if you * want strict input check use parseStrict() * * @see JSONParser#parse(String) * @see #parseWithException(String) * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null * */ public static Object parse(String s) { try { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s); } catch (Exception e) { return null; } } /** * Parse Json input to a java Object keeping element order * * @since 1.0.6.1 */ public static Object parseKeepingOrder(Reader in) { try { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT_ORDERED); } catch (Exception e) { return null; } } /** * Parse Json input to a java Object keeping element order * * @since 1.0.6.1 */ public static Object parseKeepingOrder(String in) { try { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT_ORDERED); } catch (Exception e) { return null; } } /** * Parse Json Using SAX event handler * * @since 1.0.6.2 * @removed in 2.0 */ // public static void SAXParse(String input, ContentHandler handler) throws // ParseException { // } /** * Parse Json Using SAX event handler * * @since 1.0.6.2 * @removed in 2.0 */ // public static void SAXParse(Reader input, ContentHandler handler) throws // ParseException, IOException { // } /** * Reformat Json input keeping element order * * @since 1.0.6.2 * * need to be rewrite in 2.0 */ public static String compress(String input, JSONStyle style) { try { StringBuilder sb = new StringBuilder(); new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(input, new CompessorMapper(defaultReader, sb, style)); return sb.toString(); } catch (Exception e) { e.printStackTrace(); return input; } } /** * Compress Json input keeping element order * * @since 1.0.6.1 * * need to be rewrite in 2.0 */ public static String compress(String input) { return compress(input, JSONStyle.MAX_COMPRESS); } /** * Compress Json input keeping element order * * @since 1.0.6.1 */ public static String uncompress(String input) { return compress(input, JSONStyle.NO_COMPRESS); } /** * Parse JSON text into java object from the input source. * * @see JSONParser * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null */ public static Object parseWithException(byte[] in) throws IOException, ParseException { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT); } /** * Parse JSON text into java object from the input source. * * @see JSONParser * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null */ public static Object parseWithException(InputStream in) throws IOException, ParseException { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT); } /** * Parse JSON text into java object from the input source. * * @see JSONParser * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null */ public static Object parseWithException(Reader in) throws IOException, ParseException { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT); } /** * Parse JSON text into java object from the input source. * * @see JSONParser * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null */ public static Object parseWithException(String s) throws ParseException { return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s, defaultReader.DEFAULT); } /** * Parse input json as a mapTo class * * mapTo can be a bean * * @since 2.0 */ public static T parseWithException(String in, Class mapTo) throws ParseException { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, defaultReader.getMapper(mapTo)); } /** * Parse valid RFC4627 JSON text into java object from the input source. * * @see JSONParser * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null */ public static Object parseStrict(Reader in) throws IOException, ParseException { return new JSONParser(MODE_RFC4627).parse(in, defaultReader.DEFAULT); } /** * Parse valid RFC4627 JSON text into java object from the input source. * * @see JSONParser * * @return Instance of the following: JSONObject, JSONArray, String, * java.lang.Number, java.lang.Boolean, null */ public static Object parseStrict(String s) throws ParseException { return new JSONParser(MODE_RFC4627).parse(s, defaultReader.DEFAULT); } /** * Check RFC4627 Json Syntax from input Reader * * @return if the input is valid */ public static boolean isValidJsonStrict(Reader in) throws IOException { try { new JSONParser(MODE_RFC4627).parse(in, FakeMapper.DEFAULT); return true; } catch (ParseException e) { return false; } } /** * check RFC4627 Json Syntax from input String * * @return if the input is valid */ public static boolean isValidJsonStrict(String s) { try { new JSONParser(MODE_RFC4627).parse(s, FakeMapper.DEFAULT); return true; } catch (ParseException e) { return false; } } /** * Check Json Syntax from input Reader * * @return if the input is valid */ public static boolean isValidJson(Reader in) throws IOException { try { new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, FakeMapper.DEFAULT); return true; } catch (ParseException e) { return false; } } /** * Check Json Syntax from input String * * @return if the input is valid */ public static boolean isValidJson(String s) { try { new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s, FakeMapper.DEFAULT); return true; } catch (ParseException e) { return false; } } /** * Encode an object into JSON text and write it to out. *

* If this object is a Map or a List, and it's also a JSONStreamAware or a * JSONAware, JSONStreamAware or JSONAware will be considered firstly. *

* * @see JSONObject#writeJSON(Map, Appendable) * @see JSONArray#writeJSONString(List, Appendable) */ public static void writeJSONString(Object value, Appendable out) throws IOException { writeJSONString(value, out, COMPRESSION); } /** * Serialisation class Data */ public final static JsonWriter defaultWriter = new JsonWriter(); /** * deserialisation class Data */ public final static JsonReader defaultReader = new JsonReader(); /** * remap field from java to json. * @since 2.1.1 */ public static void remapField(Class type, String jsonFieldName, String javaFieldName) { defaultReader.remapField(type, jsonFieldName, javaFieldName); defaultWriter.remapField(type, javaFieldName, jsonFieldName); } /** * Register a serializer for a class. */ public static void registerWriter(Class cls, JsonWriterI writer) { defaultWriter.registerWriter(writer, cls); } /** * register a deserializer for a class. */ public static void registerReader(Class type, JsonReaderI mapper) { defaultReader.registerReader(type, mapper); } /** * Encode an object into JSON text and write it to out. *

* If this object is a Map or a List, and it's also a JSONStreamAware or a * JSONAware, JSONStreamAware or JSONAware will be considered firstly. *

* * @see JSONObject#writeJSON(Map, Appendable) * @see JSONArray#writeJSONString(List, Appendable) */ @SuppressWarnings("unchecked") public static void writeJSONString(Object value, Appendable out, JSONStyle compression) throws IOException { if (value == null) { out.append("null"); return; } Class clz = value.getClass(); @SuppressWarnings("rawtypes") JsonWriterI w = defaultWriter.getWrite(clz); if (w == null) { if (clz.isArray()) w = JsonWriter.arrayWriter; else { w = defaultWriter.getWriterByInterface(value.getClass()); if (w == null) w = JsonWriter.beansWriterASM; // w = JsonWriter.beansWriter; } defaultWriter.registerWriter(w, clz); } w.writeJSONString(value, out, compression); } /** * Encode an object into JSON text and write it to out. *

* If this object is a Map or a List, and it's also a JSONStreamAware or a * JSONAware, JSONStreamAware or JSONAware will be considered firstly. *

* * @see JSONObject#writeJSON(Map, Appendable) * @see JSONArray#writeJSONString(List, Appendable) */ public static String toJSONString(Object value) { return toJSONString(value, COMPRESSION); } /** * Convert an object to JSON text. *

* If this object is a Map or a List, and it's also a JSONAware, JSONAware * will be considered firstly. *

* DO NOT call this method from toJSONString() of a class that implements * both JSONAware and Map or List with "this" as the parameter, use * JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead. * * @see JSONObject#toJSONString(Map) * @see JSONArray#toJSONString(List) * * @return JSON text, or "null" if value is null or it's an NaN or an INF * number. */ public static String toJSONString(Object value, JSONStyle compression) { StringBuilder sb = new StringBuilder(); try { writeJSONString(value, sb, compression); } catch (IOException e) { // can not append on a StringBuilder } return sb.toString(); } public static String escape(String s) { return escape(s, COMPRESSION); } /** * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters * (U+0000 through U+001F). */ public static String escape(String s, JSONStyle compression) { if (s == null) return null; StringBuilder sb = new StringBuilder(); compression.escape(s, sb); return sb.toString(); } public static void escape(String s, Appendable ap) { escape(s, ap, COMPRESSION); } public static void escape(String s, Appendable ap, JSONStyle compression) { if (s == null) return; compression.escape(s, ap); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/JStylerObj.java000066400000000000000000000170741255620162700266330ustar00rootroot00000000000000package net.minidev.json; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; /** * protected class used to stored Internal methods * * @author Uriel Chemouni */ class JStylerObj { public final static MPSimple MP_SIMPLE = new MPSimple(); public final static MPTrue MP_TRUE = new MPTrue(); public final static MPAgressive MP_AGGRESIVE = new MPAgressive(); public final static EscapeLT ESCAPE_LT = new EscapeLT(); public final static Escape4Web ESCAPE4Web = new Escape4Web(); public static interface MustProtect { public boolean mustBeProtect(String s); } private static class MPTrue implements MustProtect { public boolean mustBeProtect(String s) { return true; } } private static class MPSimple implements MustProtect { /** * can a String can be store without enclosing quotes. ie: should not * contain any special json char * * @param s * @return */ public boolean mustBeProtect(final String s) { if (s == null) return false; int len = s.length(); if (len == 0) return true; if (s.trim() != s) return true; char ch = s.charAt(0); if (ch >= '0' && ch <= '9' || ch == '-') return true; for (int i = 0; i < len; i++) { ch = s.charAt(i); if (isSpace(ch)) return true; if (isSpecial(ch)) return true; if (isSpecialChar(ch)) return true; if (isUnicode(ch)) return true; } // keyword check if (isKeyword(s)) return true; return false; } } private static class MPAgressive implements MustProtect { public boolean mustBeProtect(final String s) { if (s == null) return false; int len = s.length(); // protect empty String if (len == 0) return true; // protect trimable String if (s.trim() != s) return true; // json special char char ch = s.charAt(0); if (isSpecial(ch) || isUnicode(ch)) return true; for (int i = 1; i < len; i++) { ch = s.charAt(i); if (isSpecialClose(ch) || isUnicode(ch)) return true; } // keyWord must be protect if (isKeyword(s)) return true; // Digit like text must be protect ch = s.charAt(0); // only test String if First Ch is a digit if (ch >= '0' && ch <= '9' || ch == '-') { int p = 1; // skip first digits for (; p < len; p++) { ch = s.charAt(p); if (ch < '0' || ch > '9') break; } // int/long if (p == len) return true; // Floating point if (ch == '.') { p++; } // Skip digits for (; p < len; p++) { ch = s.charAt(p); if (ch < '0' || ch > '9') break; } if (p == len) return true; // can be read as an floating number // Double if (ch == 'E' || ch == 'e') { p++; if (p == len) // no power data not a digits return false; ch = s.charAt(p); if (ch == '+' || ch == '-') { p++; ch = s.charAt(p); } } if (p == len) // no power data => not a digit return false; for (; p < len; p++) { ch = s.charAt(p); if (ch < '0' || ch > '9') break; } // floating point With power of data. if (p == len) return true; return false; } return false; } } public static boolean isSpace(char c) { return (c == '\r' || c == '\n' || c == '\t' || c == ' '); } public static boolean isSpecialChar(char c) { return (c == '\b' || c == '\f' || c == '\n'); } public static boolean isSpecialOpen(char c) { return (c == '{' || c == '[' || c == ',' || c == ':'); } public static boolean isSpecialClose(char c) { return (c == '}' || c == ']' || c == ',' || c == ':'); } public static boolean isSpecial(char c) { return (c == '{' || c == '[' || c == ',' || c == '}' || c == ']' || c == ':' || c == '\'' || c == '"'); } public static boolean isUnicode(char c) { return ((c >= '\u0000' && c <= '\u001F') || (c >= '\u007F' && c <= '\u009F') || (c >= '\u2000' && c <= '\u20FF')); } public static boolean isKeyword(String s) { if (s.length() < 3) return false; char c = s.charAt(0); if (c == 'n') return s.equals("null"); if (c == 't') return s.equals("true"); if (c == 'f') return s.equals("false"); if (c == 'N') return s.equals("NaN"); return false; } public static interface StringProtector { public void escape(String s, Appendable out); } private static class EscapeLT implements StringProtector { /** * Escape special chars form String except / * * @param s * - Must not be null. * @param out */ public void escape(String s, Appendable out) { try { int len = s.length(); for (int i = 0; i < len; i++) { char ch = s.charAt(i); switch (ch) { case '"': out.append("\\\""); break; case '\\': out.append("\\\\"); break; case '\b': out.append("\\b"); break; case '\f': out.append("\\f"); break; case '\n': out.append("\\n"); break; case '\r': out.append("\\r"); break; case '\t': out.append("\\t"); break; default: // Reference: // http://www.unicode.org/versions/Unicode5.1.0/ if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) { out.append("\\u"); String hex = "0123456789ABCDEF"; out.append(hex.charAt(ch >> 12 & 0x000F)); out.append(hex.charAt(ch >> 8 & 0x000F)); out.append(hex.charAt(ch >> 4 & 0x000F)); out.append(hex.charAt(ch >> 0 & 0x000F)); } else { out.append(ch); } } } } catch (IOException e) { throw new RuntimeException("Impossible Exeption"); } } } private static class Escape4Web implements StringProtector { /** * Escape special chars form String including / * * @param s * - Must not be null. * @param sb */ public void escape(String s, Appendable sb) { try { int len = s.length(); for (int i = 0; i < len; i++) { char ch = s.charAt(i); switch (ch) { case '"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '/': sb.append("\\/"); break; default: // Reference: // http://www.unicode.org/versions/Unicode5.1.0/ if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) { sb.append("\\u"); String hex = "0123456789ABCDEF"; sb.append(hex.charAt(ch >> 12 & 0x0F)); sb.append(hex.charAt(ch >> 8 & 0x0F)); sb.append(hex.charAt(ch >> 4 & 0x0F)); sb.append(hex.charAt(ch >> 0 & 0x0F)); } else { sb.append(ch); } } } } catch (IOException e) { throw new RuntimeException("Impossible Error"); } } } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/annotate/000077500000000000000000000000001255620162700255415ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/annotate/JsonIgnore.java000066400000000000000000000014721255620162700304650ustar00rootroot00000000000000package net.minidev.json.annotate; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * block access to a field or to a getter or to a setter. * * If field and getter are annotate with @JsonIgnore the field will be Writable * only * * * If field and setter are annotate with @JsonIgnore the field will be Readable * only * * * If getter and setter are annotate with @JsonIgnore the field will be * Read/Write using field if the field is public (default ) * * * * * @author uriel * */ @Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @JsonSmartAnnotation public @interface JsonIgnore { boolean value() default true; } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/annotate/JsonSmartAnnotation.java000066400000000000000000000005721255620162700323630ustar00rootroot00000000000000package net.minidev.json.annotate; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Jackson Annotation like * * @author uriel * */ @Target({ ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface JsonSmartAnnotation { } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/000077500000000000000000000000001255620162700252245ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/JSONParser.java000066400000000000000000000157621255620162700300300ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.InputStream; import java.io.Reader; import net.minidev.json.JSONValue; import net.minidev.json.writer.JsonReaderI; public class JSONParser { /** * allow simple quote as String quoting char */ public final static int ACCEPT_SIMPLE_QUOTE = 1; /** * allow non quoted test */ public final static int ACCEPT_NON_QUOTE = 2; /** * Parse NaN as Float.NaN */ public final static int ACCEPT_NAN = 4; /** * Ignore control char in input text. */ public final static int IGNORE_CONTROL_CHAR = 8; /** * Use int datatype to store number when it's possible. * * @since 1.0.7 */ public final static int USE_INTEGER_STORAGE = 16; /** * Throws exception on excessive 0 leading in digits * * @since 1.0.7 */ public final static int ACCEPT_LEADING_ZERO = 32; /** * Throws exception on useless comma in object and array * * @since 1.0.8 */ public final static int ACCEPT_USELESS_COMMA = 64; /** * Allow Json-smart to use Double or BigDecimal to store floating point * value * * You may need to disable HI_PRECISION_FLOAT feature on 32bit to improve * parsing performances. * * @since 1.0.9 */ public final static int USE_HI_PRECISION_FLOAT = 128; /** * If enabled json-smart will throws exception if datas are present after * the end of the Json data. * * @since 1.0.9-2 */ public final static int ACCEPT_TAILLING_DATA = 256; /** * smart mode, fastest parsing mode. accept lots of non standard json syntax * * @since 2.0.1 */ public final static int ACCEPT_TAILLING_SPACE = 512; /** * smart mode, fastest parsing mode. accept lots of non standard json syntax * * @since 1.0.6 */ public final static int MODE_PERMISSIVE = -1; /** * strict RFC4627 mode. * * slower than PERMISIF MODE. * * @since 1.0.6 */ public final static int MODE_RFC4627 = USE_INTEGER_STORAGE | USE_HI_PRECISION_FLOAT | ACCEPT_TAILLING_SPACE; /** * Parse Object like json-simple * * Best for an iso-bug json-simple API port. * * @since 1.0.7 */ public final static int MODE_JSON_SIMPLE = ACCEPT_USELESS_COMMA | USE_HI_PRECISION_FLOAT | ACCEPT_TAILLING_DATA | ACCEPT_TAILLING_SPACE; /** * Strictest parsing mode * * @since 2.0.1 */ public final static int MODE_STRICTEST = USE_INTEGER_STORAGE | USE_HI_PRECISION_FLOAT; /** * Default json-smart processing mode */ public static int DEFAULT_PERMISSIVE_MODE = (System.getProperty("JSON_SMART_SIMPLE") != null) ? MODE_JSON_SIMPLE : MODE_PERMISSIVE; /* * internal fields */ private int mode; private JSONParserInputStream pBinStream; private JSONParserByteArray pBytes; private JSONParserReader pStream; private JSONParserString pString; private JSONParserReader getPStream() { if (pStream == null) pStream = new JSONParserReader(mode); return pStream; } /** * cached construcor * * @return */ private JSONParserInputStream getPBinStream() { if (pBinStream == null) pBinStream = new JSONParserInputStream(mode); return pBinStream; } /** * cached construcor * * @return */ private JSONParserString getPString() { if (pString == null) pString = new JSONParserString(mode); return pString; } /** * cached construcor * * @return */ private JSONParserByteArray getPBytes() { if (pBytes == null) pBytes = new JSONParserByteArray(mode); return pBytes; } /** * @deprecated prefer usage of new JSONParser(JSONParser.MODE_*) */ public JSONParser() { this.mode = DEFAULT_PERMISSIVE_MODE; } public JSONParser(int permissifMode) { this.mode = permissifMode; } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public Object parse(byte[] in) throws ParseException { return getPBytes().parse(in); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(byte[] in, JsonReaderI mapper) throws ParseException { return getPBytes().parse(in, mapper); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(byte[] in, Class mapTo) throws ParseException { return getPBytes().parse(in, JSONValue.defaultReader.getMapper(mapTo)); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public Object parse(InputStream in) throws ParseException { return getPBinStream().parse(in); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(InputStream in, JsonReaderI mapper) throws ParseException { return getPBinStream().parse(in, mapper); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(InputStream in, Class mapTo) throws ParseException { return getPBinStream().parse(in, JSONValue.defaultReader.getMapper(mapTo)); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public Object parse(Reader in) throws ParseException { return getPStream().parse(in); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(Reader in, JsonReaderI mapper) throws ParseException { return getPStream().parse(in, mapper); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(Reader in, Class mapTo) throws ParseException { return getPStream().parse(in, JSONValue.defaultReader.getMapper(mapTo)); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public Object parse(String in) throws ParseException { return getPString().parse(in); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(String in, JsonReaderI mapper) throws ParseException { return getPString().parse(in, mapper); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(String in, Class mapTo) throws ParseException { return getPString().parse(in, JSONValue.defaultReader.getMapper(mapTo)); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/JSONParserBase.java000066400000000000000000000451561255620162700306230ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_CHAR; import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_LEADING_0; import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_TOKEN; import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_UNICODE; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import net.minidev.json.writer.JsonReader; import net.minidev.json.writer.JsonReaderI; /** * JSONParserBase is the common code between {@link JSONParserString} and * {@link JSONParserReader} * * @see JSONParserMemory * @see JSONParserStream * * @author Uriel Chemouni */ abstract class JSONParserBase { protected char c; JsonReader base; public final static byte EOI = 0x1A; protected static final char MAX_STOP = 126; // '}' -> 125 private String lastKey; protected static boolean[] stopAll = new boolean[MAX_STOP]; protected static boolean[] stopArray = new boolean[MAX_STOP]; protected static boolean[] stopKey = new boolean[MAX_STOP]; protected static boolean[] stopValue = new boolean[MAX_STOP]; protected static boolean[] stopX = new boolean[MAX_STOP]; static { stopKey[':'] = stopKey[EOI] = true; stopValue[','] = stopValue['}'] = stopValue[EOI] = true; stopArray[','] = stopArray[']'] = stopArray[EOI] = true; stopX[EOI] = true; stopAll[','] = stopAll[':'] = true; stopAll[']'] = stopAll['}'] = stopAll[EOI] = true; } /* * End of static declaration */ // // protected final MSB sb = new MSB(15); protected Object xo; protected String xs; protected int pos; /* * Parsing flags */ protected final boolean acceptLeadinZero; protected final boolean acceptNaN; protected final boolean acceptNonQuote; protected final boolean acceptSimpleQuote; protected final boolean acceptUselessComma; protected final boolean checkTaillingData; protected final boolean checkTaillingSpace; protected final boolean ignoreControlChar; protected final boolean useHiPrecisionFloat; protected final boolean useIntegerStorage; public JSONParserBase(int permissiveMode) { this.acceptNaN = (permissiveMode & JSONParser.ACCEPT_NAN) > 0; this.acceptNonQuote = (permissiveMode & JSONParser.ACCEPT_NON_QUOTE) > 0; this.acceptSimpleQuote = (permissiveMode & JSONParser.ACCEPT_SIMPLE_QUOTE) > 0; this.ignoreControlChar = (permissiveMode & JSONParser.IGNORE_CONTROL_CHAR) > 0; this.useIntegerStorage = (permissiveMode & JSONParser.USE_INTEGER_STORAGE) > 0; this.acceptLeadinZero = (permissiveMode & JSONParser.ACCEPT_LEADING_ZERO) > 0; this.acceptUselessComma = (permissiveMode & JSONParser.ACCEPT_USELESS_COMMA) > 0; this.useHiPrecisionFloat = (permissiveMode & JSONParser.USE_HI_PRECISION_FLOAT) > 0; this.checkTaillingData = (permissiveMode & (JSONParser.ACCEPT_TAILLING_DATA | JSONParser.ACCEPT_TAILLING_SPACE)) != (JSONParser.ACCEPT_TAILLING_DATA | JSONParser.ACCEPT_TAILLING_SPACE); this.checkTaillingSpace = (permissiveMode & JSONParser.ACCEPT_TAILLING_SPACE) == 0; } public void checkControleChar() throws ParseException { if (ignoreControlChar) return; int l = xs.length(); for (int i = 0; i < l; i++) { char c = xs.charAt(i); if (c < 0) continue; if (c <= 31) throw new ParseException(pos + i, ParseException.ERROR_UNEXPECTED_CHAR, c); if (c == 127) throw new ParseException(pos + i, ParseException.ERROR_UNEXPECTED_CHAR, c); } } public void checkLeadinZero() throws ParseException { int len = xs.length(); if (len == 1) return; if (len == 2) { if (xs.equals("00")) throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, xs); return; } char c1 = xs.charAt(0); char c2 = xs.charAt(1); if (c1 == '-') { char c3 = xs.charAt(2); if (c2 == '0' && c3 >= '0' && c3 <= '9') throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, xs); return; } if (c1 == '0' && c2 >= '0' && c2 <= '9') throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, xs); } protected Number extractFloat() throws ParseException { if (!acceptLeadinZero) checkLeadinZero(); if (!useHiPrecisionFloat) return Float.parseFloat(xs); if (xs.length() > 18) // follow JSonIJ parsing method return new BigDecimal(xs); return Double.parseDouble(xs); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ protected T parse(JsonReaderI mapper) throws ParseException { this.pos = -1; T result; try { read(); result = readFirst(mapper); if (checkTaillingData) { if (!checkTaillingSpace) skipSpace(); if (c != EOI) throw new ParseException(pos - 1, ERROR_UNEXPECTED_TOKEN, c); } } catch (IOException e) { throw new ParseException(pos, e); } xs = null; xo = null; return result; } protected Number parseNumber(String s) throws ParseException { // pos int p = 0; // len int l = s.length(); // max pos long base 10 len int max = 19; boolean neg; if (s.charAt(0) == '-') { p++; max++; neg = true; if (!acceptLeadinZero && l >= 3 && s.charAt(1) == '0') throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, s); } else { neg = false; if (!acceptLeadinZero && l >= 2 && s.charAt(0) == '0') throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, s); } boolean mustCheck; if (l < max) { max = l; mustCheck = false; } else if (l > max) { return new BigInteger(s, 10); } else { max = l - 1; mustCheck = true; } long r = 0; while (p < max) { r = (r * 10L) + ('0' - s.charAt(p++)); } if (mustCheck) { boolean isBig; if (r > -922337203685477580L) { isBig = false; } else if (r < -922337203685477580L) { isBig = true; } else { if (neg) isBig = (s.charAt(p) > '8'); else isBig = (s.charAt(p) > '7'); } if (isBig) return new BigInteger(s, 10); r = r * 10L + ('0' - s.charAt(p)); } if (neg) { if (this.useIntegerStorage && r >= Integer.MIN_VALUE) return (int) r; return r; } r = -r; if (this.useIntegerStorage && r <= Integer.MAX_VALUE) return (int) r; return r; } abstract protected void read() throws IOException; protected T readArray(JsonReaderI mapper) throws ParseException, IOException { Object current = mapper.createArray(); if (c != '[') throw new RuntimeException("Internal Error"); read(); boolean needData = false; // for (;;) { switch (c) { case ' ': case '\r': case '\n': case '\t': read(); continue; case ']': if (needData && !acceptUselessComma) throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); read(); /* unstack */ // return mapper.convert(current); case ':': case '}': throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); case ',': if (needData && !acceptUselessComma) throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); read(); needData = true; continue; case EOI: throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); default: mapper.addValue(current, readMain(mapper, stopArray)); needData = false; continue; } } } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ protected T readFirst(JsonReaderI mapper) throws ParseException, IOException { for (;;) { switch (c) { // skip spaces case ' ': case '\r': case '\n': case '\t': read(); continue; // invalid stats case ':': case '}': case ']': throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); // start object case '{': return readObject(mapper); // start Array case '[': return readArray(mapper); // start string case '"': case '\'': readString(); // return mapper.convert(xs); // string or null case 'n': readNQString(stopX); if ("null".equals(xs)) { // return null; } if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return mapper.convert(xs); // string or false case 'f': readNQString(stopX); if ("false".equals(xs)) { // return mapper.convert(Boolean.FALSE); } if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return mapper.convert(xs); // string or true case 't': readNQString(stopX); if ("true".equals(xs)) { // return mapper.convert(Boolean.TRUE); } if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return mapper.convert(xs); // string or NaN case 'N': readNQString(stopX); if (!acceptNaN) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); if ("NaN".equals(xs)) { // return mapper.convert(Float.valueOf(Float.NaN)); } if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return mapper.convert(xs); // digits case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': xo = readNumber(stopX); // return mapper.convert(xo); default: readNQString(stopX); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return mapper.convert(xs); } } } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ protected Object readMain(JsonReaderI mapper, boolean stop[]) throws ParseException, IOException { for (;;) { switch (c) { // skip spaces case ' ': case '\r': case '\n': case '\t': read(); continue; // invalid stats case ':': case '}': case ']': throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); // start object case '{': return readObject(mapper.startObject(lastKey)); // start Array case '[': return readArray(mapper.startArray(lastKey)); // start string case '"': case '\'': readString(); // return xs; // string or null case 'n': readNQString(stop); if ("null".equals(xs)) { // return null; } if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return xs; // string or false case 'f': readNQString(stop); if ("false".equals(xs)) { // return Boolean.FALSE; } if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return xs; // string or true case 't': readNQString(stop); if ("true".equals(xs)) { // return Boolean.TRUE; } if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return xs; // string or NaN case 'N': readNQString(stop); if (!acceptNaN) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); if ("NaN".equals(xs)) { // return Float.valueOf(Float.NaN); } if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return xs; // digits case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': // // return readNumber(stop); default: readNQString(stop); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); // return xs; } } } abstract protected void readNoEnd() throws ParseException, IOException; abstract protected void readNQString(boolean[] stop) throws IOException; abstract protected Object readNumber(boolean[] stop) throws ParseException, IOException; protected T readObject(JsonReaderI mapper) throws ParseException, IOException { // if (c != '{') throw new RuntimeException("Internal Error"); Object current = mapper.createObject(); boolean needData = false; boolean acceptData = true; for (;;) { read(); switch (c) { case ' ': case '\r': case '\t': case '\n': continue; case ':': case ']': case '[': case '{': throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); case '}': if (needData && !acceptUselessComma) throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); read(); /* unstack */ // return mapper.convert(current); case ',': if (needData && !acceptUselessComma) throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); acceptData = needData = true; continue; case '"': case '\'': default: // int keyStart = pos; if (c == '\"' || c == '\'') { readString(); } else { readNQString(stopKey); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); } String key = xs; if (!acceptData) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, key); // Skip spaces skipSpace(); if (c != ':') { if (c == EOI) throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, null); throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, c); } readNoEnd(); /* skip : */ lastKey = key; Object value = readMain(mapper, stopValue); mapper.setValue(current, key, value); lastKey = null; // Object duplicate = obj.put(key, readMain(stopValue)); // if (duplicate != null) // throw new ParseException(keyStart, ERROR_UNEXPECTED_DUPLICATE_KEY, key); // handler.endObjectEntry(); // should loop skipping read step skipSpace(); if (c == '}') { read(); /* unstack */ // return mapper.convert(current); } if (c == EOI) // Fixed on 18/10/2011 reported by vladimir throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, null); // if c==, continue if (c == ',') acceptData = needData = true; else throw new ParseException(pos - 1, ERROR_UNEXPECTED_TOKEN, c); // acceptData = needData = false; } } } /** * store and read */ abstract void readS() throws IOException; abstract protected void readString() throws ParseException, IOException; protected void readString2() throws ParseException, IOException { /* assert (c == '\"' || c == '\'') */ char sep = c; for (;;) { read(); switch (c) { case EOI: throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, null); case '"': case '\'': if (sep == c) { read(); xs = sb.toString(); return; } sb.append(c); break; case '\\': read(); switch (c) { case 't': sb.append('\t'); break; case 'n': sb.append('\n'); break; case 'r': sb.append('\r'); break; case 'f': sb.append('\f'); break; case 'b': sb.append('\b'); break; case '\\': sb.append('\\'); break; case '/': sb.append('/'); break; case '\'': sb.append('\''); break; case '"': sb.append('"'); break; case 'u': sb.append(readUnicode(4)); break; case 'x': sb.append(readUnicode(2)); break; default: break; } break; case '\0': // end of string case (char) 1: // Start of heading case (char) 2: // Start of text case (char) 3: // End of text case (char) 4: // End of transmission case (char) 5: // Enquiry case (char) 6: // Acknowledge case (char) 7: // Bell case '\b': // 8: backSpase case '\t': // 9: horizontal tab case '\n': // 10: new line case (char) 11: // Vertical tab case '\f': // 12: form feed case '\r': // 13: return carriage case (char) 14: // Shift Out, alternate character set case (char) 15: // Shift In, resume defaultn character set case (char) 16: // Data link escape case (char) 17: // XON, with XOFF to pause listings; case (char) 18: // Device control 2, block-mode flow control case (char) 19: // XOFF, with XON is TERM=18 flow control case (char) 20: // Device control 4 case (char) 21: // Negative acknowledge case (char) 22: // Synchronous idle case (char) 23: // End transmission block, not the same as EOT case (char) 24: // Cancel line, MPE echoes !!! case (char) 25: // End of medium, Control-Y interrupt // case (char) 26: // Substitute case (char) 27: // escape case (char) 28: // File Separator case (char) 29: // Group Separator case (char) 30: // Record Separator case (char) 31: // Unit Separator case (char) 127: // del if (ignoreControlChar) continue; throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); default: sb.append(c); } } } protected char readUnicode(int totalChars) throws ParseException, IOException { int value = 0; for (int i = 0; i < totalChars; i++) { value = value * 16; read(); if (c <= '9' && c >= '0') value += c - '0'; else if (c <= 'F' && c >= 'A') value += (c - 'A') + 10; else if (c >= 'a' && c <= 'f') value += (c - 'a') + 10; else if (c == EOI) throw new ParseException(pos, ERROR_UNEXPECTED_EOF, "EOF"); else throw new ParseException(pos, ERROR_UNEXPECTED_UNICODE, c); } return (char) value; } protected void skipDigits() throws IOException { for (;;) { if (c < '0' || c > '9') return; readS(); } } protected void skipNQString(boolean[] stop) throws IOException { for (;;) { if ((c == EOI) || (c >= 0 && c < MAX_STOP && stop[c])) return; readS(); } } protected void skipSpace() throws IOException { for (;;) { if (c > ' ' || c == EOI) return; readS(); } } public static class MSB { char b[]; int p; public MSB(int size) { b = new char[size]; p = -1; } public void append(char c) { p++; if (b.length <= p) { char[] t = new char[b.length * 2 + 1]; System.arraycopy(b, 0, t, 0, b.length); b = t; } b[p] = c; } public void append(int c) { p++; if (b.length <= p) { char[] t = new char[b.length * 2 + 1]; System.arraycopy(b, 0, t, 0, b.length); b = t; } b[p] = (char) c; } public String toString() { return new String(b, 0, p + 1); } public void clear() { p = -1; } } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/JSONParserByteArray.java000066400000000000000000000051531255620162700316440ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; import net.minidev.json.JSONValue; import net.minidev.json.writer.JsonReaderI; /** * Parser for JSON text. Please note that JSONParser is NOT thread-safe. * * @author Uriel Chemouni */ class JSONParserByteArray extends JSONParserMemory { private byte[] in; public JSONParserByteArray(int permissiveMode) { super(permissiveMode); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public Object parse(byte[] in) throws ParseException { return parse(in, JSONValue.defaultReader.DEFAULT); } // // // // // // // /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(byte[] in, JsonReaderI mapper) throws ParseException { this.base = mapper.base; this.in = in; this.len = in.length; return parse(mapper); } protected void extractString(int beginIndex, int endIndex) { xs = new String(in, beginIndex, endIndex - beginIndex); } protected void extractStringTrim(int start, int stop) { byte[] val = this.in; /* avoid getfield opcode */ while ((start < stop) && (val[start] <= ' ')) { start++; } while ((start < stop) && (val[stop - 1] <= ' ')) { stop--; } xs = new String(in, start, stop - start); } protected int indexOf(char c, int pos) { for (int i = pos; pos < len; i++) if (in[i] == (byte) c) return i; return -1; } protected void read() { if (++pos >= len) this.c = EOI; else this.c = (char) in[pos]; } /** * Same as read() in memory parsing */ protected void readS() { if (++pos >= len) this.c = EOI; else this.c = (char) in[pos]; } /** * read data can not be EOI */ protected void readNoEnd() throws ParseException { if (++pos >= len) { this.c = EOI; throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); } else this.c = (char) in[pos]; } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/JSONParserInputStream.java000066400000000000000000000042031255620162700322100ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; import java.io.IOException; import java.io.InputStream; import net.minidev.json.JSONValue; import net.minidev.json.writer.JsonReaderI; /** * Parser for JSON text. Please note that JSONParser is NOT thread-safe. * * @author Uriel Chemouni */ class JSONParserInputStream extends JSONParserStream { private InputStream in; // len public JSONParserInputStream(int permissiveMode) { super(permissiveMode); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public Object parse(InputStream in) throws ParseException { return parse(in, JSONValue.defaultReader.DEFAULT); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(InputStream in, JsonReaderI mapper) throws ParseException { this.base = mapper.base; // this.in = in; return super.parse(mapper); } // // // // // // // // protected void read() throws IOException { int i = in.read(); c = (i == -1) ? (char) EOI : (char) i; pos++; // } protected void readS() throws IOException { sb.append(c); int i = in.read(); if (i == -1) { c = EOI; } else { c = (char) i; pos++; } } protected void readNoEnd() throws ParseException, IOException { int i = in.read(); if (i == -1) throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); c = (char) i; // } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/JSONParserMemory.java000066400000000000000000000074151255620162700312150ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_CHAR; import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_TOKEN; import java.io.IOException; /** * Parser for JSON text. Please note that JSONParser is NOT thread-safe. * * @author Uriel Chemouni * @see JSONParserString * @see JSONParserByteArray */ abstract class JSONParserMemory extends JSONParserBase { protected int len; public JSONParserMemory(int permissiveMode) { super(permissiveMode); } protected void readNQString(boolean[] stop) throws IOException { int start = pos; skipNQString(stop); extractStringTrim(start, pos); } protected Object readNumber(boolean[] stop) throws ParseException, IOException { int start = pos; // accept first char digit or - read(); skipDigits(); // Integer digit if (c != '.' && c != 'E' && c != 'e') { skipSpace(); if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { // convert string skipNQString(stop); extractStringTrim(start, pos); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); return xs; } extractStringTrim(start, pos); return parseNumber(xs); } // floating point if (c == '.') { // read(); skipDigits(); } if (c != 'E' && c != 'e') { skipSpace(); if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { // convert string skipNQString(stop); extractStringTrim(start, pos); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); return xs; } extractStringTrim(start, pos); return extractFloat(); } sb.append('E'); read(); if (c == '+' || c == '-' || c >= '0' && c <= '9') { sb.append(c); read(); // skip first char skipDigits(); skipSpace(); if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { // convert string skipNQString(stop); extractStringTrim(start, pos); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); return xs; } extractStringTrim(start, pos); return extractFloat(); } else { skipNQString(stop); extractStringTrim(start, pos); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); if (!acceptLeadinZero) checkLeadinZero(); return xs; } // throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, null); } protected void readString() throws ParseException, IOException { if (!acceptSimpleQuote && c == '\'') { if (acceptNonQuote) { readNQString(stopAll); return; } throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); } int tmpP = indexOf(c, pos + 1); if (tmpP == -1) throw new ParseException(len, ERROR_UNEXPECTED_EOF, null); extractString(pos + 1, tmpP); if (xs.indexOf('\\') == -1) { checkControleChar(); pos = tmpP; read(); // handler.primitive(tmp); return; } sb.clear(); readString2(); } abstract protected void extractString(int start, int stop); abstract protected int indexOf(char c, int pos); abstract protected void extractStringTrim(int start, int stop); } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/JSONParserReader.java000066400000000000000000000041401255620162700311370ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; import java.io.IOException; import java.io.Reader; import net.minidev.json.JSONValue; import net.minidev.json.writer.JsonReaderI; /** * Parser for JSON text. Please note that JSONParser is NOT thread-safe. * * @author Uriel Chemouni */ class JSONParserReader extends JSONParserStream { private Reader in; // len public JSONParserReader(int permissiveMode) { super(permissiveMode); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public Object parse(Reader in) throws ParseException { return parse(in, JSONValue.defaultReader.DEFAULT); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(Reader in, JsonReaderI mapper) throws ParseException { this.base = mapper.base; // this.in = in; return super.parse(mapper); } // // // // // // // protected void read() throws IOException { int i = in.read(); c = (i == -1) ? (char) EOI : (char) i; pos++; // } protected void readS() throws IOException { sb.append(c); int i = in.read(); if (i == -1) { c = EOI; } else { c = (char) i; pos++; } } protected void readNoEnd() throws ParseException, IOException { int i = in.read(); if (i == -1) throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); c = (char) i; // } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/JSONParserStream.java000066400000000000000000000065401255620162700311760ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_CHAR; import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_TOKEN; import java.io.IOException; /** * Parser for JSON text. Please note that JSONParser is NOT thread-safe. * * @author Uriel Chemouni * @see JSONParserInputStream * @see JSONParserReader */ abstract class JSONParserStream extends JSONParserBase { // len // public JSONParserStream(int permissiveMode) { super(permissiveMode); } protected void readNQString(boolean[] stop) throws IOException { sb.clear(); skipNQString(stop); xs = sb.toString().trim(); } protected Object readNumber(boolean[] stop) throws ParseException, IOException { sb.clear(); sb.append(c);// accept first char digit or - read(); skipDigits(); // Integer digit if (c != '.' && c != 'E' && c != 'e') { skipSpace(); if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { // convert string skipNQString(stop); xs = sb.toString().trim(); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); return xs; } xs = sb.toString().trim(); return parseNumber(xs); } // floating point if (c == '.') { sb.append(c); read(); skipDigits(); } if (c != 'E' && c != 'e') { skipSpace(); if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { // convert string skipNQString(stop); xs = sb.toString().trim(); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); return xs; } xs = sb.toString().trim(); return extractFloat(); } sb.append('E'); read(); if (c == '+' || c == '-' || c >= '0' && c <= '9') { sb.append(c); read(); // skip first char skipDigits(); skipSpace(); if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { // convert string skipNQString(stop); xs = sb.toString().trim(); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); return xs; } xs = sb.toString().trim(); return extractFloat(); } else { skipNQString(stop); xs = sb.toString().trim(); if (!acceptNonQuote) throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); if (!acceptLeadinZero) checkLeadinZero(); return xs; } // throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, null); } protected void readString() throws ParseException, IOException { if (!acceptSimpleQuote && c == '\'') { if (acceptNonQuote) { readNQString(stopAll); return; } throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); } sb.clear(); // // // // // // // // // // /* assert (c == '\"' || c == '\'') */ readString2(); } // // // // // // // // } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/JSONParserString.java000066400000000000000000000046221255620162700312100ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; import net.minidev.json.JSONValue; import net.minidev.json.writer.JsonReaderI; /** * Parser for JSON text. Please note that JSONParser is NOT thread-safe. * * @author Uriel Chemouni */ class JSONParserString extends JSONParserMemory { private String in; public JSONParserString(int permissiveMode) { super(permissiveMode); } /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public Object parse(String in) throws ParseException { return parse(in, JSONValue.defaultReader.DEFAULT); } // // // // // // // /** * use to return Primitive Type, or String, Or JsonObject or JsonArray * generated by a ContainerFactory */ public T parse(String in, JsonReaderI mapper) throws ParseException { this.base = mapper.base; this.in = in; this.len = in.length(); return parse(mapper); } protected void extractString(int beginIndex, int endIndex) { xs = in.substring(beginIndex, endIndex); } protected void extractStringTrim(int start, int stop) { extractString(start, stop); xs = xs.trim(); } protected int indexOf(char c, int pos) { return in.indexOf(c, pos); } /** * Read next char or END OF INPUT */ protected void read() { if (++pos >= len) this.c = EOI; else this.c = in.charAt(pos); } /** * Same as read() in memory parsing */ protected void readS() { if (++pos >= len) this.c = EOI; else this.c = in.charAt(pos); } /** * read data can not be EOI */ protected void readNoEnd() throws ParseException { if (++pos >= len) { this.c = EOI; throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); } else this.c = in.charAt(pos); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/parser/ParseException.java000066400000000000000000000076551255620162700310350ustar00rootroot00000000000000package net.minidev.json.parser; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * ParseException explains why and where the error occurs in source JSON text. * * @author Uriel Chemouni */ public class ParseException extends Exception { private static final long serialVersionUID = 8879024178584091857L; public static final int ERROR_UNEXPECTED_CHAR = 0; public static final int ERROR_UNEXPECTED_TOKEN = 1; public static final int ERROR_UNEXPECTED_EXCEPTION = 2; public static final int ERROR_UNEXPECTED_EOF = 3; public static final int ERROR_UNEXPECTED_UNICODE = 4; public static final int ERROR_UNEXPECTED_DUPLICATE_KEY = 5; public static final int ERROR_UNEXPECTED_LEADING_0 = 6; private int errorType; private Object unexpectedObject; private int position; public ParseException(int position, int errorType, Object unexpectedObject) { super(toMessage(position, errorType, unexpectedObject)); this.position = position; this.errorType = errorType; this.unexpectedObject = unexpectedObject; } public ParseException(int position, Throwable cause) { super(toMessage(position, ERROR_UNEXPECTED_EXCEPTION, cause), cause); this.position = position; this.errorType = ERROR_UNEXPECTED_EXCEPTION; this.unexpectedObject = cause; } public int getErrorType() { return errorType; } /** * @return The character position (starting with 0) of the input where the * error occurs. */ public int getPosition() { return position; } /** * @return One of the following base on the value of errorType: * ERROR_UNEXPECTED_CHAR java.lang.Character ERROR_UNEXPECTED_TOKEN * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception */ public Object getUnexpectedObject() { return unexpectedObject; } private static String toMessage(int position, int errorType, Object unexpectedObject) { StringBuilder sb = new StringBuilder(); if (errorType == ERROR_UNEXPECTED_CHAR) { sb.append("Unexpected character ("); sb.append(unexpectedObject); sb.append(") at position "); sb.append(position); sb.append("."); } else if (errorType == ERROR_UNEXPECTED_TOKEN) { sb.append("Unexpected token "); sb.append(unexpectedObject); sb.append(" at position "); sb.append(position); sb.append("."); } else if (errorType == ERROR_UNEXPECTED_EXCEPTION) { sb.append("Unexpected exception "); sb.append(unexpectedObject); sb.append(" occur at position "); sb.append(position); sb.append("."); } else if (errorType == ERROR_UNEXPECTED_EOF) { sb.append("Unexpected End Of File position "); sb.append(position); sb.append(": "); sb.append(unexpectedObject); } else if (errorType == ERROR_UNEXPECTED_UNICODE) { sb.append("Unexpected unicode escape sequence "); sb.append(unexpectedObject); sb.append(" at position "); sb.append(position); sb.append("."); } else if (errorType == ERROR_UNEXPECTED_DUPLICATE_KEY) { sb.append("Unexpected duplicate key:"); sb.append(unexpectedObject); sb.append(" at position "); sb.append(position); sb.append("."); } else if (errorType == ERROR_UNEXPECTED_LEADING_0) { sb.append("Unexpected leading 0 in digit for token:"); sb.append(unexpectedObject); sb.append(" at position "); sb.append(position); sb.append("."); } else { sb.append("Unkown error at position "); sb.append(position); sb.append("."); } return sb.toString(); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/reader/000077500000000000000000000000001255620162700251725ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/reader/ArrayWriter.java000066400000000000000000000010571255620162700303130ustar00rootroot00000000000000package net.minidev.json.reader; import java.io.IOException; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; public class ArrayWriter implements JsonWriterI { public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { compression.arrayStart(out); boolean needSep = false; for (Object o : ((Object[]) value)) { if (needSep) compression.objectNext(out); else needSep = true; JSONValue.writeJSONString(o, out, compression); } compression.arrayStop(out); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/reader/BeansWriter.java000066400000000000000000000033621255620162700302660ustar00rootroot00000000000000package net.minidev.json.reader; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import net.minidev.json.JSONStyle; import net.minidev.json.JSONUtil; public class BeansWriter implements JsonWriterI { public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { try { Class nextClass = value.getClass(); boolean needSep = false; compression.objectStart(out); while (nextClass != Object.class) { Field[] fields = nextClass.getDeclaredFields(); for (Field field : fields) { int m = field.getModifiers(); if ((m & (Modifier.STATIC | Modifier.TRANSIENT | Modifier.FINAL)) > 0) continue; Object v = null; if ((m & Modifier.PUBLIC) > 0) { v = field.get(value); } else { String g = JSONUtil.getGetterName(field.getName()); Method mtd = null; try { mtd = nextClass.getDeclaredMethod(g); } catch (Exception e) { } if (mtd == null) { Class c2 = field.getType(); if (c2 == Boolean.TYPE || c2 == Boolean.class) { g = JSONUtil.getIsName(field.getName()); mtd = nextClass.getDeclaredMethod(g); } } if (mtd == null) continue; v = mtd.invoke(value); } if (v == null && compression.ignoreNull()) continue; if (needSep) compression.objectNext(out); else needSep = true; String key = field.getName(); JsonWriter.writeJSONKV(key, v, out, compression); // compression.objectElmStop(out); } nextClass = nextClass.getSuperclass(); } compression.objectStop(out); } catch (Exception e) { throw new RuntimeException(e); } } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/reader/BeansWriterASM.java000066400000000000000000000020141255620162700306200ustar00rootroot00000000000000package net.minidev.json.reader; import java.io.IOException; import net.minidev.asm.Accessor; import net.minidev.asm.BeansAccess; import net.minidev.json.JSONObject; import net.minidev.json.JSONStyle; import net.minidev.json.JSONUtil; public class BeansWriterASM implements JsonWriterI { public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { try { Class cls = value.getClass(); boolean needSep = false; @SuppressWarnings("rawtypes") BeansAccess fields = BeansAccess.get(cls, JSONUtil.JSON_SMART_FIELD_FILTER); out.append('{'); for (Accessor field : fields.getAccessors()) { @SuppressWarnings("unchecked") Object v = fields.get(value, field.getIndex()); if (v == null && compression.ignoreNull()) continue; if (needSep) out.append(','); else needSep = true; String key = field.getName(); JSONObject.writeJSONKV(key, v, out, compression); } out.append('}'); } catch (IOException e) { throw e; } } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/reader/BeansWriterASMRemap.java000066400000000000000000000025541255620162700316160ustar00rootroot00000000000000package net.minidev.json.reader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import net.minidev.asm.Accessor; import net.minidev.asm.BeansAccess; import net.minidev.json.JSONObject; import net.minidev.json.JSONStyle; import net.minidev.json.JSONUtil; public class BeansWriterASMRemap implements JsonWriterI { private Map rename = new HashMap(); public void renameField(String source, String dest) { rename.put(source, dest); } private String rename(String key) { String k2 = rename.get(key); if (k2 != null) return k2; return key; } public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { try { Class cls = value.getClass(); boolean needSep = false; @SuppressWarnings("rawtypes") BeansAccess fields = BeansAccess.get(cls, JSONUtil.JSON_SMART_FIELD_FILTER); out.append('{'); for (Accessor field : fields.getAccessors()) { @SuppressWarnings("unchecked") Object v = fields.get(value, field.getIndex()); if (v == null && compression.ignoreNull()) continue; if (needSep) out.append(','); else needSep = true; String key = field.getName(); key = rename(key); JSONObject.writeJSONKV(key, v, out, compression); } out.append('}'); } catch (IOException e) { throw e; } } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/reader/JsonWriter.java000066400000000000000000000300711255620162700301440ustar00rootroot00000000000000package net.minidev.json.reader; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import net.minidev.json.JSONAware; import net.minidev.json.JSONAwareEx; import net.minidev.json.JSONStreamAware; import net.minidev.json.JSONStreamAwareEx; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; public class JsonWriter { private ConcurrentHashMap, JsonWriterI> data; private LinkedList writerInterfaces; public JsonWriter() { data = new ConcurrentHashMap, JsonWriterI>(); writerInterfaces = new LinkedList(); init(); } /** * remap field name in custom classes * * @param fromJava * field name in java * @param toJson * field name in json * @since 2.1.1 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void remapField(Class type, String fromJava, String toJson) { JsonWriterI map = this.getWrite(type); if (!(map instanceof BeansWriterASMRemap)) { map = new BeansWriterASMRemap(); registerWriter(map, type); } ((BeansWriterASMRemap) map).renameField(fromJava, toJson); } static class WriterByInterface { public Class _interface; public JsonWriterI _writer; public WriterByInterface(Class _interface, JsonWriterI _writer) { this._interface = _interface; this._writer = _writer; } } /** * try to find a Writer by Cheking implemented interface * @param clazz class to serialize * @return a Writer or null */ @SuppressWarnings("rawtypes") public JsonWriterI getWriterByInterface(Class clazz) { for (WriterByInterface w : writerInterfaces) { if (w._interface.isAssignableFrom(clazz)) return w._writer; } return null; } @SuppressWarnings("rawtypes") public JsonWriterI getWrite(Class cls) { return data.get(cls); } final static public JsonWriterI JSONStreamAwareWriter = new JsonWriterI() { public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { value.writeJSONString(out); } }; final static public JsonWriterI JSONStreamAwareExWriter = new JsonWriterI() { public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { value.writeJSONString(out, compression); } }; final static public JsonWriterI JSONJSONAwareExWriter = new JsonWriterI() { public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { out.append(value.toJSONString(compression)); } }; final static public JsonWriterI JSONJSONAwareWriter = new JsonWriterI() { public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { out.append(value.toJSONString()); } }; final static public JsonWriterI> JSONIterableWriter = new JsonWriterI>() { public > void writeJSONString(E list, Appendable out, JSONStyle compression) throws IOException { boolean first = true; compression.arrayStart(out); for (Object value : list) { if (first) { first = false; compression.arrayfirstObject(out); } else { compression.arrayNextElm(out); } if (value == null) out.append("null"); else JSONValue.writeJSONString(value, out, compression); compression.arrayObjectEnd(out); } compression.arrayStop(out); } }; final static public JsonWriterI> EnumWriter = new JsonWriterI>() { public > void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { @SuppressWarnings("rawtypes") String s = ((Enum) value).name(); compression.writeString(out, s); } }; final static public JsonWriterI> JSONMapWriter = new JsonWriterI>() { public > void writeJSONString(E map, Appendable out, JSONStyle compression) throws IOException { boolean first = true; compression.objectStart(out); /** * do not use to handle non String key maps */ for (Map.Entry entry : map.entrySet()) { Object v = entry.getValue(); if (v == null && compression.ignoreNull()) continue; if (first) { compression.objectFirstStart(out); first = false; } else { compression.objectNext(out); } JsonWriter.writeJSONKV(entry.getKey().toString(), v, out, compression); // compression.objectElmStop(out); } compression.objectStop(out); } }; /** * Json-Smart V2 Beans serialiser * * Based on ASM */ final static public JsonWriterI beansWriterASM = new BeansWriterASM(); /** * Json-Smart V1 Beans serialiser */ final static public JsonWriterI beansWriter = new BeansWriter(); /** * Json-Smart ArrayWriterClass */ final static public JsonWriterI arrayWriter = new ArrayWriter(); /** * ToString Writer */ final static public JsonWriterI toStringWriter = new JsonWriterI() { public void writeJSONString(Object value, Appendable out, JSONStyle compression) throws IOException { out.append(value.toString()); } }; public void init() { registerWriter(new JsonWriterI() { public void writeJSONString(String value, Appendable out, JSONStyle compression) throws IOException { compression.writeString(out, (String) value); } }, String.class); registerWriter(new JsonWriterI() { public void writeJSONString(Double value, Appendable out, JSONStyle compression) throws IOException { if (value.isInfinite()) out.append("null"); else out.append(value.toString()); } }, Double.class); registerWriter(new JsonWriterI() { public void writeJSONString(Date value, Appendable out, JSONStyle compression) throws IOException { out.append('"'); JSONValue.escape(value.toString(), out, compression); out.append('"'); } }, Date.class); registerWriter(new JsonWriterI() { public void writeJSONString(Float value, Appendable out, JSONStyle compression) throws IOException { if (value.isInfinite()) out.append("null"); else out.append(value.toString()); } }, Float.class); registerWriter(toStringWriter, Integer.class, Long.class, Byte.class, Short.class, BigInteger.class, BigDecimal.class); registerWriter(toStringWriter, Boolean.class); /** * Array */ registerWriter(new JsonWriterI() { public void writeJSONString(int[] value, Appendable out, JSONStyle compression) throws IOException { boolean needSep = false; compression.arrayStart(out); for (int b : value) { if (needSep) compression.objectNext(out); else needSep = true; out.append(Integer.toString(b)); } compression.arrayStop(out); } }, int[].class); registerWriter(new JsonWriterI() { public void writeJSONString(short[] value, Appendable out, JSONStyle compression) throws IOException { boolean needSep = false; compression.arrayStart(out); for (short b : value) { if (needSep) compression.objectNext(out); else needSep = true; out.append(Short.toString(b)); } compression.arrayStop(out); } }, short[].class); registerWriter(new JsonWriterI() { public void writeJSONString(long[] value, Appendable out, JSONStyle compression) throws IOException { boolean needSep = false; compression.arrayStart(out); for (long b : value) { if (needSep) compression.objectNext(out); else needSep = true; out.append(Long.toString(b)); } compression.arrayStop(out); } }, long[].class); registerWriter(new JsonWriterI() { public void writeJSONString(float[] value, Appendable out, JSONStyle compression) throws IOException { boolean needSep = false; compression.arrayStart(out); for (float b : value) { if (needSep) compression.objectNext(out); else needSep = true; out.append(Float.toString(b)); } compression.arrayStop(out); } }, float[].class); registerWriter(new JsonWriterI() { public void writeJSONString(double[] value, Appendable out, JSONStyle compression) throws IOException { boolean needSep = false; compression.arrayStart(out); for (double b : value) { if (needSep) compression.objectNext(out); else needSep = true; out.append(Double.toString(b)); } compression.arrayStop(out); } }, double[].class); registerWriter(new JsonWriterI() { public void writeJSONString(boolean[] value, Appendable out, JSONStyle compression) throws IOException { boolean needSep = false; compression.arrayStart(out); for (boolean b : value) { if (needSep) compression.objectNext(out); else needSep = true; out.append(Boolean.toString(b)); } compression.arrayStop(out); } }, boolean[].class); registerWriterInterface(JSONStreamAwareEx.class, JsonWriter.JSONStreamAwareExWriter); registerWriterInterface(JSONStreamAware.class, JsonWriter.JSONStreamAwareWriter); registerWriterInterface(JSONAwareEx.class, JsonWriter.JSONJSONAwareExWriter); registerWriterInterface(JSONAware.class, JsonWriter.JSONJSONAwareWriter); registerWriterInterface(Map.class, JsonWriter.JSONMapWriter); registerWriterInterface(Iterable.class, JsonWriter.JSONIterableWriter); registerWriterInterface(Enum.class, JsonWriter.EnumWriter); registerWriterInterface(Number.class, JsonWriter.toStringWriter); } /** * associate an Writer to a interface With Hi priority * @param interFace interface to map * @param writer writer Object * @deprecated use registerWriterInterfaceFirst */ public void addInterfaceWriterFirst(Class interFace, JsonWriterI writer) { registerWriterInterfaceFirst(interFace, writer); } /** * associate an Writer to a interface With Low priority * @param interFace interface to map * @param writer writer Object * @deprecated use registerWriterInterfaceLast */ public void addInterfaceWriterLast(Class interFace, JsonWriterI writer) { registerWriterInterfaceLast(interFace, writer); } /** * associate an Writer to a interface With Low priority * @param interFace interface to map * @param writer writer Object */ public void registerWriterInterfaceLast(Class interFace, JsonWriterI writer) { writerInterfaces.addLast(new WriterByInterface(interFace, writer)); } /** * associate an Writer to a interface With Hi priority * @param interFace interface to map * @param writer writer Object */ public void registerWriterInterfaceFirst(Class interFace, JsonWriterI writer) { writerInterfaces.addFirst(new WriterByInterface(interFace, writer)); } /** * an alias for registerWriterInterfaceLast * @param interFace interface to map * @param writer writer Object */ public void registerWriterInterface(Class interFace, JsonWriterI writer) { registerWriterInterfaceLast(interFace, writer); } /** * associate an Writer to a Class * @param writer * @param cls */ public void registerWriter(JsonWriterI writer, Class... cls) { for (Class c : cls) data.put(c, writer); } /** * Write a Key : value entry to a stream */ public static void writeJSONKV(String key, Object value, Appendable out, JSONStyle compression) throws IOException { if (key == null) out.append("null"); else if (!compression.mustProtectKey(key)) out.append(key); else { out.append('"'); JSONValue.escape(key, out, compression); out.append('"'); } compression.objectEndOfKey(out); if (value instanceof String) { compression.writeString(out, (String) value); } else JSONValue.writeJSONString(value, out, compression); compression.objectElmStop(out); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/reader/JsonWriterI.java000066400000000000000000000003661255620162700302610ustar00rootroot00000000000000package net.minidev.json.reader; import java.io.IOException; import net.minidev.json.JSONStyle; public interface JsonWriterI { public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException; } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/000077500000000000000000000000001255620162700252445ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/ArraysMapper.java000066400000000000000000000174221255620162700305230ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; public class ArraysMapper extends JsonReaderI { public ArraysMapper(JsonReader base) { super(base); } @Override public Object createArray() { return new ArrayList(); } @SuppressWarnings("unchecked") @Override public void addValue(Object current, Object value) { ((List) current).add(value); } @SuppressWarnings("unchecked") @Override public T convert(Object current) { return (T) current; } public static class GenericMapper extends ArraysMapper { final Class componentType; JsonReaderI subMapper; public GenericMapper(JsonReader base, Class type) { super(base); this.componentType = type.getComponentType(); } @SuppressWarnings("unchecked") @Override public T convert(Object current) { int p = 0; Object[] r = (Object[]) Array.newInstance(componentType, ((List) current).size()); for (Object e : ((List) current)) r[p++] = e; return (T) r; } @Override public JsonReaderI startArray(String key) { if (subMapper == null) subMapper = base.getMapper(componentType); return subMapper; } @Override public JsonReaderI startObject(String key) { if (subMapper == null) subMapper = base.getMapper(componentType); return subMapper; } }; public static JsonReaderI MAPPER_PRIM_INT = new ArraysMapper(null) { @Override public int[] convert(Object current) { int p = 0; int[] r = new int[((List) current).size()]; for (Object e : ((List) current)) r[p++] = ((Number) e).intValue(); return r; } }; public static JsonReaderI MAPPER_INT = new ArraysMapper(null) { @Override public Integer[] convert(Object current) { int p = 0; Integer[] r = new Integer[((List) current).size()]; for (Object e : ((List) current)) { if (e == null) continue; if (e instanceof Integer) r[p] = (Integer) e; else r[p] = ((Number) e).intValue(); p++; } return r; } }; public static JsonReaderI MAPPER_PRIM_SHORT = new ArraysMapper(null) { @Override public short[] convert(Object current) { int p = 0; short[] r = new short[((List) current).size()]; for (Object e : ((List) current)) r[p++] = ((Number) e).shortValue(); return r; } }; public static JsonReaderI MAPPER_SHORT = new ArraysMapper(null) { @Override public Short[] convert(Object current) { int p = 0; Short[] r = new Short[((List) current).size()]; for (Object e : ((List) current)) { if (e == null) continue; if (e instanceof Short) r[p] = (Short) e; else r[p] = ((Number) e).shortValue(); p++; } return r; } }; public static JsonReaderI MAPPER_PRIM_BYTE = new ArraysMapper(null) { @Override public byte[] convert(Object current) { int p = 0; byte[] r = new byte[((List) current).size()]; for (Object e : ((List) current)) r[p++] = ((Number) e).byteValue(); return r; } }; public static JsonReaderI MAPPER_BYTE = new ArraysMapper(null) { @Override public Byte[] convert(Object current) { int p = 0; Byte[] r = new Byte[((List) current).size()]; for (Object e : ((List) current)) { if (e == null) continue; if (e instanceof Byte) r[p] = (Byte) e; else r[p] = ((Number) e).byteValue(); p++; } return r; } }; public static JsonReaderI MAPPER_PRIM_CHAR = new ArraysMapper(null) { @Override public char[] convert(Object current) { int p = 0; char[] r = new char[((List) current).size()]; for (Object e : ((List) current)) r[p++] = e.toString().charAt(0); return r; } }; public static JsonReaderI MAPPER_CHAR = new ArraysMapper(null) { @Override public Character[] convert(Object current) { int p = 0; Character[] r = new Character[((List) current).size()]; for (Object e : ((List) current)) { if (e == null) continue; r[p] = e.toString().charAt(0); p++; } return r; } }; public static JsonReaderI MAPPER_PRIM_LONG = new ArraysMapper(null) { @Override public long[] convert(Object current) { int p = 0; long[] r = new long[((List) current).size()]; for (Object e : ((List) current)) r[p++] = ((Number) e).intValue(); return r; } }; public static JsonReaderI MAPPER_LONG = new ArraysMapper(null) { @Override public Long[] convert(Object current) { int p = 0; Long[] r = new Long[((List) current).size()]; for (Object e : ((List) current)) { if (e == null) continue; if (e instanceof Float) r[p] = ((Long) e); else r[p] = ((Number) e).longValue(); p++; } return r; } }; public static JsonReaderI MAPPER_PRIM_FLOAT = new ArraysMapper(null) { @Override public float[] convert(Object current) { int p = 0; float[] r = new float[((List) current).size()]; for (Object e : ((List) current)) r[p++] = ((Number) e).floatValue(); return r; } }; public static JsonReaderI MAPPER_FLOAT = new ArraysMapper(null) { @Override public Float[] convert(Object current) { int p = 0; Float[] r = new Float[((List) current).size()]; for (Object e : ((List) current)) { if (e == null) continue; if (e instanceof Float) r[p] = ((Float) e); else r[p] = ((Number) e).floatValue(); p++; } return r; } }; public static JsonReaderI MAPPER_PRIM_DOUBLE = new ArraysMapper(null) { @Override public double[] convert(Object current) { int p = 0; double[] r = new double[((List) current).size()]; for (Object e : ((List) current)) r[p++] = ((Number) e).doubleValue(); return r; } }; public static JsonReaderI MAPPER_DOUBLE = new ArraysMapper(null) { @Override public Double[] convert(Object current) { int p = 0; Double[] r = new Double[((List) current).size()]; for (Object e : ((List) current)) { if (e == null) continue; if (e instanceof Double) r[p] = ((Double) e); else r[p] = ((Number) e).doubleValue(); p++; } return r; } }; public static JsonReaderI MAPPER_PRIM_BOOL = new ArraysMapper(null) { @Override public boolean[] convert(Object current) { int p = 0; boolean[] r = new boolean[((List) current).size()]; for (Object e : ((List) current)) r[p++] = ((Boolean) e).booleanValue(); return r; } }; public static JsonReaderI MAPPER_BOOL = new ArraysMapper(null) { @Override public Boolean[] convert(Object current) { int p = 0; Boolean[] r = new Boolean[((List) current).size()]; for (Object e : ((List) current)) { if (e == null) continue; if (e instanceof Boolean) r[p] = ((Boolean) e).booleanValue(); else if (e instanceof Number) r[p] = ((Number) e).intValue() != 0; else throw new RuntimeException("can not convert " + e + " toBoolean"); p++; } return r; } }; } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/BeansMapper.java000066400000000000000000000101331255620162700303020ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Type; import java.util.Date; import java.util.HashMap; import net.minidev.asm.Accessor; import net.minidev.asm.BeansAccess; import net.minidev.asm.ConvertDate; import net.minidev.json.JSONUtil; @SuppressWarnings("unchecked") public abstract class BeansMapper extends JsonReaderI { public BeansMapper(JsonReader base) { super(base); } public abstract Object getValue(Object current, String key); public static class Bean extends JsonReaderI { final Class clz; final BeansAccess ba; final HashMap index; public Bean(JsonReader base, Class clz) { super(base); this.clz = clz; this.ba = BeansAccess.get(clz, JSONUtil.JSON_SMART_FIELD_FILTER); this.index = ba.getMap(); } @Override public void setValue(Object current, String key, Object value) { ba.set((T) current, key, value); // Accessor nfo = index.get(key); // if (nfo == null) // throw new RuntimeException("Can not set " + key + " field in " + // clz); // value = JSONUtil.convertTo(value, nfo.getType()); // ba.set((T) current, nfo.getIndex(), value); } public Object getValue(Object current, String key) { return ba.get((T) current, key); // Accessor nfo = index.get(key); // if (nfo == null) // throw new RuntimeException("Can not set " + key + " field in " + // clz); // return ba.get((T) current, nfo.getIndex()); } @Override public Type getType(String key) { Accessor nfo = index.get(key); return nfo.getGenericType(); } @Override public JsonReaderI startArray(String key) { Accessor nfo = index.get(key); if (nfo == null) throw new RuntimeException("Can not find Array '" + key + "' field in " + clz); return base.getMapper(nfo.getGenericType()); } @Override public JsonReaderI startObject(String key) { Accessor f = index.get(key); if (f == null) throw new RuntimeException("Can not find Object '" + key + "' field in " + clz); return base.getMapper(f.getGenericType()); } @Override public Object createObject() { return ba.newInstance(); } } public static class BeanNoConv extends JsonReaderI { final Class clz; final BeansAccess ba; final HashMap index; public BeanNoConv(JsonReader base, Class clz) { super(base); this.clz = clz; this.ba = BeansAccess.get(clz, JSONUtil.JSON_SMART_FIELD_FILTER); this.index = ba.getMap(); } @Override public void setValue(Object current, String key, Object value) { ba.set((T) current, key, value); } public Object getValue(Object current, String key) { return ba.get((T) current, key); } @Override public Type getType(String key) { Accessor nfo = index.get(key); return nfo.getGenericType(); } @Override public JsonReaderI startArray(String key) { Accessor nfo = index.get(key); if (nfo == null) throw new RuntimeException("Can not set " + key + " field in " + clz); return base.getMapper(nfo.getGenericType()); } @Override public JsonReaderI startObject(String key) { Accessor f = index.get(key); if (f == null) throw new RuntimeException("Can not set " + key + " field in " + clz); return base.getMapper(f.getGenericType()); } @Override public Object createObject() { return ba.newInstance(); } } public static JsonReaderI MAPPER_DATE = new ArraysMapper(null) { @Override public Date convert(Object current) { return ConvertDate.convertToDate(current); } }; } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/CollectionMapper.java000066400000000000000000000143371255620162700313570ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import net.minidev.asm.BeansAccess; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import net.minidev.json.JSONUtil; public class CollectionMapper { public static class MapType extends JsonReaderI { final ParameterizedType type; final Class rawClass; final Class instance; final BeansAccess ba; final Type keyType; final Type valueType; final Class keyClass; final Class valueClass; JsonReaderI subMapper; public MapType(JsonReader base, ParameterizedType type) { super(base); this.type = type; this.rawClass = (Class) type.getRawType(); if (rawClass.isInterface()) instance = JSONObject.class; else instance = rawClass; ba = BeansAccess.get(instance, JSONUtil.JSON_SMART_FIELD_FILTER); keyType = type.getActualTypeArguments()[0]; valueType = type.getActualTypeArguments()[1]; if (keyType instanceof Class) keyClass = (Class) keyType; else keyClass = (Class) ((ParameterizedType) keyType).getRawType(); if (valueType instanceof Class) valueClass = (Class) valueType; else valueClass = (Class) ((ParameterizedType) valueType).getRawType(); } @Override public Object createObject() { try { return instance.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } @Override public JsonReaderI startArray(String key) { if (subMapper == null) subMapper = base.getMapper(valueType); return subMapper; } @Override public JsonReaderI startObject(String key) { if (subMapper == null) subMapper = base.getMapper(valueType); return subMapper; } @SuppressWarnings("unchecked") @Override public void setValue(Object current, String key, Object value) { ((Map) current).put(JSONUtil.convertToX(key, keyClass), JSONUtil.convertToX(value, valueClass)); } @SuppressWarnings("unchecked") @Override public Object getValue(Object current, String key) { return ((Map) current).get(JSONUtil.convertToX(key, keyClass)); } @Override public Type getType(String key) { return type; } }; public static class MapClass extends JsonReaderI { final Class type; final Class instance; final BeansAccess ba; JsonReaderI subMapper; public MapClass(JsonReader base, Class type) { super(base); this.type = type; if (type.isInterface()) this.instance = JSONObject.class; else this.instance = type; this.ba = BeansAccess.get(instance, JSONUtil.JSON_SMART_FIELD_FILTER); } @Override public Object createObject() { return ba.newInstance(); } @Override public JsonReaderI startArray(String key) { return base.DEFAULT ; // _ARRAY } @Override public JsonReaderI startObject(String key) { return base.DEFAULT; // _MAP } @SuppressWarnings("unchecked") @Override public void setValue(Object current, String key, Object value) { ((Map) current).put(key, value); } @SuppressWarnings("unchecked") @Override public Object getValue(Object current, String key) { return ((Map) current).get(key); } @Override public Type getType(String key) { return type; } }; public static class ListType extends JsonReaderI { final ParameterizedType type; final Class rawClass; final Class instance; final BeansAccess ba; final Type valueType; final Class valueClass; JsonReaderI subMapper; public ListType(JsonReader base, ParameterizedType type) { super(base); this.type = type; this.rawClass = (Class) type.getRawType(); if (rawClass.isInterface()) instance = JSONArray.class; else instance = rawClass; ba = BeansAccess.get(instance, JSONUtil.JSON_SMART_FIELD_FILTER); // NEW valueType = type.getActualTypeArguments()[0]; if (valueType instanceof Class) valueClass = (Class) valueType; else valueClass = (Class) ((ParameterizedType) valueType).getRawType(); } @Override public Object createArray() { return ba.newInstance(); } @Override public JsonReaderI startArray(String key) { if (subMapper == null) subMapper = base.getMapper(type.getActualTypeArguments()[0]); return subMapper; } @Override public JsonReaderI startObject(String key) { if (subMapper == null) subMapper = base.getMapper(type.getActualTypeArguments()[0]); return subMapper; } @SuppressWarnings("unchecked") @Override public void addValue(Object current, Object value) { ((List) current).add(JSONUtil.convertToX(value, valueClass)); } }; public static class ListClass extends JsonReaderI { final Class type; final Class instance; final BeansAccess ba; JsonReaderI subMapper; public ListClass(JsonReader base, Class clazz) { super(base); this.type = clazz; if (clazz.isInterface()) instance = JSONArray.class; else instance = clazz; ba = BeansAccess.get(instance, JSONUtil.JSON_SMART_FIELD_FILTER); } @Override public Object createArray() { return ba.newInstance(); } @Override public JsonReaderI startArray(String key) { return base.DEFAULT;// _ARRAY; } @Override public JsonReaderI startObject(String key) { return base.DEFAULT;// _MAP; } @SuppressWarnings("unchecked") @Override public void addValue(Object current, Object value) { ((List) current).add(value); } }; } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/CompessorMapper.java000066400000000000000000000121431255620162700312270ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; public class CompessorMapper extends JsonReaderI { private Appendable out; private JSONStyle compression; private Boolean _isObj; private boolean needSep = false; private boolean isOpen = false; private boolean isClosed = false; // private boolean isRoot = false; private boolean isArray() { return _isObj == Boolean.FALSE; } private boolean isObject() { return _isObj == Boolean.TRUE; } private boolean isCompressor(Object obj) { return obj instanceof CompessorMapper; } public CompessorMapper(JsonReader base, Appendable out, JSONStyle compression) { this(base, out, compression, null); // isRoot = true; } public CompessorMapper(JsonReader base, Appendable out, JSONStyle compression, Boolean isObj) { super(base); this.out = out; this.compression = compression; this._isObj = isObj; // System.out.println("new CompressorMapper isObj:" + isObj); } @Override public JsonReaderI startObject(String key) throws IOException { open(this); startKey(key); // System.out.println("startObject " + key); CompessorMapper r = new CompessorMapper(base, out, compression, true); open(r); return r; } @Override public JsonReaderI startArray(String key) throws IOException { open(this); startKey(key); // System.out.println("startArray " + key); CompessorMapper r = new CompessorMapper(base, out, compression, false); open(r); return r; } private void startKey(String key) throws IOException { addComma(); // if (key == null) // return; if (isArray()) return; if (!compression.mustProtectKey(key)) out.append(key); else { out.append('"'); JSONValue.escape(key, out, compression); out.append('"'); } out.append(':'); } @Override public void setValue(Object current, String key, Object value) throws IOException { // System.out.println("setValue(" + key + "," + value + ")"); // if comprossor => data allready writed if (isCompressor(value)) { addComma(); return; } startKey(key); writeValue(value); } @Override public void addValue(Object current, Object value) throws IOException { // System.out.println("add value" + value); // if (!isCompressor(value)) addComma(); writeValue(value); } private void addComma() throws IOException { if (needSep) { out.append(','); // needSep = false; } else { needSep = true; } } private void writeValue(Object value) throws IOException { if (value instanceof String) { compression.writeString(out, (String) value); // // if (!compression.mustProtectValue((String) value)) // out.append((String) value); // else { // out.append('"'); // JSONValue.escape((String) value, out, compression); // out.append('"'); // } // needSep = true; } else { if (isCompressor(value)) { close(value); // needSep = true; } else { JSONValue.writeJSONString(value, out, compression); // needSep = true; } } } @Override public Object createObject() { // System.out.println("createObject"); this._isObj = true; try { open(this); } catch (Exception e) { } // if (this.isUnknow() && isRoot) { // && isRoot // this._isObj = true; // try { // out.append('{'); // 1 // } catch (Exception e) { // } // } return this; } @Override public Object createArray() { // System.out.println("createArray"); this._isObj = false; try { open(this); } catch (Exception e) { } return this; } public CompessorMapper convert(Object current) { try { close(current); return this; } catch (Exception e) { return this; } } private void close(Object obj) throws IOException { if (!isCompressor(obj)) return; if (((CompessorMapper) obj).isClosed) return; ((CompessorMapper) obj).isClosed = true; if (((CompessorMapper) obj).isObject()) { // System.out.println("convert }"); out.append('}'); needSep = true; } else if (((CompessorMapper) obj).isArray()) { // System.out.println("convert ]"); out.append(']'); needSep = true; } } private void open(Object obj) throws IOException { if (!isCompressor(obj)) return; if (((CompessorMapper) obj).isOpen) return; ((CompessorMapper) obj).isOpen = true; if (((CompessorMapper) obj).isObject()) { // System.out.println("open {"); out.append('{'); needSep = false; } else if (((CompessorMapper) obj).isArray()) { // System.out.println("open ["); out.append('['); needSep = false; } } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/DefaultMapper.java000066400000000000000000000027601255620162700306450ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011-2014 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import net.minidev.json.JSONArray; import net.minidev.json.JSONAwareEx; import net.minidev.json.JSONObject; /** * Simple Reader Class for generic Map * * @author uriel * * @param */ public class DefaultMapper extends JsonReaderI { protected DefaultMapper(JsonReader base) { super(base); } @Override public JsonReaderI startObject(String key) { return base.DEFAULT; } @Override public JsonReaderI startArray(String key) { return base.DEFAULT; } @Override public Object createObject() { return new JSONObject(); } @Override public Object createArray() { return new JSONArray(); } @Override public void setValue(Object current, String key, Object value) { ((JSONObject) current).put(key, value); } @Override public void addValue(Object current, Object value) { ((JSONArray) current).add(value); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/DefaultMapperCollection.java000066400000000000000000000034471255620162700326640ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Constructor; import java.util.List; import java.util.Map; public class DefaultMapperCollection extends JsonReaderI { Class clz; //? extends Collection public DefaultMapperCollection(JsonReader base, Class clz) { super(base); this.clz = clz; } // public static AMapper DEFAULT = new // DefaultMapperCollection(); @Override public JsonReaderI startObject(String key) { return this; } @Override public JsonReaderI startArray(String key) { return this; } @Override public Object createObject() { try { Constructor c = clz.getConstructor(); return c.newInstance(); } catch (Exception e) { return null; } } @Override public Object createArray() { try { Constructor c = clz.getConstructor(); return c.newInstance(); } catch (Exception e) { return null; } } @SuppressWarnings({ "unchecked"}) @Override public void setValue(Object current, String key, Object value) { ((Map) current).put(key, value); } @SuppressWarnings("unchecked") @Override public void addValue(Object current, Object value) { ((List) current).add(value); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/DefaultMapperOrdered.java000066400000000000000000000030001255620162700321360ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.LinkedHashMap; import java.util.Map; import net.minidev.json.JSONArray; import net.minidev.json.JSONAwareEx; public class DefaultMapperOrdered extends JsonReaderI { protected DefaultMapperOrdered(JsonReader base) { super(base); }; @Override public JsonReaderI startObject(String key) { return base.DEFAULT_ORDERED; } @Override public JsonReaderI startArray(String key) { return base.DEFAULT_ORDERED; } @SuppressWarnings("unchecked") public void setValue(Object current, String key, Object value) { ((Map) current).put(key, value); } @Override public Object createObject() { return new LinkedHashMap(); } @Override public void addValue(Object current, Object value) { ((JSONArray) current).add(value); } @Override public Object createArray() { return new JSONArray(); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/FakeMapper.java000066400000000000000000000023151255620162700301230ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class FakeMapper extends JsonReaderI { private FakeMapper() { super(null); } public static JsonReaderI DEFAULT = new FakeMapper(); @Override public JsonReaderI startObject(String key) { return this; } @Override public JsonReaderI startArray(String key) { return this; } @Override public void setValue(Object current, String key, Object value) { } @Override public void addValue(Object current, Object value) { } @Override public Object createObject() { return null; } @Override public Object createArray() { return null; } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/JsonReader.java000066400000000000000000000113411255620162700301430ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import net.minidev.json.JSONArray; import net.minidev.json.JSONAware; import net.minidev.json.JSONAwareEx; import net.minidev.json.JSONObject; public class JsonReader { private final ConcurrentHashMap> cache; public JsonReaderI DEFAULT; public JsonReaderI DEFAULT_ORDERED; public JsonReader() { cache = new ConcurrentHashMap>(100); cache.put(Date.class, BeansMapper.MAPPER_DATE); cache.put(int[].class, ArraysMapper.MAPPER_PRIM_INT); cache.put(Integer[].class, ArraysMapper.MAPPER_INT); cache.put(short[].class, ArraysMapper.MAPPER_PRIM_INT); cache.put(Short[].class, ArraysMapper.MAPPER_INT); cache.put(long[].class, ArraysMapper.MAPPER_PRIM_LONG); cache.put(Long[].class, ArraysMapper.MAPPER_LONG); cache.put(byte[].class, ArraysMapper.MAPPER_PRIM_BYTE); cache.put(Byte[].class, ArraysMapper.MAPPER_BYTE); cache.put(char[].class, ArraysMapper.MAPPER_PRIM_CHAR); cache.put(Character[].class, ArraysMapper.MAPPER_CHAR); cache.put(float[].class, ArraysMapper.MAPPER_PRIM_FLOAT); cache.put(Float[].class, ArraysMapper.MAPPER_FLOAT); cache.put(double[].class, ArraysMapper.MAPPER_PRIM_DOUBLE); cache.put(Double[].class, ArraysMapper.MAPPER_DOUBLE); cache.put(boolean[].class, ArraysMapper.MAPPER_PRIM_BOOL); cache.put(Boolean[].class, ArraysMapper.MAPPER_BOOL); this.DEFAULT = new DefaultMapper(this); this.DEFAULT_ORDERED = new DefaultMapperOrdered(this); cache.put(JSONAwareEx.class, this.DEFAULT); cache.put(JSONAware.class, this.DEFAULT); cache.put(JSONArray.class, this.DEFAULT); cache.put(JSONObject.class, this.DEFAULT); } /** * remap field name in custom classes * * @param fromJson * field name in json * @param toJava * field name in Java * @since 2.1.1 */ public void remapField(Class type, String fromJson, String toJava) { JsonReaderI map = this.getMapper(type); if (!(map instanceof MapperRemapped)) { map = new MapperRemapped(map); registerReader(type, map); } ((MapperRemapped) map).renameField(fromJson, toJava); } public void registerReader(Class type, JsonReaderI mapper) { cache.put(type, mapper); } @SuppressWarnings("unchecked") public JsonReaderI getMapper(Type type) { if (type instanceof ParameterizedType) return getMapper((ParameterizedType) type); return getMapper((Class) type); } /** * Get the corresponding mapper Class, or create it on first call * * @param type * to be map */ public JsonReaderI getMapper(Class type) { // look for cached Mapper @SuppressWarnings("unchecked") JsonReaderI map = (JsonReaderI) cache.get(type); if (map != null) return map; /* * Special handle */ if (type instanceof Class) { if (Map.class.isAssignableFrom(type)) map = new DefaultMapperCollection(this, type); else if (List.class.isAssignableFrom(type)) map = new DefaultMapperCollection(this, type); if (map != null) { cache.put(type, map); return map; } } if (type.isArray()) map = new ArraysMapper.GenericMapper(this, type); else if (List.class.isAssignableFrom(type)) map = new CollectionMapper.ListClass(this, type); else if (Map.class.isAssignableFrom(type)) map = new CollectionMapper.MapClass(this, type); else // use bean class map = new BeansMapper.Bean(this, type); cache.putIfAbsent(type, map); return map; } @SuppressWarnings("unchecked") public JsonReaderI getMapper(ParameterizedType type) { JsonReaderI map = (JsonReaderI) cache.get(type); if (map != null) return map; Class clz = (Class) type.getRawType(); if (List.class.isAssignableFrom(clz)) map = new CollectionMapper.ListType(this, type); else if (Map.class.isAssignableFrom(clz)) map = new CollectionMapper.MapType(this, type); cache.putIfAbsent(type, map); return map; } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/JsonReaderI.java000066400000000000000000000062001255620162700302520ustar00rootroot00000000000000package net.minidev.json.writer; /* * Copyright 2011 JSON-SMART authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.lang.reflect.Type; import net.minidev.json.parser.ParseException; /** * Default datatype mapper use by Json-smart ton store data. * * @author uriel Chemouni * * @param */ public abstract class JsonReaderI { public final JsonReader base; /** * Reader can be link to the JsonReader Base * * @param base */ public JsonReaderI(JsonReader base) { this.base = base; } private static String ERR_MSG = "Invalid or non Implemented status"; /** * called when json-smart parser meet an object key */ public JsonReaderI startObject(String key) throws ParseException, IOException { throw new RuntimeException(ERR_MSG + " startObject(String key) in " + this.getClass() + " key=" + key); } /** * called when json-smart parser start an array. * * @param key * the destination key name, or null. */ public JsonReaderI startArray(String key) throws ParseException, IOException { throw new RuntimeException(ERR_MSG + " startArray in " + this.getClass() + " key=" + key); } /** * called when json-smart done parsing a value */ public void setValue(Object current, String key, Object value) throws ParseException, IOException { throw new RuntimeException(ERR_MSG + " setValue in " + this.getClass() + " key=" + key); } /** * ------------- */ public Object getValue(Object current, String key) { throw new RuntimeException(ERR_MSG + " getValue(Object current, String key) in " + this.getClass() + " key=" + key); } // Object current, public Type getType(String key) { throw new RuntimeException(ERR_MSG + " getType(String key) in " + this.getClass() + " key=" + key); } /** * add a value in an array json object. */ public void addValue(Object current, Object value) throws ParseException, IOException { throw new RuntimeException(ERR_MSG + " addValue(Object current, Object value) in " + this.getClass()); } /** * use to instantiate a new object that will be used as an object */ public Object createObject() { throw new RuntimeException(ERR_MSG + " createObject() in " + this.getClass()); } /** * use to instantiate a new object that will be used as an array */ public Object createArray() { throw new RuntimeException(ERR_MSG + " createArray() in " + this.getClass()); } /** * Allow a mapper to converte a temprary structure to the final data format. * * example: convert an List to an int[] */ @SuppressWarnings("unchecked") public T convert(Object current) { return (T) current; } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/MapperRemapped.java000066400000000000000000000030141255620162700310070ustar00rootroot00000000000000package net.minidev.json.writer; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import net.minidev.json.parser.ParseException; /** * Simple solution to supporr on read filed renaming * * @author uriel * * @param */ public class MapperRemapped extends JsonReaderI { private Map rename; private JsonReaderI parent; public MapperRemapped(JsonReaderI parent) { super(parent.base); this.parent = parent; this.rename = new HashMap(); } public void renameField(String source, String dest) { rename.put(source, dest); } private String rename(String key) { String k2 = rename.get(key); if (k2 != null) return k2; return key; } @Override public void setValue(Object current, String key, Object value) throws ParseException, IOException { key = rename(key); parent.setValue(current, key, value); } public Object getValue(Object current, String key) { key = rename(key); return parent.getValue(current, key); } @Override public Type getType(String key) { key = rename(key); return parent.getType(key); } @Override public JsonReaderI startArray(String key) throws ParseException, IOException { key = rename(key); return parent.startArray(key); } @Override public JsonReaderI startObject(String key) throws ParseException, IOException { key = rename(key); return parent.startObject(key); } @Override public Object createObject() { return parent.createObject(); } } json-smart-v2-2.2/json-smart/src/main/java/net/minidev/json/writer/UpdaterMapper.java000066400000000000000000000045021255620162700306610ustar00rootroot00000000000000package net.minidev.json.writer; import java.io.IOException; import java.lang.reflect.Type; import net.minidev.json.parser.ParseException; public class UpdaterMapper extends JsonReaderI { final T obj; final JsonReaderI mapper; public UpdaterMapper(JsonReader base, T obj) { super(base); if (obj == null) throw new NullPointerException("can not update null Object"); this.obj = obj; this.mapper = (JsonReaderI) base.getMapper(obj.getClass()); } public UpdaterMapper(JsonReader base, T obj, Type type) { super(base); if (obj == null) throw new NullPointerException("can not update null Object"); this.obj = obj; this.mapper = (JsonReaderI) base.getMapper(type); } /** * called when json-smart parser meet an object key */ public JsonReaderI startObject(String key) throws ParseException, IOException { Object bean = mapper.getValue(obj, key); if (bean == null) return mapper.startObject(key); return new UpdaterMapper(base, bean, mapper.getType(key)); } /** * called when json-smart parser start an array. * * @param key * the destination key name, or null. */ public JsonReaderI startArray(String key) throws ParseException, IOException { // if (obj != null) return mapper.startArray(key); } /** * called when json-smart done parsing a value */ public void setValue(Object current, String key, Object value) throws ParseException, IOException { // if (obj != null) mapper.setValue(current, key, value); } /** * add a value in an array json object. */ public void addValue(Object current, Object value) throws ParseException, IOException { // if (obj != null) mapper.addValue(current, value); } /** * use to instantiate a new object that will be used as an object */ public Object createObject() { if (obj != null) return obj; return mapper.createObject(); } /** * use to instantiate a new object that will be used as an array */ public Object createArray() { if (obj != null) return obj; return mapper.createArray(); } /** * Allow a mapper to converte a temprary structure to the final data format. * * example: convert an List to an int[] */ @SuppressWarnings("unchecked") public T convert(Object current) { if (obj != null) return obj; return (T) mapper.convert(current); } } json-smart-v2-2.2/json-smart/src/test/000077500000000000000000000000001255620162700176505ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/000077500000000000000000000000001255620162700205715ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/000077500000000000000000000000001255620162700213575ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/minidev/000077500000000000000000000000001255620162700230125ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/000077500000000000000000000000001255620162700237635ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/000077500000000000000000000000001255620162700247425ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/JSONSimpleTest.java000066400000000000000000000012161255620162700303700ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONArray; import net.minidev.json.parser.JSONParser; public class JSONSimpleTest extends TestCase { public void testLong() throws Exception { String s = "[1]"; JSONParser p = new JSONParser(JSONParser.MODE_JSON_SIMPLE); JSONArray array = (JSONArray) p.parse(s); assertEquals(Long.valueOf(1), (Long) array.get(0)); } public void testDefault() throws Exception { String s = "[1]"; JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE); JSONArray array = (JSONArray) p.parse(s); assertEquals(Integer.valueOf(1), (Integer) array.get(0)); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/MustThrows.java000066400000000000000000000022271255620162700277470ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; public class MustThrows { public static void testStrictInvalidJson(String json, int execptionType) throws Exception { testStrictInvalidJson(json, execptionType, null); } public static void testStrictInvalidJson(String json, int execptionType, Class cls) throws Exception { testInvalidJson(json, JSONParser.MODE_RFC4627, execptionType, cls); } public static void testInvalidJson(String json, int permissifMode, int execptionType) throws Exception { testInvalidJson(json, permissifMode, execptionType, null); } public static void testInvalidJson(String json, int permissifMode, int execptionType, Class cls) throws Exception { JSONParser p = new JSONParser(permissifMode); try { if (cls == null) p.parse(json); else p.parse(json, cls); TestCase.assertFalse("Exception Should Occure parsing:" + json, true); } catch (ParseException e) { if (execptionType == -1) execptionType = e.getErrorType(); TestCase.assertEquals(execptionType, e.getErrorType()); } } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestBigValue.java000066400000000000000000000024661255620162700301530ustar00rootroot00000000000000package net.minidev.json.test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; import junit.framework.TestCase; public class TestBigValue extends TestCase { String bigStr = "12345678901234567890123456789"; /** * test BigDecimal serialization */ public void testBigDecimal() { HashMap map = new HashMap(); BigDecimal bigDec = new BigDecimal(bigStr + "." + bigStr); map.put("big", bigDec); String test = JSONValue.toJSONString(map); String result = "{\"big\":" + bigStr + "." +bigStr + "}"; assertEquals(result, test); JSONObject obj = (JSONObject)JSONValue.parse(test); assertEquals(bigDec, obj.get("big")); assertEquals(bigDec.getClass(), obj.get("big").getClass()); } /** * test BigInteger serialization */ public void testBigInteger() { HashMap map = new HashMap(); BigInteger bigInt = new BigInteger(bigStr); map.put("big", bigInt); String test = JSONValue.toJSONString(map); String result = "{\"big\":" + bigStr + "}"; assertEquals(result, test); JSONObject obj = (JSONObject)JSONValue.parse(test); assertEquals(bigInt, obj.get("big")); assertEquals(bigInt.getClass(), obj.get("big").getClass()); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestCompressor.java000066400000000000000000000022561255620162700306060ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONValue; public class TestCompressor extends TestCase { public void testCompressor() { String j = "{'a':{'b':'c','d':'e'},f:[1,2,'XYZ']}".replace('\'', '"'); String sol = j.replace(" ", "").replace("\"", ""); String comp = JSONValue.compress(j); assertEquals(sol, comp); } public void testCompressor2() { String j = "[{} ]"; String sol = j.replace(" ", ""); String comp = JSONValue.compress(j); assertEquals(sol, comp); } public void testCompressor3() { String j = "[[],[],[] ]"; String sol = j.replace(" ", ""); String comp = JSONValue.compress(j); assertEquals(sol, comp); } public void testCompressor4() { String j = "[[1],[2,3],[4] ]"; String sol = j.replace(" ", ""); String comp = JSONValue.compress(j); assertEquals(sol, comp); } public void testCompressor5() { String j = "[{},{},{} ]"; String sol = j.replace(" ", ""); String comp = JSONValue.compress(j); assertEquals(sol, comp); } public void testCompressor6() { String j = "[{a:b},{c:d},{e:f}]"; String sol = j; String comp = JSONValue.compress(j); assertEquals(sol, comp); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestCompressorFlags.java000066400000000000000000000047371255620162700315710ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONObject; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; /** * Test all Compression Styles * * @author Uriel Chemouni * */ public class TestCompressorFlags extends TestCase { public void testProtect() throws Exception { String compressed = "{k:value}"; String nCompress = "{\"k\":\"value\"}"; JSONObject obj = (JSONObject) JSONValue.parse(nCompress); // test MAX_COMPRESS String r = obj.toJSONString(JSONStyle.MAX_COMPRESS); assertEquals(compressed, r); // test LT_COMPRESS r = obj.toJSONString(JSONStyle.LT_COMPRESS); assertEquals(nCompress, r); // test NO_COMPRESS r = obj.toJSONString(JSONStyle.NO_COMPRESS); assertEquals(nCompress, r); // only keys values JSONStyle style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_KEYS); r = obj.toJSONString(style); assertEquals("{k:\"value\"}", r); // only protect values style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_VALUES); r = obj.toJSONString(style); assertEquals("{\"k\":value}", r); } public void testAggresive() throws Exception { String r; JSONStyle style; String NProtectValue = "{\"a b\":\"c d\"}"; JSONObject obj = (JSONObject) JSONValue.parse(NProtectValue); /** * Test Without Agressive */ style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_KEYS); r = obj.toJSONString(style); assertEquals(NProtectValue, r); style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_VALUES); r = obj.toJSONString(style); assertEquals(NProtectValue, r); /** * Test With Agressive */ style = new JSONStyle(-1 & (JSONStyle.FLAG_PROTECT_VALUES | JSONStyle.FLAG_AGRESSIVE)); r = obj.toJSONString(style); assertEquals("{\"a b\":c d}", r); style = new JSONStyle(-1 & (JSONStyle.FLAG_PROTECT_KEYS | JSONStyle.FLAG_AGRESSIVE)); r = obj.toJSONString(style); assertEquals("{a b:\"c d\"}", r); style = JSONStyle.MAX_COMPRESS; r = obj.toJSONString(style); assertEquals("{a b:c d}", r); } public void test4Web() throws Exception { String NProtectValue = "{\"k\":\"http:\\/\\/url\"}"; JSONObject obj = (JSONObject) JSONValue.parse(NProtectValue); String r = obj.toJSONString(JSONStyle.MAX_COMPRESS); assertEquals("{k:\"http://url\"}", r); r = obj.toJSONString(JSONStyle.LT_COMPRESS); assertEquals("{\"k\":\"http://url\"}", r); r = obj.toJSONString(JSONStyle.NO_COMPRESS); assertEquals("{\"k\":\"http:\\/\\/url\"}", r); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestFloat.java000066400000000000000000000031601255620162700275120ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONObject; import net.minidev.json.JSONStyle; import net.minidev.json.parser.JSONParser; public class TestFloat extends TestCase { public static String[] TRUE_NUMBERS = new String[] { "1.0", "123.456", "1.0E1", "123.456E12", "1.0E+1", "123.456E+12", "1.0E-1", "123.456E-12", "1.0e1", "123.456e12", "1.0e+1", "123.456e+12", "1.0e-1", "123.456e-12" }; public static String[] FALSE_NUMBERS = new String[] { "1.0%", "123.45.6", "1.0E", "++123.456E12", "+-01", "1.0E+1.2" }; public void testFloat() throws Exception { JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE); for (String s : TRUE_NUMBERS) { String json = "{v:" + s + "}"; Double val = Double.valueOf(s.trim()); JSONObject obj = (JSONObject) p.parse(json); Object value = obj.get("v"); assertEquals("Should be parse as double", val, value); } } public void testNonFloat() throws Exception { JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE); for (String s : FALSE_NUMBERS) { String json = "{v:" + s + "}"; JSONObject obj = (JSONObject) p.parse(json); assertEquals("Should be parse as string", s, obj.get("v")); String correct = "{\"v\":\"" + s + "\"}"; assertEquals("Should be re serialized as", correct, obj.toJSONString()); } } /** * Error reported in issue 44 */ public void testUUID() { String UUID = "58860611416142319131902418361e88"; JSONObject obj = new JSONObject(); obj.put("uuid", UUID); String compressed =obj.toJSONString(JSONStyle.MAX_COMPRESS); assertTrue(compressed.contains("uuid:\"")); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestFloatStrict.java000066400000000000000000000013341255620162700307040ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; public class TestFloatStrict extends TestCase { public void testFloat() throws Exception { for (String s : TestFloat.TRUE_NUMBERS) { String json = "{\"v\":" + s + "}"; Double val = Double.valueOf(s.trim()); JSONObject obj = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(json); Object value = obj.get("v"); assertEquals("Should be parse as double", val, value); } } public void testNonFloat() throws Exception { for (String s : TestFloat.FALSE_NUMBERS) { String json = "{\"v\":" + s + "}"; MustThrows.testStrictInvalidJson(json, -1); } } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestInts.java000066400000000000000000000060051255620162700273630ustar00rootroot00000000000000package net.minidev.json.test; import java.math.BigDecimal; import java.math.BigInteger; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; import junit.framework.TestCase; public class TestInts extends TestCase { public void testIntMax() throws Exception { String s = "{t:" + Integer.MAX_VALUE + "}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), Integer.MAX_VALUE); } public void testIntMin() throws Exception { String s = "{t:" + Integer.MIN_VALUE + "}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), Integer.MIN_VALUE); } public void testIntResult() throws Exception { String s = "{\"t\":1}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s); assertEquals(o.get("t"), Integer.valueOf(1)); o = (JSONObject) new JSONParser(JSONParser.MODE_JSON_SIMPLE).parse(s); assertEquals(o.get("t"), Long.valueOf(1)); o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), Integer.valueOf(1)); } public void testInt() throws Exception { String s = "{t:90}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), Integer.valueOf(90)); } public void testIntNeg() throws Exception { String s = "{t:-90}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), -90); } public void testBigInt() throws Exception { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) sb.append(Integer.MAX_VALUE); String bigText = sb.toString(); BigInteger big = new BigInteger(bigText, 10); String s = "{t:" + bigText + "}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), big); } public void testBigDoubleInt() throws Exception { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) sb.append(Integer.MAX_VALUE); sb.append('.'); for (int i = 0; i < 10; i++) sb.append(Integer.MAX_VALUE); String bigText = sb.toString(); BigDecimal big = new BigDecimal(bigText); String s = "{\"t\":" + bigText + "}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s); assertEquals(o.get("t"), big); o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), big); } public void testjunkTaillingData() throws Exception { String s = "{\"t\":124}$ifsisg045"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_JSON_SIMPLE).parse(s); assertEquals(o.get("t"), 124L); MustThrows.testInvalidJson(s, JSONParser.MODE_RFC4627, ParseException.ERROR_UNEXPECTED_TOKEN); // o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s); // assertEquals(o.get("t"), 124); o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), 124); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestInvalidNumber.java000066400000000000000000000026051255620162700312070ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONObject; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; public class TestInvalidNumber extends TestCase { public void testF1() { String test = "51e88"; JSONObject o = new JSONObject(); o.put("a", test); String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS); assertEquals("{a:\"51e88\"}", comp); o = JSONValue.parse(comp, JSONObject.class); assertEquals(o.get("a"), test); } public void testF2() { String test = "51e+88"; JSONObject o = new JSONObject(); o.put("a", test); String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS); assertEquals("{a:\"51e+88\"}", comp); o = JSONValue.parse(comp, JSONObject.class); assertEquals(o.get("a"), test); } public void testF3() { String test = "51e-88"; JSONObject o = new JSONObject(); o.put("a", test); String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS); assertEquals("{a:\"51e-88\"}", comp); o = JSONValue.parse(comp, JSONObject.class); assertEquals(o.get("a"), test); } public void testF4() { String test = "51ee88"; JSONObject o = new JSONObject(); o.put("a", test); String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS); assertEquals("{a:51ee88}", comp); o = JSONValue.parse(comp, JSONObject.class); assertEquals(o.get("a"), test); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestKeyword.java000066400000000000000000000020761255620162700300760ustar00rootroot00000000000000package net.minidev.json.test; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; import junit.framework.TestCase; public class TestKeyword extends TestCase { public void testBool() throws Exception { String s = "{t:true}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), true); s = "{t:false}"; o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), false); } public void testNull() throws Exception { String s = "{t:null}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertNull(o.get("t")); } public void testNaN() throws Exception { String s = "{t:NaN}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), Float.NaN); } public void testNaNStrict() throws Exception { String s = "{\"t\":NaN}"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_TOKEN); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestMisc.java000066400000000000000000000033341255620162700273430ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; public class TestMisc extends TestCase { public void testIssue23() throws Exception { String s = JSONValue.toJSONString(new int[] { 1, 2, 50, 1234, 10000 }); assertEquals("[1,2,50,1234,10000]", s); } public void testEmptyStrict() throws Exception { String s = "{\"key1\":\"v1\", \"key2\":{}, \"key3\":[]}"; JSONObject o = (JSONObject) JSONValue.parseStrict(s); assertEquals(o.get("key1"), "v1"); assertEquals(((JSONObject) o.get("key2")).size(), 0); assertEquals(((JSONArray) o.get("key3")).size(), 0); } public void testBool() throws Exception { String s = "{\"key1\":\"v1\", \"key2\":{}, \"key3\":[]}"; JSONObject o = (JSONObject) JSONValue.parseWithException(s); assertEquals(o.get("key1"), "v1"); assertEquals(((JSONObject) o.get("key2")).size(), 0); assertEquals(((JSONArray) o.get("key3")).size(), 0); } public void testInt() throws Exception { String s = "123"; Object o = JSONValue.parseWithException(s); assertEquals(o, 123); } public void testFloat() throws Exception { String s = "123.5"; Object o = JSONValue.parseWithException(s); assertEquals(o, new Double(123.5)); } public void testFloat2() throws Exception { String s = "123.5E1"; Object o = JSONValue.parseWithException(s); assertEquals(o, new Double(1235)); } public void testFloat3() throws Exception { String s = "123..5"; Object o = JSONValue.parseWithException(s); assertEquals(o, "123..5"); } public void testFloat4() throws Exception { String s = "123é.5"; Object o = JSONValue.parseWithException(s); assertEquals(o, 123); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestNavi.java000066400000000000000000000042541255620162700273470ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONAwareEx; import net.minidev.json.JSONNavi; public class TestNavi extends TestCase { public void testNaviWrite() { JSONNavi nav = JSONNavi.newInstance(); nav.set("name", "jhone").set("age", 42).at("childName").add("fifi", "riri", "loulou").up().at("cat") .set("color", "red"); String s1 = "{\"name\":\"jhone\",\"age\":42,\"childName\":[\"fifi\",\"riri\",\"loulou\"],\"cat\":{\"color\":\"red\"}}"; String s2 = nav.toString(); assertEquals(s1, s2); } public void testNaviWrite2() { JSONNavi nav = JSONNavi.newInstance(); nav.at("name").set("toto").up().set("tutu", "V2").at("size").set("width", 10).set("higth", 35).up(3) .set("FinUp", 1).at("array").add(0, 1, 2, 3, 4, 5); nav.at(-1); assertEquals("/array[5]", nav.getJPath()); String s1 = "{'name':'toto','tutu':'V2','size':{'width':10,'higth':35},'FinUp':1,'array':[0,1,2,3,4,5]}" .replace('\'', '"'); String s2 = nav.toString(); assertEquals(s1, s2); } public void testNaviRead() { String json = "{name:foo,str:null,ar:[1,2,3,4]}"; JSONNavi nav = new JSONNavi(json, JSONAwareEx.class); nav.at(5); assertTrue("Navigator should be in error stat", nav.hasFailure()); nav.root(); assertEquals(3, nav.at("ar").at(2).asInt()); nav.up(2); assertEquals(4, nav.at("ar").at(-1).asInt()); nav.up(2); assertEquals("foo", nav.at("name").asString()); } public void testNaviWriteArray() { String expected = "{'type':'bundle','data':[{'type':'object','name':'obj1'},{'type':'object','name':'obj2'}]}".replace('\'', '"'); JSONNavi nav = JSONNavi.newInstance(); nav.set("type", "bundle").at("data").array().at(0).set("type", "object").set("name", "obj1").up().at(1).set("type", "object").set("name", "obj2").root(); String s2 = nav.toString(); assertEquals(expected, nav.toString()); nav = JSONNavi.newInstance(); nav.set("type", "bundle").at("data").array().atNext().set("type", "object").set("name", "obj1").up().atNext().set("type", "object").set("name", "obj2").root(); s2 = nav.toString(); assertEquals(expected, nav.toString()); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestNumberPrecision.java000066400000000000000000000020601255620162700315470ustar00rootroot00000000000000package net.minidev.json.test; import java.math.BigInteger; import junit.framework.TestCase; import net.minidev.json.JSONArray; import net.minidev.json.JSONValue; public class TestNumberPrecision extends TestCase { public void testMaxLong() { Long v = Long.MAX_VALUE; String s = "[" + v + "]"; JSONArray array = (JSONArray) JSONValue.parse(s); Object r = array.get(0); assertEquals(v, r); } public void testMinLong() { Long v = Long.MIN_VALUE; String s = "[" + v + "]"; JSONArray array = (JSONArray) JSONValue.parse(s); Object r = array.get(0); assertEquals(v, r); } public void testMinBig() { BigInteger v = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE); String s = "[" + v + "]"; JSONArray array = (JSONArray) JSONValue.parse(s); Object r = array.get(0); assertEquals(v, r); } public void testMaxBig() { BigInteger v = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); String s = "[" + v + "]"; JSONArray array = (JSONArray) JSONValue.parse(s); Object r = array.get(0); assertEquals(v, r); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestStrict.java000066400000000000000000000031711255620162700277170ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; public class TestStrict extends TestCase { public void testS1() throws Exception { String text = "My Test"; String s = "{t:\"" + text + "\"}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), text); } public void testS2() throws Exception { String text = "My Test"; String s = "{t:'" + text + "'}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), text); } public void testSEscape() throws Exception { String text = "My\r\nTest"; String text2 = "My\\r\\nTest"; String s = "{t:'" + text2 + "'}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), text); } public void testBadString() throws Exception { String s = "{\"t\":\"Before\u000CAfter\"}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals("Before\u000CAfter", o.get("t")); try { o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s); assertEquals("nothink", o.get("t")); } catch (ParseException e) { assertEquals("Exception", "Exception"); } } /** * issue report gitHub 8 by jochenberger */ public void testDataAfterValue() throws Exception { String s = "{\"foo\":\"bar\"x}"; MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST | JSONParser.ACCEPT_TAILLING_SPACE, ParseException.ERROR_UNEXPECTED_TOKEN); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestString.java000066400000000000000000000027751255620162700277260ustar00rootroot00000000000000package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; public class TestString extends TestCase { public void testS0() throws Exception { MustThrows.testStrictInvalidJson("{\"1\":\"one\"\n\"2\":\"two\"}", ParseException.ERROR_UNEXPECTED_TOKEN); } public void testS1() throws Exception { String text = "My Test"; String s = "{t:\"" + text + "\"}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), text); } public void testS2() throws Exception { String text = "My Test"; String s = "{t:'" + text + "'}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), text); } public void testSEscape() throws Exception { String text = "My\r\nTest"; String text2 = "My\\r\\nTest"; String s = "{t:'" + text2 + "'}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), text); } public void testBadString() throws Exception { String s = "{\"t\":\"Before\u000CAfter\"}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals("Before\u000CAfter", o.get("t")); try { o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s); assertEquals("nothink", o.get("t")); } catch (ParseException e) { assertEquals("Exception", "Exception"); } } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestStringStrict.java000066400000000000000000000010461255620162700311050ustar00rootroot00000000000000package net.minidev.json.test; import net.minidev.json.parser.ParseException; import junit.framework.TestCase; public class TestStringStrict extends TestCase { public void testS1() throws Exception { String text = "My Test"; String s = "{t:\"" + text + "\"}"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_TOKEN); } public void testSEscape() throws Exception { String text2 = "My\\r\\nTest"; String s = "{\"t\":'" + text2 + "'}"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/TestTruncated.java000066400000000000000000000011371255620162700304000ustar00rootroot00000000000000package net.minidev.json.test; import net.minidev.json.parser.ParseException; import junit.framework.TestCase; public class TestTruncated extends TestCase { public void testS1() throws Exception { String s = "{\"key\":{}"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_EOF); } public void testS2() throws Exception { String s = "{\"key\":"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_EOF); } public void testS3() throws Exception { String s = "{\"key\":123"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_EOF); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/strict/000077500000000000000000000000001255620162700262525ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/strict/TestExcessiveComma.java000066400000000000000000000026201255620162700326700ustar00rootroot00000000000000package net.minidev.json.test.strict; import junit.framework.TestCase; import net.minidev.json.JSONValue; import net.minidev.json.parser.ParseException; import net.minidev.json.test.MustThrows; public class TestExcessiveComma extends TestCase { public void testExcessiveComma1A() throws Exception { String s = "[1,2,,3]"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR); JSONValue.parseWithException(s); } public void testExcessiveComma2A() throws Exception { String s = "[1,2,]"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR); JSONValue.parseWithException(s); } public void testExcessiveComma3A() throws Exception { String s = "[,]"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR); JSONValue.parseWithException(s); } public void testExcessiveComma1O() throws Exception { String s = "{\"a\":1,,\"b\":1}"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR); JSONValue.parseWithException(s); } public void testExcessiveComma2O() throws Exception { String s = "{\"a\":1,}"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR); JSONValue.parseWithException(s); } public void testExcessiveComma3O() throws Exception { String s = "{,}"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR); JSONValue.parseWithException(s); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/strict/TestTaillingJunk.java000066400000000000000000000030231255620162700323460ustar00rootroot00000000000000package net.minidev.json.test.strict; import junit.framework.TestCase; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; import net.minidev.json.test.MustThrows; /** * @since 1.0.7 */ public class TestTaillingJunk extends TestCase { public void testTaillingSpace() throws Exception { String s = "{\"t\":0} "; MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST, ParseException.ERROR_UNEXPECTED_TOKEN); s = "{\"t\":0} "; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_STRICTEST | JSONParser.ACCEPT_TAILLING_SPACE).parse(s); assertEquals(o.get("t"), 0); } public void testTaillingSpace2() throws Exception { String s = "{\"t\":0} \r\n "; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_STRICTEST | JSONParser.ACCEPT_TAILLING_SPACE).parse(s); assertEquals(o.get("t"), 0); } public void testTaillingData() throws Exception { String s = "{\"t\":0} 0"; MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST, ParseException.ERROR_UNEXPECTED_TOKEN, null); } public void testTaillingDataPermisive() throws Exception { String s = "{\"t\":0} 0"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), 0); } public void testTaillingDataWithSpaceAllowed() throws Exception { String s = "{\"t\":0}{"; MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST | JSONParser.ACCEPT_TAILLING_SPACE, ParseException.ERROR_UNEXPECTED_TOKEN); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/strict/TestZeroLead.java000066400000000000000000000037171255620162700314720ustar00rootroot00000000000000package net.minidev.json.test.strict; import junit.framework.TestCase; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; import net.minidev.json.test.MustThrows; /** * @since 1.0.7 */ public class TestZeroLead extends TestCase { public void test0O() throws Exception { String s = "{\"t\":0}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s); assertEquals(o.get("t"), 0); JSONValue.parseWithException(s); } public void test0A() throws Exception { String s = "[0]"; JSONArray o = (JSONArray) new JSONParser(JSONParser.MODE_RFC4627).parse(s); assertEquals(o.get(0), 0); JSONValue.parseWithException(s); } public void test0Float() throws Exception { String s = "[00.0]"; // strict MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_LEADING_0); // PERMISIVE JSONValue.parseWithException(s); } public void test01Float() throws Exception { String s = "[01.0]"; // strict MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_LEADING_0); // PERMISIVE JSONValue.parseWithException(s); } public void test00001() throws Exception { String s = "{\"t\":00001}"; JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); assertEquals(o.get("t"), 1); JSONValue.parseWithException(s); } public void test00001Strict() throws Exception { String s = "{\"t\":00001}"; MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_LEADING_0); JSONValue.parseWithException(s); } // disable in 1.1 // public void testDup() throws Exception { // String s = "{'t':1,'t':2}"; // try { // new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s); // assertEquals("Should Stack", ""); // } catch (ParseException e) { // assertEquals(ParseException.ERROR_UNEXPECTED_DUPLICATE_KEY, e.getErrorType()); // } // } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/writer/000077500000000000000000000000001255620162700262565ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/test/writer/TestWriteFeatures.java000066400000000000000000000013421255620162700325520ustar00rootroot00000000000000package net.minidev.json.test.writer; import junit.framework.TestCase; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; public class TestWriteFeatures extends TestCase { public void testS1() throws Exception { Beans beans = new Beans(); String s = JSONValue.toJSONString(beans, JSONStyle.MAX_COMPRESS); assertEquals("{}", s); s = JSONValue.toJSONString(beans, JSONStyle.NO_COMPRESS); if (s.startsWith("{\"b")) { assertEquals("{\"b\":null,\"a\":null}", s); } else { assertEquals("{\"a\":null,\"b\":null}", s); } beans.a = "a"; s = JSONValue.toJSONString(beans, JSONStyle.MAX_COMPRESS); assertEquals("{a:a}", s); } public static class Beans { public String a; public String b; } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/000077500000000000000000000000001255620162700262565ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestAdvancedMapper.java000066400000000000000000000016271255620162700326410ustar00rootroot00000000000000package net.minidev.json.testMapping; import java.text.SimpleDateFormat; import java.util.Date; import junit.framework.TestCase; import net.minidev.asm.BeansAccessConfig; import net.minidev.json.JSONValue; public class TestAdvancedMapper extends TestCase { public static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); public void testCustomBean() throws Exception { BeansAccessConfig.addTypeMapper(Object.class, MyLocalConverterot.class); String s = "{'val':2,'date':'19/04/2010'}"; TestBean r = JSONValue.parseWithException(s, TestBean.class); assertEquals("19/04/2010", sdf.format(r.date)); } public static class TestBean { public int val; public Date date; } public static class MyLocalConverterot { public static Date fromString(Object text) throws Exception { if (text == null) return null; synchronized (sdf) { return sdf.parse(text.toString()); } } } } TestCustomMappingInstant.java000066400000000000000000000042101255620162700340260ustar00rootroot00000000000000json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMappingpackage net.minidev.json.testMapping; import java.io.IOException; import junit.framework.Assert; import junit.framework.TestCase; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; import net.minidev.json.parser.ParseException; /** * Test JDK 8+ java.time.Instant * * Serialize a custom class Sample 1 * * @author uriel * */ public class TestCustomMappingInstant extends TestCase { public void test_dummy() throws IOException { @SuppressWarnings("unused") ParseException e = null; JSONValue.toJSONString(true, JSONStyle.MAX_COMPRESS); Assert.assertEquals(true, true); } // Need JDK 1.8 // public void test_instant() { // JSONValue.registerWriter(java.time.Instant.class, new net.minidev.json.reader.JsonWriterI() { // @Override // public void writeJSONString(java.time.Instant value, Appendable out, JSONStyle compression) // throws IOException { // if (value == null) // out.append("null"); // else // out.append(Long.toString(value.toEpochMilli())); // } // }); // // JSONValue.registerReader(RegularClass.class, new net.minidev.json.writer.JsonReaderI(JSONValue.defaultReader) { // @Override // public void setValue(Object current, String key, Object value) throws ParseException, IOException { // if (key.equals("instant")) { // java.time.Instant inst = java.time.Instant.ofEpochMilli((((Number)value).longValue())); // ((RegularClass)current).setInstant(inst); // } // } // @Override // public Object createObject() { // return new RegularClass(); // } // }); // java.time.Instant instant = java.time.Instant.now(); // RegularClass regularClass = new RegularClass(); // regularClass.setInstant(instant); // String data = JSONValue.toJSONString(regularClass); // RegularClass result = JSONValue.parse(data, RegularClass.class); // Assert.assertEquals(result.getInstant(), instant); // } // // public static class RegularClass { // private java.time.Instant instant; // public java.time.Instant getInstant() { // return instant; // } // public void setInstant(java.time.Instant instant) { // this.instant = instant; // } // } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestDate.java000066400000000000000000000010171255620162700306350ustar00rootroot00000000000000package net.minidev.json.testMapping; import junit.framework.TestCase; import net.minidev.json.JSONValue; public class TestDate extends TestCase { public void testBooleans() throws Exception { String s = "[true,true,false]"; boolean[] bs = new boolean[] { true, true, false }; String s2 = JSONValue.toJSONString(bs); assertEquals(s, s2); } public void testInts() throws Exception { String s = "[1,2,3]"; int[] bs = new int[] { 1, 2, 3 }; String s2 = JSONValue.toJSONString(bs); assertEquals(s, s2); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestFieldRename.java000066400000000000000000000012061255620162700321330ustar00rootroot00000000000000package net.minidev.json.testMapping; import junit.framework.TestCase; import net.minidev.json.JSONValue; public class TestFieldRename extends TestCase { public static class TRen { public String new_; public String default_; } public void testRemap() throws Exception { String text = "{'new':'foo','default':'bar'}"; JSONValue.remapField(TRen.class, "default", "default_"); JSONValue.remapField(TRen.class, "new", "new_"); TRen t = JSONValue.parse(text, TRen.class); assertEquals(t.new_, "foo"); assertEquals(t.default_, "bar"); String dest = JSONValue.toJSONString(t); assertTrue(dest.contains("\"default\"")); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestMapBeans.java000066400000000000000000000040401255620162700314450ustar00rootroot00000000000000package net.minidev.json.testMapping; import java.util.Map; import junit.framework.TestCase; import net.minidev.json.JSONValue; public class TestMapBeans extends TestCase { public void testObjInts() throws Exception { String s = "{\"vint\":[1,2,3]}"; T1 r = JSONValue.parse(s, T1.class); assertEquals(3, r.vint[2]); } public void testObjIntKey() throws Exception { String s = "{\"data\":{\"1\":\"toto\"}}"; T2 r = JSONValue.parse(s, T2.class); assertEquals("toto", r.data.get(1)); } public void testObjEnumKey() throws Exception { String s = "{\"data\":{\"red\":10}}"; T3 r = JSONValue.parse(s, T3.class); assertEquals((Integer)10, r.data.get(ColorEnum.red)); } public void testObjBool1() throws Exception { String s = "{\"data\":true}"; T4 r = JSONValue.parse(s, T4.class); assertEquals(true, r.data); } public void testObjBool2() throws Exception { String s = "{\"data\":true}"; T5 r = JSONValue.parse(s, T5.class); assertEquals(true, r.data); } /** * class containing primitive array; */ public static class T1 { private int[] vint; public int[] getVint() { return vint; } public void setVint(int[] vint) { this.vint = vint; } } /** * class containing Map interface; */ public static class T2 { private Map data; public Map getData() { return data; } public void setData(Map data) { this.data = data; } } public static enum ColorEnum { bleu, green, red, yellow } public static class T3 { private Map data; public Map getData() { return data; } public void setData(Map data) { this.data = data; } } public static class T4 { private boolean data; public boolean getData() { return data; } public void setData(boolean data) { this.data = data; } } public static class T5 { private boolean data; public boolean isData() { return data; } public void setData(boolean data) { this.data = data; } } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestMapPrimArrays.java000066400000000000000000000021661255620162700325150ustar00rootroot00000000000000package net.minidev.json.testMapping; import junit.framework.TestCase; import net.minidev.json.JSONValue; public class TestMapPrimArrays extends TestCase { public void testInts() throws Exception { String s = "[1,2,3]"; int[] r = JSONValue.parse(s, int[].class); assertEquals(3, r[2]); } public void testIntss() throws Exception { String s = "[[1],[2],[3,4]]"; int[][] r = JSONValue.parse(s, int[][].class); assertEquals(3, r[2][0]); assertEquals(4, r[2][1]); } public void testLongs() throws Exception { String s = "[1,2,3]"; long[] r = JSONValue.parse(s, long[].class); assertEquals(3, r[2]); } public void testFloat() throws Exception { String s = "[1.2,22.4,3.14]"; float[] r = JSONValue.parse(s, float[].class); assertEquals(3.14F, r[2]); } public void testDouble() throws Exception { String s = "[1.2,22.4,3.14]"; double[] r = JSONValue.parse(s, double[].class); assertEquals(3.14, r[2]); } public void testBooleans() throws Exception { String s = "[true,true,false]"; boolean[] r = JSONValue.parse(s, boolean[].class); assertEquals(true, r[1]); assertEquals(false, r[2]); } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestMapPublic.java000066400000000000000000000035721255620162700316440ustar00rootroot00000000000000package net.minidev.json.testMapping; import java.util.Map; import java.util.TreeMap; import junit.framework.TestCase; import net.minidev.json.JSONValue; public class TestMapPublic extends TestCase { public void testObjInts() throws Exception { String s = "{\"vint\":[1,2,3]}"; T1 r = JSONValue.parse(s, T1.class); assertEquals(3, r.vint[2]); } String MultiTyepJson = "{\"name\":\"B\",\"age\":120,\"cost\":12000,\"flag\":3,\"valid\":true,\"f\":1.2,\"d\":1.5,\"l\":12345678912345}"; public void testObjMixte() throws Exception { T2 r = JSONValue.parse(MultiTyepJson, T2.class); assertEquals("B", r.name); assertEquals(120, r.age); assertEquals(12000, r.cost); assertEquals(3, r.flag); assertEquals(true, r.valid); assertEquals(1.2F, r.f); assertEquals(1.5, r.d); assertEquals(12345678912345L, r.l); } public void testObjMixtePrim() throws Exception { T3 r = JSONValue.parse(MultiTyepJson, T3.class); assertEquals("B", r.name); assertEquals(Short.valueOf((short) 120), r.age); assertEquals(Integer.valueOf(12000), r.cost); assertEquals(Byte.valueOf((byte) 3), r.flag); assertEquals(Boolean.TRUE, r.valid); assertEquals(1.2F, r.f); assertEquals(1.5, r.d); assertEquals(Long.valueOf(12345678912345L), r.l); } public static class T1 { public int[] vint; } public static class T2 { public String name; public short age; public int cost; public byte flag; public boolean valid; public float f; public double d; public long l; } public static class T3 { public String name; public Short age; public Integer cost; public Byte flag; public Boolean valid; public Float f; public Double d; public Long l; } public static class T123 { public T1 t1; public T2 t2; public T3 t3; } public static class T5 { public Map data; } public static class T6 { public TreeMap data; } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestMapPublic2.java000066400000000000000000000014271255620162700317230ustar00rootroot00000000000000package net.minidev.json.testMapping; import java.util.Map; import java.util.TreeMap; import junit.framework.TestCase; import net.minidev.json.JSONValue; public class TestMapPublic2 extends TestCase { String s = "{\"data\":{\"a\":\"b\"}}"; public void testMapPublicInterface() throws Exception { T5 r = JSONValue.parse(s, T5.class); assertEquals(1, r.data.size()); } public void testMapPublicMapClass() throws Exception { T6 r = JSONValue.parse(s, T6.class); assertEquals(1, r.data.size()); } String MultiTyepJson = "{\"name\":\"B\",\"age\":120,\"cost\":12000,\"flag\":3,\"valid\":true,\"f\":1.2,\"d\":1.5,\"l\":12345678912345}"; public static class T5 { public Map data; } public static class T6 { public TreeMap data; } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestSerPrimArrays.java000066400000000000000000000015571255620162700325340ustar00rootroot00000000000000package net.minidev.json.testMapping; import java.text.SimpleDateFormat; import java.util.Date; import junit.framework.TestCase; import net.minidev.json.JSONValue; public class TestSerPrimArrays extends TestCase { SimpleDateFormat sdf; String testDateString; Date testDate; public TestSerPrimArrays() { try { sdf = new SimpleDateFormat("dd/MM/yyyy"); testDateString = "12/01/2010"; testDate = sdf.parse(testDateString); } catch (Exception e) { } } public void testDate() throws Exception { String s = "'" + testDateString + "'"; Date dt = JSONValue.parse(s, Date.class); assertEquals(dt, this.testDate); } public void testDtObj() throws Exception { String s = "{date:'" + testDateString + "'}"; ADate dt = JSONValue.parse(s, ADate.class); assertEquals(dt.date, this.testDate); } public static class ADate { public Date date; } } json-smart-v2-2.2/json-smart/src/test/java/net/minidev/json/testMapping/TestUpdater.java000066400000000000000000000027721255620162700313750ustar00rootroot00000000000000package net.minidev.json.testMapping; import junit.framework.TestCase; import net.minidev.json.JSONValue; import net.minidev.json.testMapping.TestMapPublic.T123; import net.minidev.json.testMapping.TestMapPublic.T1; import net.minidev.json.testMapping.TestMapPublic.T2; import net.minidev.json.testMapping.TestMapPublic.T3; public class TestUpdater extends TestCase { public void testUpdate1() throws Exception { T3 t3 = new T3(); t3.age = 20; t3.f = 1.4f; t3.l = 120000L; String s = "{\"name\":\"text\"}"; T3 t3_1 = JSONValue.parse(s, t3); assertEquals(t3, t3_1); assertEquals("text", t3.name); assertEquals((Long) 120000L, t3.l); } public void testUpdateExistingBeans() throws Exception { T123 t123 = new T123(); T1 t1 = new T1(); T2 t2 = new T2(); T3 t3 = new T3(); t123.t1 = t1; t123.t2 = t2; t123.t3 = t3; String s = "{\"t2\":{\"name\":\"valueT2\"},\"t3\":{\"name\":\"valueT3\"},}"; T123 res = JSONValue.parse(s, t123); assertEquals(res, t123); assertEquals(res.t2, t2); assertEquals(res.t2.name, "valueT2"); assertEquals(res.t3.name, "valueT3"); } public void testUpdateNullBean() throws Exception { T123 t123 = new T123(); T1 t1 = new T1(); T2 t2 = null; T3 t3 = null; t123.t1 = t1; t123.t2 = t2; t123.t3 = t3; String s = "{\"t2\":{\"name\":\"valueT2\"},\"t3\":{\"name\":\"valueT3\"},}"; T123 res = JSONValue.parse(s, t123); assertEquals(res, t123); assertEquals(res.t2.name, "valueT2"); assertEquals(res.t3.name, "valueT3"); } } json-smart-v2-2.2/parent/000077500000000000000000000000001255620162700152765ustar00rootroot00000000000000json-smart-v2-2.2/parent/pom.xml000066400000000000000000000216211255620162700166150ustar00rootroot00000000000000 4.0.0 net.minidev minidev-parent 2.2 Minidev super pom minidev common properties. pom http://www.minidev.net/ Chemouni Uriel http://www.minidev.net/ uriel Uriel Chemouni uchemouni@gmail.com GMT+1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo All files under Apache 2 UTF-8 1.5 1.5 org.apache.maven.plugins maven-source-plugin 2.4 bind-sources jar-no-fork org.apache.maven.plugins maven-compiler-plugin 2.3.2 UTF-8 1.6 1.6 **/.svn/* **/.svn org.apache.maven.plugins maven-resources-plugin 2.5 UTF-8 org.apache.maven.plugins maven-jar-plugin 2.3.1 **/.svn/* **/.svn org.apache.maven.plugins maven-javadoc-plugin 2.10.3 false -Xdoclint:none attach-javadocs jar scm:git:https://github.com/netplex/json-smart-v2.git scm:git:https://github.com/netplex/json-smart-v2.git https://github.com/netplex/json-smart-v2 org.apache.maven.plugins maven-checkstyle-plugin 2.6 config/sun_checks.xml ../accessors-smart ../json-smart ossrh https://oss.sonatype.org/content/repositories/snapshots ossrh https://oss.sonatype.org/service/local/staging/deploy/maven2/ release-sign-artifacts performRelease true 8E322ED0 org.apache.maven.plugins maven-gpg-plugin 1.6 sign-artifacts verify sign org.apache.maven.plugins maven-javadoc-plugin attach-javadocs jar org.apache.maven.plugins maven-release-plugin 2.5.2 forked-path -Psonatype-oss-release false false release deploy include-sources / true src/main/java **/*.java net.minidev json-smart ${project.version} net.minidev accessors-smart 1.1 net.minidev json-smart-mini ${project.version} junit junit 3.8.2