[exo-jcr-commits] exo-jcr SVN: r3246 - in ws/trunk: exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json and 5 other directories.
do-not-reply at jboss.org
do-not-reply at jboss.org
Tue Oct 5 10:59:11 EDT 2010
Author: aparfonov
Date: 2010-10-05 10:59:07 -0400 (Tue, 05 Oct 2010)
New Revision: 3246
Added:
ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonStack.java
ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilder.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonTest.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilderTest.java
ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java
Removed:
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JavaNumericTypeTest.java
ws/trunk/exo.ws.frameworks.json/src/test/resources/MultiDimension.txt
ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java
Modified:
ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/BeanBuilder.java
ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonDefaultHandler.java
ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonGeneratorImpl.java
ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonParserImpl.java
ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonUtils.java
ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonWriterImpl.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/Book.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonGeneratorTest.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonParserTest.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonUtilsTest.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonWriterTest.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/TransferJavaBeanTest.java
ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/groovy/GroovyBeanTest.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/provider/JsonEntityProvider.java
Log:
EXOJCR-989
Modified: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/BeanBuilder.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/BeanBuilder.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/BeanBuilder.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -18,506 +18,27 @@
*/
package org.exoplatform.ws.frameworks.json.impl;
-import org.exoplatform.ws.frameworks.json.impl.JsonUtils.Types;
import org.exoplatform.ws.frameworks.json.value.JsonValue;
-import java.lang.reflect.Array;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.Map;
-
/**
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
* @version $Id: BeanBuilder.java 34417 2009-07-23 14:42:56Z dkatayev $
+ * @deprecated use {@link ObjectBuilder#createObject(Class, JsonValue)} instead
*/
public class BeanBuilder
{
- static final Collection<String> SKIP_METHODS = new HashSet<String>();
-
- static
- {
- // Since we need support for Groovy must skip this.
- // All "Groovy Objects" implements interface groovy.lang.GroovyObject
- // and has method setMetaClass. Not need to process it.
- SKIP_METHODS.add("setMetaClass");
- }
-
/**
- * Create Java Bean from Json Source.
+ * Create Java Bean from JSON Source.
*
* @param clazz the Class of target Object.
- * @param jsonValue the Json representation.
+ * @param jsonValue the JSON representation.
* @return Object.
* @throws Exception if any errors occurs.
*/
- @SuppressWarnings("unchecked")
public Object createObject(Class<?> clazz, JsonValue jsonValue) throws Exception
{
- if (JsonUtils.getType(clazz) == Types.ENUM)
- {
- // Enum is not instantiable via CLass.getInstance().
- // This is used when enum is member of array or collection.
- Class c = clazz;
- return Enum.valueOf(c, jsonValue.getStringValue());
- }
- Object object = clazz.newInstance();
- Method[] methods = clazz.getMethods();
-
- for (Method method : methods)
- {
- String methodName = method.getName();
- Class<?>[] parameterTypes = method.getParameterTypes();
-
- if (!SKIP_METHODS.contains(methodName) && methodName.startsWith("set") && parameterTypes.length == 1
- && methodName.length() > 3)
- {
- Class<?> methodParameterClazz = parameterTypes[0];
- String key = methodName.substring(3);
- // first letter to lower case
- key = (key.length() > 1) ? Character.toLowerCase(key.charAt(0)) + key.substring(1) : key.toLowerCase();
-
- // Bug : WS-53
- if (jsonValue.isNull())
- {
- return null;
- }
-
- if (!jsonValue.isObject())
- {
- throw new JsonException("Unsupported type of jsonValue for parameter of method " + clazz.getName() + "#"
- + method.getName());
- }
-
- JsonValue childJsonValue = jsonValue.getElement(key);
-
- if (childJsonValue == null)
- {
- continue;
- }
-
- // if one of known primitive type or array of primitive type
- if (JsonUtils.isKnownType(methodParameterClazz))
- {
- method.invoke(object, new Object[]{createObjectKnownTypes(methodParameterClazz, childJsonValue)});
- }
- else
- {
- Types type = JsonUtils.getType(methodParameterClazz);
- // other type Collection, Map or Object[].
- if (type != null)
- {
- switch (type)
- {
- case ENUM : {
- Class c = methodParameterClazz;
- Enum<?> en = Enum.valueOf(c, childJsonValue.getStringValue());
- method.invoke(object, new Object[]{en});
- }
- break;
- case ARRAY_OBJECT : {
- Object array = createArray(methodParameterClazz, childJsonValue);
- method.invoke(object, new Object[]{array});
- }
- break;
- case COLLECTION : {
- Type[] genericParameterTypes = method.getGenericParameterTypes();
- Class<?> parameterizedTypeClass = null;
- if (genericParameterTypes.length == 1)
- {
- if (genericParameterTypes[0] instanceof ParameterizedType)
- {
- ParameterizedType parameterizedType = (ParameterizedType)genericParameterTypes[0];
- try
- {
- // Collection can't be parameterized by other Collection,
- // Array, etc.
- parameterizedTypeClass = (Class<?>)parameterizedType.getActualTypeArguments()[0];
- }
- catch (ClassCastException e)
- {
- throw new JsonException("Unsupported parameter in method " + clazz.getName() + "#"
- + method.getName()
- + ". This type of Collection can't be restored from JSON source.\n"
- + "Collection is parameterized by wrong Type: " + parameterizedType + ".");
- }
- }
- else
- {
- throw new JsonException("Unsupported parameter in method " + clazz.getName() + "#"
- + method.getName() + ". Collection is not parameterized. "
- + "Collection<?> is not supported. \nCollection must be parameterized by"
- + " any types, or by JavaBean with 'get' and 'set' methods.");
- }
- }
- Constructor<?> constructor = null;
- if (methodParameterClazz.isInterface()
- || Modifier.isAbstract(methodParameterClazz.getModifiers()))
- {
- try
- {
- constructor =
- ArrayList.class.asSubclass(methodParameterClazz).getConstructor(
- new Class[]{Collection.class});
- }
- catch (Exception e)
- {
- try
- {
- constructor =
- HashSet.class.asSubclass(methodParameterClazz).getConstructor(
- new Class[]{Collection.class});
- }
- catch (Exception e1)
- {
- try
- {
- constructor =
- LinkedList.class.asSubclass(methodParameterClazz).getConstructor(
- new Class[]{Collection.class});
- }
- catch (Exception e2)
- {
- // ignore exception here
- }
- }
- }
- }
- else
- {
- constructor = methodParameterClazz.getConstructor(new Class[]{Collection.class});
- }
- if (constructor == null)
- {
- throw new JsonException("Can't find satisfied constructor for : " + methodParameterClazz
- + ", method : " + clazz.getName() + "#" + method.getName());
- }
-
- ArrayList<Object> sourceCollection = new ArrayList<Object>(childJsonValue.size());
-
- Iterator<JsonValue> values = childJsonValue.getElements();
-
- while (values.hasNext())
- {
- JsonValue v = values.next();
- if (!JsonUtils.isKnownType(parameterizedTypeClass))
- {
- sourceCollection.add(createObject(parameterizedTypeClass, v));
- }
- else
- {
- sourceCollection.add(createObjectKnownTypes(parameterizedTypeClass, v));
- }
- }
-
- constructor.newInstance(sourceCollection);
- method.invoke(object, constructor.newInstance(sourceCollection));
- }
- break;
- case MAP : {
- Type[] genericParameterTypes = method.getGenericParameterTypes();
- Class<?> parameterizedTypeClass = null;
- if (genericParameterTypes.length == 1)
- {
- if (genericParameterTypes[0] instanceof ParameterizedType)
- {
- ParameterizedType parameterizedType = (ParameterizedType)genericParameterTypes[0];
- if (!String.class
- .isAssignableFrom((Class<?>)parameterizedType.getActualTypeArguments()[0]))
- {
- throw new JsonException("Unsupported parameter in method " + clazz.getName() + "#"
- + method.getName() + ". Key of Map must be String.");
- }
- try
- {
- parameterizedTypeClass = (Class<?>)parameterizedType.getActualTypeArguments()[1];
- }
- catch (Exception e)
- {
- throw new JsonException("Unsupported parameter in method " + clazz.getName() + "#"
- + method.getName() + ". This type of Map can't be restored from JSON source.\n"
- + "Map is parameterized by wrong Type: " + parameterizedType + ".");
- }
- }
- else
- {
- throw new JsonException("Unsupported parameter in method " + clazz.getName() + "#"
- + method.getName() + ". Map is not parameterized. "
- + "Map<Sting, ?> is not supported. \nMap must be parameterized by"
- + "String and any types or JavaBean with 'get' and 'set' methods.");
- }
- }
- Constructor<?> constructor = null;
- if (methodParameterClazz.isInterface()
- || Modifier.isAbstract(methodParameterClazz.getModifiers()))
- {
- try
- {
- constructor =
- HashMap.class.asSubclass(methodParameterClazz).getConstructor(new Class[]{Map.class});
- }
- catch (Exception e)
- {
- try
- {
- constructor =
- Hashtable.class.asSubclass(methodParameterClazz).getConstructor(
- new Class[]{Map.class});
- }
- catch (Exception e1)
- {
- try
- {
- constructor =
- LinkedHashMap.class.asSubclass(methodParameterClazz).getConstructor(
- new Class[]{Map.class});
- }
- catch (Exception e2)
- {
- // ignore exception here
- }
- }
- }
- }
- else
- {
- constructor = methodParameterClazz.getConstructor(new Class[]{Map.class});
- }
-
- if (constructor == null)
- {
- throw new JsonException("Can't find satisfied constructor for : " + methodParameterClazz
- + ", method : " + clazz.getName() + "#" + method.getName());
- }
-
- HashMap<String, Object> sourceMap = new HashMap<String, Object>(childJsonValue.size());
-
- Iterator<String> keys = childJsonValue.getKeys();
-
- while (keys.hasNext())
- {
- String k = keys.next();
- JsonValue v = childJsonValue.getElement(k);
- if (!JsonUtils.isKnownType(parameterizedTypeClass))
- {
- sourceMap.put(k, createObject(parameterizedTypeClass, v));
- }
- else
- {
- sourceMap.put(k, createObjectKnownTypes(parameterizedTypeClass, v));
- }
- }
-
- method.invoke(object, constructor.newInstance(sourceMap));
-
- }
- break;
- default :
- // it must never happen!
- throw new JsonException("Can't restore parameter of method : " + clazz.getName() + "#"
- + method.getName() + " from JSON source.");
- }
-
- }
- else
- {
- method.invoke(object, createObject(methodParameterClazz, childJsonValue));
- }
- }
- }
- }
-
- return object;
+ return ObjectBuilder.createObject(clazz, jsonValue);
}
- /**
- * Create array of Java Object from Json Source include multi-dimension
- * array.
- *
- * @param clazz the Class of target Object.
- * @param jsonValue the Json representation.
- * @return Object.
- * @throws Exception if any errors occurs.
- */
- private Object createArray(Class<?> clazz, JsonValue jsonValue) throws Exception
- {
-
- Class<?> componentType = clazz.getComponentType();
- Object array = Array.newInstance(componentType, jsonValue.size());
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
-
- if (componentType.isArray())
- {
- if (JsonUtils.isKnownType(componentType))
- {
- while (values.hasNext())
- {
- JsonValue v = values.next();
- Array.set(array, i++, createObjectKnownTypes(componentType, v));
- }
- }
- else
- {
- while (values.hasNext())
- {
- JsonValue v = values.next();
- Array.set(array, i++, createArray(componentType, v));
- }
- }
- }
- else
- {
- while (values.hasNext())
- {
- JsonValue v = values.next();
- Array.set(array, i++, createObject(componentType, v));
- }
- }
- return array;
- }
-
- /**
- * Create Objects of known types.
- *
- * @param clazz class.
- * @param jsonValue JsonValue , @see {@link JsonValue}
- * @return Object.
- * @throws JsonException if type is unknown.
- */
- private Object createObjectKnownTypes(Class<?> clazz, JsonValue jsonValue) throws JsonException
- {
- Types t = JsonUtils.getType(clazz);
- switch (t)
- {
- case NULL :
- return null;
- case BOOLEAN :
- return jsonValue.getBooleanValue();
- case BYTE :
- return jsonValue.getByteValue();
- case SHORT :
- return jsonValue.getShortValue();
- case INT :
- return jsonValue.getIntValue();
- case LONG :
- return jsonValue.getLongValue();
- case FLOAT :
- return jsonValue.getFloatValue();
- case DOUBLE :
- return jsonValue.getDoubleValue();
- case CHAR :
- // TODO check String length
- return jsonValue.getStringValue().charAt(0);
- case STRING :
- return jsonValue.getStringValue();
- case ARRAY_BOOLEAN : {
- boolean[] params = new boolean[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- while (values.hasNext())
- {
- params[i++] = values.next().getBooleanValue();
- }
- return params;
- }
- case ARRAY_BYTE : {
- byte[] params = new byte[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- while (values.hasNext())
- {
- params[i++] = values.next().getByteValue();
- }
- return params;
- }
- case ARRAY_SHORT : {
- short[] params = new short[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- while (values.hasNext())
- {
- params[i++] = values.next().getShortValue();
- }
- return params;
- }
- case ARRAY_INT : {
- int[] params = new int[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- while (values.hasNext())
- {
- params[i++] = values.next().getIntValue();
- }
- return params;
- }
- case ARRAY_LONG : {
- long[] params = new long[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- while (values.hasNext())
- {
- params[i++] = values.next().getLongValue();
- }
- return params;
- }
- case ARRAY_FLOAT : {
- float[] params = new float[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- while (values.hasNext())
- {
- params[i++] = values.next().getFloatValue();
- }
- return params;
- }
- case ARRAY_DOUBLE : {
- double[] params = new double[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- while (values.hasNext())
- {
- params[i++] = values.next().getDoubleValue();
- }
- return params;
- }
- case ARRAY_CHAR : {
- char[] params = new char[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- // TODO better checking an transformation string to char
- while (values.hasNext())
- {
- params[i++] = values.next().getStringValue().charAt(0);
- }
- return params;
- }
- case ARRAY_STRING : {
- String[] params = new String[jsonValue.size()];
- Iterator<JsonValue> values = jsonValue.getElements();
- int i = 0;
- while (values.hasNext())
- {
- params[i++] = values.next().getStringValue();
- }
- return params;
- }
- default :
- // Nothing to do for other type. Exception will be thrown.
- break;
- }
- throw new JsonException("Unknown type " + clazz.getName());
- }
-
}
Modified: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonDefaultHandler.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonDefaultHandler.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonDefaultHandler.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -28,8 +28,6 @@
import org.exoplatform.ws.frameworks.json.value.impl.ObjectValue;
import org.exoplatform.ws.frameworks.json.value.impl.StringValue;
-import java.util.Stack;
-
/**
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
* @version $Id: JsonDefaultHandler.java 34417 2009-07-23 14:42:56Z dkatayev $
@@ -37,27 +35,19 @@
public class JsonDefaultHandler implements JsonHandler
{
- /**
- * The key.
- */
+ /** The key. */
private String key;
- /**
- * JsonValue which is currently in process.
- */
+ /** JsonValue which is currently in process. */
private JsonValue current;
- /**
- * Stack of JsonValues.
- */
- private Stack<JsonValue> values;
+ /** Stack of JsonValues. */
+ private JsonStack<JsonValue> values;
- /**
- * Constructs new JsonHandler.
- */
+ /** Constructs new JsonHandler. */
public JsonDefaultHandler()
{
- this.values = new Stack<JsonValue>();
+ this.values = new JsonStack<JsonValue>();
}
/**
@@ -66,9 +56,13 @@
public void characters(char[] characters)
{
if (current.isObject())
+ {
current.addElement(key, parseCharacters(characters));
+ }
else if (current.isArray())
+ {
current.addElement(parseCharacters(characters));
+ }
}
/**
@@ -101,10 +95,18 @@
public void startArray()
{
ArrayValue o = new ArrayValue();
- if (current.isObject())
+ if (current == null)
+ {
+ current = o;
+ }
+ else if (current.isObject())
+ {
current.addElement(key, o);
+ }
else if (current.isArray())
+ {
current.addElement(o);
+ }
values.push(current);
current = o;
}
@@ -122,14 +124,28 @@
}
ObjectValue o = new ObjectValue();
if (current.isObject())
+ {
current.addElement(key, o);
+ }
else if (current.isArray())
+ {
current.addElement(o);
+ }
values.push(current);
current = o;
}
/**
+ * Reset JSON events handler and prepare it for next usage.
+ */
+ public void reset()
+ {
+ current = null;
+ key = null;
+ values.clear();
+ }
+
+ /**
* {@inheritDoc}
*/
public JsonValue getJsonObject()
@@ -139,13 +155,13 @@
/**
* Parse characters array dependent of context.
+ *
* @param characters the characters array.
* @return JsonValue.
*/
private JsonValue parseCharacters(char[] characters)
{
String s = new String(characters);
-
if (characters[0] == '"' && characters[characters.length - 1] == '"')
{
return new StringValue(s.substring(1, s.length() - 1));
@@ -232,9 +248,6 @@
}
}
// if can't parse return as string
- /////////////////////////////////////////////
- //TODO may be better generate exception here
- /////////////////////////////////////////////
return new StringValue(s);
}
Modified: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonGeneratorImpl.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonGeneratorImpl.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonGeneratorImpl.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -71,23 +71,7 @@
*/
public JsonValue createJsonArray(Collection<?> collection) throws JsonException
{
- if (collection == null)
- return new NullValue();
-
- JsonValue jsonArray = new ArrayValue();
- for (Object o : collection)
- {
- // If :
- // 1. Known types (primitive, String, array of primitive or String)
- // 2. Array of any object (expect for Java Bean)
- // 3. Collection<?>
- // 4. Map<String, ?>
- if (JsonUtils.getType(o) != null)
- jsonArray.addElement(createJsonValue(o));
- else
- jsonArray.addElement(createJsonObject(o));
- }
- return jsonArray;
+ return createJsonValue(collection);
}
/**
@@ -101,77 +85,20 @@
public JsonValue createJsonArray(Object array) throws JsonException
{
if (array == null)
+ {
return new NullValue();
-
+ }
Types t = JsonUtils.getType(array);
- JsonValue jsonArray = new ArrayValue();
- int length = Array.getLength(array);
- if (t == Types.ARRAY_BOOLEAN)
+ if (t == Types.ARRAY_BOOLEAN || t == Types.ARRAY_BYTE || t == Types.ARRAY_SHORT || t == Types.ARRAY_INT
+ || t == Types.ARRAY_LONG || t == Types.ARRAY_FLOAT || t == Types.ARRAY_DOUBLE || t == Types.ARRAY_CHAR
+ || t == Types.ARRAY_STRING || t == Types.ARRAY_OBJECT)
{
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new BooleanValue(Array.getBoolean(array, i)));
+ return createJsonValue(array);
}
- else if (t == Types.ARRAY_BYTE)
- {
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new LongValue(Array.getByte(array, i)));
- }
- else if (t == Types.ARRAY_SHORT)
- {
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new LongValue(Array.getShort(array, i)));
- }
- else if (t == Types.ARRAY_INT)
- {
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new LongValue(Array.getInt(array, i)));
- }
- else if (t == Types.ARRAY_LONG)
- {
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new LongValue(Array.getLong(array, i)));
- }
- else if (t == Types.ARRAY_FLOAT)
- {
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new DoubleValue(Array.getFloat(array, i)));
- }
- else if (t == Types.ARRAY_DOUBLE)
- {
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new DoubleValue(Array.getDouble(array, i)));
- }
- else if (t == Types.ARRAY_CHAR)
- {
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new StringValue(Character.toString(Array.getChar(array, i))));
- }
- else if (t == Types.ARRAY_STRING)
- {
- for (int i = 0; i < length; i++)
- jsonArray.addElement(new StringValue((String)Array.get(array, i)));
- }
- else if (t == Types.ARRAY_OBJECT)
- {
- for (int i = 0; i < length; i++)
- {
- Object el = Array.get(array, i);
- // If :
- // 1. Known types (primitive, String, array of primitive or String)
- // 2. Array of any object (expect for Java Bean)
- // 3. Collection<?>
- // 4. Map<String, ?>
- if (JsonUtils.getType(el) != null)
- jsonArray.addElement(createJsonValue(el));
- else
- jsonArray.addElement(createJsonObject(el));
- }
- }
else
{
throw new JsonException("Invalid argument, must be array.");
}
- return jsonArray;
}
/**
@@ -181,52 +108,35 @@
* @return JSON representation of map
* @throws JsonException if map can't be transformed in JSON representation
*/
- public JsonValue createJsonObject(Map<String, Object> map) throws JsonException
+ public JsonValue createJsonObjectFromMap(Map<String, ?> map) throws JsonException
{
- if (map == null)
- return new NullValue();
-
- JsonValue jsonObject = new ObjectValue();
- Set<String> keys = map.keySet();
- for (String k : keys)
- {
- Object o = map.get(k);
- // If :
- // 1. Known types (primitive, String, array of primitive or String)
- // 2. Array of any object (expect for Java Bean)
- // 3. Collection<?>
- // 4. Map<String, ?>
- if (JsonUtils.getType(o) != null)
- jsonObject.addElement(k, createJsonValue(o));
- else
- jsonObject.addElement(k, createJsonObject(o));
- }
- return jsonObject;
+ return createJsonValue(map);
}
/**
- * {@inheritDoc}
+ * Create JSON object from specified object. Object must be conform with java
+ * bean structure.
+ *
+ * @param object source object
+ * @return JSON representation of object
+ * @throws JsonException if map can't be transformed in JSON representation
*/
public JsonValue createJsonObject(Object object) throws JsonException
{
- Method[] methods = object.getClass().getMethods();
-
- List<String> transientFields = getTransientFields(object.getClass());
-
+ Class<?> clazz = object.getClass();
+ Method[] methods = clazz.getMethods();
+ Set<String> transientFields = getTransientFields(clazz);
JsonValue jsonRootValue = new ObjectValue();
-
for (Method method : methods)
{
String methodName = method.getName();
-
/*
* Method must be as follow:
- * 1. Name starts from "get" plus at least one character or starts from
- * "is" plus at least one more character and return boolean type
- * 2. Must be without parameters
- * 3. Must not be in list of skipped methods
+ * 1. Name starts from "get" plus at least one character or
+ * starts from "is" plus one more character and return boolean type;
+ * 2. Must be without parameters;
+ * 3. Not be in SKIP_METHODS set.
*/
-
String key = null;
if (!SKIP_METHODS.contains(methodName) && method.getParameterTypes().length == 0)
{
@@ -240,7 +150,6 @@
key = methodName.substring(2);
}
}
-
if (key != null)
{
// First letter of key to lower case.
@@ -252,12 +161,6 @@
{
// Get result of invoke method get...
Object invokeResult = method.invoke(object, new Object[0]);
-
- // If :
- // 1. Known types (primitive, String, array of primitive or String)
- // 2. Array of any object (expect for Java Bean)
- // 3. Collection<?>
- // 4. Map<String, ?>
if (JsonUtils.getType(invokeResult) != null)
{
jsonRootValue.addElement(key, createJsonValue(invokeResult));
@@ -266,15 +169,14 @@
{
jsonRootValue.addElement(key, createJsonObject(invokeResult));
}
-
}
catch (InvocationTargetException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
catch (IllegalAccessException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
}
@@ -292,8 +194,8 @@
@SuppressWarnings("unchecked")
private JsonValue createJsonValue(Object object) throws JsonException
{
- Types t = JsonUtils.getType(object);
- switch (t)
+ Types type = JsonUtils.getType(object);
+ switch (type)
{
case NULL :
return new NullValue();
@@ -413,7 +315,6 @@
jsonArray.addElement(createJsonObject(el));
}
}
-
return jsonArray;
}
case COLLECTION : {
@@ -430,7 +331,6 @@
jsonArray.addElement(createJsonObject(o));
}
}
-
return jsonArray;
}
case MAP :
@@ -449,13 +349,11 @@
jsonObject.addElement(k, createJsonObject(o));
}
}
-
return jsonObject;
default :
// Must not be here!
return null;
}
-
}
/**
@@ -463,18 +361,20 @@
* be not serialized in JSON representation.
*
* @param clazz the class.
- * @return list of fields which must be skiped.
+ * @return set of fields which must be skiped.
*/
- private List<String> getTransientFields(Class<?> clazz)
+ private static Set<String> getTransientFields(Class<?> clazz)
{
- List<String> l = new ArrayList<String>();
+ Set<String> set = new HashSet<String>();
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields)
{
if (Modifier.isTransient(f.getModifiers()))
- l.add(f.getName());
+ {
+ set.add(f.getName());
+ }
}
- return l;
+ return set;
}
}
Modified: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonParserImpl.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonParserImpl.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonParserImpl.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -28,7 +28,6 @@
import java.io.InputStreamReader;
import java.io.PushbackReader;
import java.io.Reader;
-import java.util.Stack;
/**
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
@@ -37,74 +36,71 @@
public class JsonParserImpl implements JsonParser
{
- /**
- * JsonHandler will serve events from parser.
- */
- private JsonHandler jsonHandler;
+ /** JsonHandler will serve events from parser. */
+ private JsonHandler eventHandler;
- /**
- * @see {@link java.io.PushbackReader} .
- */
+ /** Stack of JSON tokens. */
+ private final JsonStack<JsonToken> stack;
+
+ /** @see {@link java.io.PushbackReader}. */
private PushbackReader pushbackReader;
- /**
- * Stack of JSON tokens.
- */
- private Stack<JsonToken> jsonTokens = new Stack<JsonToken>();
-
- /**
- * Default constructor.
- */
public JsonParserImpl()
{
+ stack = new JsonStack<JsonToken>();
}
/**
* {@inheritDoc}
*/
- public void parse(Reader reader, JsonHandler handler) throws JsonException
+ public void parse(Reader reader, JsonHandler eventHandler) throws JsonException
{
- jsonHandler = handler;
- pushbackReader = new PushbackReader(reader);
- try
+ this.pushbackReader = new PushbackReader(reader);
+ this.eventHandler = eventHandler;
+ this.stack.clear();
+
+ char c = 0;
+ while ((c = next()) != 0)
{
- char c = 0;
- while ((c = next()) != 0)
+ if (c == '{')
{
- if (c == '{')
- readObject();
- else
- throw new JsonException("Syntax error. Unexpected '" + c + "'. Must be '{'.");
+ readObject();
}
- if (!jsonTokens.isEmpty())
- throw new JsonException("Syntax error. Missing one or more close bracket(s).");
+ else if (c == '[')
+ {
+ readArray();
+ }
+ else
+ {
+ throw new JsonException("Syntax error. Unexpected '" + c + "'. Must be '{'.");
+ }
}
- catch (Exception e)
+ if (!stack.isEmpty())
{
- throw new JsonException(e);
+ throw new JsonException("Syntax error. Missing one or more close bracket(s).");
}
}
/**
* {@inheritDoc}
*/
- public void parse(InputStream sream, JsonHandler handler) throws JsonException
+ public void parse(InputStream sream, JsonHandler eventHandler) throws JsonException
{
- parse(new InputStreamReader(sream, JsonUtils.DEFAULT_CHARSET), handler);
+ parse(new InputStreamReader(sream, JsonUtils.DEFAULT_CHARSET), eventHandler);
}
/**
* Read JSON object token, it minds all characters from '{' to '}'.
- *
+ *
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private void readObject() throws JsonException
{
char c = 0;
// inform handler about start of object
- jsonHandler.startObject();
- jsonTokens.push(JsonToken.object);
+ eventHandler.startObject();
+ stack.push(JsonToken.object);
for (;;)
{
switch (c = next())
@@ -116,11 +112,12 @@
break;
case '}' :
// inform handler about end of object
- jsonHandler.endObject();
+ eventHandler.endObject();
// check is allowed end of object now
- if (JsonToken.object != jsonTokens.pop())
+ if (JsonToken.object != stack.pop())
+ {
throw new JsonException("Syntax error. Unexpected end of object.");
-
+ }
// check is allowed char after end of json object
switch (c = next())
{
@@ -137,11 +134,13 @@
throw new JsonException("Syntax error. Excpected " + "for ',' or ']' or '}' but found '" + c
+ "'.");
}
- return; // end for(;;)
+ // end for(;;)
+ return;
case '[' :
readArray();
break;
- case ',' : // nothing to do just must not be default is switch
+ case ',' :
+ // nothing to do just must not be default is switch
break;
default :
back(c);
@@ -152,7 +151,9 @@
back(c);
// object/array/value
if (c != '{' && c != '[')
+ {
readValue();
+ }
break;
}
}
@@ -160,16 +161,16 @@
/**
* Read JSON array token, it minds all characters from '[' to ']'.
- *
+ *
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private void readArray() throws JsonException
{
char c = 0;
// inform handler about start of array
- jsonHandler.startArray();
- jsonTokens.push(JsonToken.array);
+ eventHandler.startArray();
+ stack.push(JsonToken.array);
for (;;)
{
switch (c = next())
@@ -178,22 +179,37 @@
throw new JsonException("Syntax error. Unexpected end of array. Array must end by ']'.");
case ']' :
// inform handler about end of array
- jsonHandler.endArray();
+ eventHandler.endArray();
// check is allowed end of array now
- if (JsonToken.array != jsonTokens.pop())
+ if (JsonToken.array != stack.pop())
+ {
throw new JsonException("Syntax error. Unexpected end of array.");
+ }
// check is allowed char after end of json array
-
- c = next(",]}");
- back(c);
- return; // end for(;;)
+ switch (c = next())
+ {
+ // end of stream
+ case 0 :
+ break;
+ case ',' :
+ case ']' :
+ case '}' :
+ back(c);
+ break;
+ default :
+ // must not happen
+ throw new JsonException("Syntax error. Excpected for ',' or ']' or '}' but found '" + c + "'.");
+ }
+ // end for(;;)
+ return;
case '[' :
readArray();
break;
case '{' :
readObject();
break;
- case ',' : // nothing to do just must not be default
+ case ',' :
+ // nothing to do just must not be default
break;
default :
back(c);
@@ -205,28 +221,32 @@
/**
* Read key from stream.
- *
+ *
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private void readKey() throws JsonException
{
char c = next();
if (c != '"')
+ {
throw new JsonException("Syntax error. Key must start from quote, but found '" + c + "'.");
+ }
back(c);
String s = new String(nextString());
// if key as ""
if (s.length() == 2)
+ {
throw new JsonException("Missing key.");
- jsonHandler.key(s.substring(1, s.length() - 1));
+ }
+ eventHandler.key(s.substring(1, s.length() - 1));
}
/**
* Read value from stream.
- *
+ *
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private void readValue() throws JsonException
{
@@ -235,7 +255,7 @@
if (c == '"')
{
// value will be read as string
- jsonHandler.characters(nextString());
+ eventHandler.characters(nextString());
}
else
{
@@ -245,11 +265,13 @@
{
// Bug : WS-66
if (c == 0)
+ {
throw new JsonException("Unexpected end of stream.");
+ }
cw.append(c);
}
back(c);
- jsonHandler.characters(cw.toCharArray());
+ eventHandler.characters(cw.toCharArray());
}
c = next(",]}");
back(c);
@@ -259,10 +281,10 @@
* Get next char from stream, skipping whitespace and comments. Comments: One
* line comment from // to end of line; Multi-line comments from / and * to *
* and /
- *
+ *
* @return the next char.
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private char next() throws JsonException
{
@@ -291,39 +313,41 @@
{
c = pushbackReader.read();
if (c == '/')
+ {
break;
+ }
}
if (c == -1)
{
throw new JsonException("Syntax error. Missing end of comment.");
}
}
-
}
else
{
back((char)c);
return '/';
}
-
}
else if (c == -1 || c > ' ')
+ {
break;
+ }
}
return (c == -1) ? 0 : (char)c;
}
catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
/**
* Get next char from stream.
- *
+ *
* @return the next char.
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private char nextAny() throws JsonException
{
@@ -334,48 +358,55 @@
}
catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
/**
* Get next char from stream. And check is this char equals expected.
- *
+ *
* @param c the expected char.
* @return the next char.
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private char next(char c) throws JsonException
{
char n = next();
if (n != c)
+ {
throw new JsonException("Expected for '" + c + "' but found '" + n + "'.");
+ }
return n;
}
/**
- * Get next char from stream. And check is this char presents in given string.
- *
+ * Get next char from stream. And check is this char presents in given
+ * string.
+ *
* @param s the string.
* @return the next char.
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private char next(String s) throws JsonException
{
char n = next();
// if char present in string
if (s.indexOf(n) >= 0)
+ {
return n;
+ }
// else error
char[] ch = s.toCharArray();
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
int i = 0;
for (char c : ch)
{
if (i > 0)
+ {
sb.append(" or ");
+ }
i++;
sb.append('\'').append(c).append('\'');
}
@@ -384,11 +415,11 @@
/**
* Get next n characters from stream.
- *
+ *
* @param n the number of characters.
* @return the array of characters.
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private char[] next(int n) throws JsonException
{
@@ -397,21 +428,23 @@
{
int i = pushbackReader.read(buff);
if (i == -1)
+ {
throw new JsonException("Unexpected end of stream.");
+ }
return buff;
}
- catch (Exception e)
+ catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
/**
* Get array chars up to given and include it.
- *
+ *
* @return the char array.
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private char[] nextString() throws JsonException
{
@@ -460,7 +493,9 @@
default :
cw.append(c);
if (c == '"')
+ {
return cw.toCharArray();
+ }
break;
}
}
@@ -468,10 +503,10 @@
/**
* Push back given char to stream.
- *
+ *
* @param c the char for pushing back.
* @throws JsonException if JSON document has wrong format or i/o error
- * occurs.
+ * occurs.
*/
private void back(char c) throws JsonException
{
@@ -479,9 +514,9 @@
{
pushbackReader.unread(c);
}
- catch (Exception e)
+ catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
Added: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonStack.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonStack.java (rev 0)
+++ ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonStack.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -0,0 +1,63 @@
+/**
+ * Copyright (C) 2010 eXo Platform SAS.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.exoplatform.ws.frameworks.json.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+class JsonStack<T>
+{
+
+ private final List<T> elements;
+
+ JsonStack()
+ {
+ elements = new ArrayList<T>(16);
+ }
+
+ boolean isEmpty()
+ {
+ return elements.isEmpty();
+ }
+
+ T peek()
+ {
+ return isEmpty() ? null : elements.get(elements.size() - 1);
+ }
+
+ T pop()
+ {
+ return isEmpty() ? null : elements.remove(elements.size() - 1);
+ }
+
+ void push(T token)
+ {
+ elements.add(token);
+ }
+
+ void clear()
+ {
+ elements.clear();
+ }
+}
Property changes on: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonStack.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Modified: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonUtils.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonUtils.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonUtils.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -105,9 +105,7 @@
/** Map. */
MAP,
- /**
- * Enum.
- */
+ /** Enum. */
ENUM
}
@@ -179,7 +177,7 @@
/**
* Transform Java String to JSON string.
- *
+ *
* @param string source String.
* @return result.
*/
@@ -240,7 +238,7 @@
* <li>String</li>
* <li>Array of T where T satisfies 2 or 3 or 4</>
* </ol>
- *
+ *
* @param o Object
* @return <code>true</code> if Object has one of described above type,
* <code>false</code> otherwise
@@ -258,7 +256,7 @@
* <li>String</li>
* <li>Array of T where T satisfies 1 or 2 or 3</>
* </ol>
- *
+ *
* @param clazz class.
* @return <code>true</code> if class object represent one of described
* above, <code>false</code> otherwise
@@ -277,11 +275,12 @@
* <li>Map<String, ?></li>
* </ol>
* then <code>null</null> will be returned
- *
+ *
* @param o Object.
* @return {@link Types} or <code>null</code> (see above)
* @see {@link KNOWN_TYPES}.
*/
+ @SuppressWarnings("unchecked")
public static Types getType(Object o)
{
if (o == null)
@@ -309,7 +308,7 @@
* <li>Map</li>
* </ol>
* then <code>null</null> will be returned
- *
+ *
* @param o Object.
* @return {@link Types} or <code>null</code> (see above)
* @see {@link KNOWN_TYPES}.
Modified: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonWriterImpl.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonWriterImpl.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/JsonWriterImpl.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -26,7 +26,6 @@
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
-import java.util.Stack;
/**
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
@@ -35,37 +34,278 @@
public class JsonWriterImpl implements JsonWriter
{
- /**
- * Stack for control position in document.
- */
- private final Stack<JsonToken> jsonTokens = new Stack<JsonToken>();
+// /**
+// * Stack for control position in document.
+// */
+// private final Stack<JsonToken> jsonTokens = new Stack<JsonToken>();
+//
+// /**
+// * Writer.
+// */
+// private final Writer writer;
+//
+// /**
+// * Indicate is current value is the first, if not before value must be written
+// * comma.
+// */
+// private boolean commaFirst = false;
+//
+// /**
+// * Constructs JsonWriter.
+// *
+// * @param writer Writer.
+// */
+// public JsonWriterImpl(Writer writer)
+// {
+// this.writer = writer;
+// }
+//
+// /**
+// * Constructs JsonWriter.
+// *
+// * @param out OutputStream.
+// * @throws UnsupportedEncodingException
+// */
+// public JsonWriterImpl(OutputStream out)
+// {
+// this(new OutputStreamWriter(out, JsonUtils.DEFAULT_CHARSET));
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeStartObject() throws JsonException
+// {
+// if (!jsonTokens.isEmpty())
+// {
+// // Object can be stated after key with followed ':' or as array item.
+// if (jsonTokens.peek() != JsonToken.key && jsonTokens.peek() != JsonToken.array)
+// throw new JsonException("Syntax error. Unexpected element '{'.");
+// }
+// try
+// {
+// if (commaFirst) // needed ',' before
+// writer.write(',');
+// writer.write('{');
+// // if at the top of stack is 'key' then remove it.
+// if (!jsonTokens.isEmpty() && jsonTokens.peek() == JsonToken.key)
+// jsonTokens.pop();
+// jsonTokens.push(JsonToken.object); // remember new object opened
+// commaFirst = false;
+// }
+// catch (IOException e)
+// {
+// throw new JsonException(e);
+// }
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeEndObject() throws JsonException
+// {
+// try
+// {
+// if (jsonTokens.pop() != JsonToken.object) // wrong JSON structure.
+// throw new JsonException("Sysntax error. Unexpected element '}'.");
+// writer.write('}');
+// commaFirst = true;
+// }
+// catch (IOException e)
+// {
+// throw new JsonException(e);
+// }
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeStartArray() throws JsonException
+// {
+// if (jsonTokens.isEmpty() || (jsonTokens.peek() != JsonToken.key && jsonTokens.peek() != JsonToken.array))
+// throw new JsonException("Sysntax error. Unexpected element '['..");
+// try
+// {
+// if (commaFirst) // needed ',' before
+// writer.write(',');
+// writer.write('[');
+// if (jsonTokens.peek() == JsonToken.key)
+// // if at the top of stack is 'key' then remove it.
+// jsonTokens.pop();
+// jsonTokens.push(JsonToken.array); // remember new array opened
+// commaFirst = false;
+// }
+// catch (IOException e)
+// {
+// throw new JsonException(e);
+// }
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeEndArray() throws JsonException
+// {
+// try
+// {
+// if (jsonTokens.pop() != JsonToken.array) // wrong JSON structure
+// throw new JsonException("Sysntax error. Unexpected element ']'.");
+// writer.write(']');
+// commaFirst = true;
+// }
+// catch (IOException e)
+// {
+// throw new JsonException(e);
+// }
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeKey(String key) throws JsonException
+// {
+// if (key == null)
+// throw new JsonException("Key is null.");
+// if (jsonTokens.isEmpty() || jsonTokens.peek() != JsonToken.object)
+// throw new JsonException("Sysntax error. Unexpected characters '" + key + "'." + jsonTokens);
+// try
+// {
+// if (commaFirst)
+// writer.write(',');
+// // create JSON representation for given string.
+// writer.write(JsonUtils.getJsonString(key));
+// writer.write(':');
+// commaFirst = false;
+// jsonTokens.push(JsonToken.key);
+// }
+// catch (IOException e)
+// {
+// throw new JsonException(e);
+// }
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeString(String value) throws JsonException
+// {
+// write(JsonUtils.getJsonString(value));
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeValue(long value) throws JsonException
+// {
+// write(Long.toString(value));
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeValue(double value) throws JsonException
+// {
+// write(Double.toString(value));
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeValue(boolean value) throws JsonException
+// {
+// write(Boolean.toString(value));
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void writeNull() throws JsonException
+// {
+// write("null");
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void flush() throws JsonException
+// {
+// try
+// {
+// writer.flush();
+// }
+// catch (IOException e)
+// {
+// new JsonException(e);
+// }
+// }
+//
+// /**
+// * {@inheritDoc}
+// */
+// public void close() throws JsonException
+// {
+// try
+// {
+// writer.close();
+// }
+// catch (IOException e)
+// {
+// new JsonException(e);
+// }
+// }
+//
+// /**
+// * Write single String.
+// *
+// * @param value String.
+// * @throws JsonException if any errors occurs.
+// */
+// private void write(String value) throws JsonException
+// {
+// try
+// {
+// if (jsonTokens.isEmpty() || (jsonTokens.peek() != JsonToken.key && jsonTokens.peek() != JsonToken.array))
+// throw new JsonException("Sysntax error. Unexpected characters '" + value + "'.");
+// if (commaFirst)
+// writer.write(',');
+// writer.write(value);
+// commaFirst = true;
+// if (jsonTokens.peek() == JsonToken.key)
+// jsonTokens.pop();
+// }
+// catch (IOException e)
+// {
+// throw new JsonException(e);
+// }
+// }
- /**
- * Writer.
- */
+
+ /** Stack for control position in document. */
+ private final JsonStack<JsonToken> stack;
+
+ /** Writer. */
private final Writer writer;
- /**
- * Indicate is current value is the first, if not before value must be written
- * comma.
- */
- private boolean commaFirst = false;
+ /** Indicate is comma must be written before next object or value. */
+ private boolean commaFirst;
/**
* Constructs JsonWriter.
- *
+ *
* @param writer Writer.
*/
public JsonWriterImpl(Writer writer)
{
this.writer = writer;
+ this.stack = new JsonStack<JsonToken>();
+ this.commaFirst = false;
}
/**
* Constructs JsonWriter.
- *
+ *
* @param out OutputStream.
- * @throws UnsupportedEncodingException
+ * @throws UnsupportedEncodingException
*/
public JsonWriterImpl(OutputStream out)
{
@@ -77,26 +317,32 @@
*/
public void writeStartObject() throws JsonException
{
- if (!jsonTokens.isEmpty())
+ JsonToken token = stack.peek();
+ // Object can be stated after key with followed ':' or as array item.
+ if (token != null && token != JsonToken.key && token != JsonToken.array)
{
- // Object can be stated after key with followed ':' or as array item.
- if (jsonTokens.peek() != JsonToken.key && jsonTokens.peek() != JsonToken.array)
- throw new JsonException("Syntax error. Unexpected element '{'.");
+ throw new JsonException("Syntax error. Unexpected element '{'.");
}
try
{
- if (commaFirst) // needed ',' before
+ if (commaFirst)
+ {
+ // needed ',' before
writer.write(',');
+ }
writer.write('{');
// if at the top of stack is 'key' then remove it.
- if (!jsonTokens.isEmpty() && jsonTokens.peek() == JsonToken.key)
- jsonTokens.pop();
- jsonTokens.push(JsonToken.object); // remember new object opened
+ if (token == JsonToken.key)
+ {
+ stack.pop();
+ }
+ // remember new object opened
+ stack.push(JsonToken.object);
commaFirst = false;
}
catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
@@ -107,14 +353,19 @@
{
try
{
- if (jsonTokens.pop() != JsonToken.object) // wrong JSON structure.
+ JsonToken token = stack.pop();
+ if (token != JsonToken.object)
+ {
+ System.out.println(token);
+ // wrong JSON structure.
throw new JsonException("Sysntax error. Unexpected element '}'.");
+ }
writer.write('}');
commaFirst = true;
}
catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
@@ -123,22 +374,32 @@
*/
public void writeStartArray() throws JsonException
{
- if (jsonTokens.isEmpty() || (jsonTokens.peek() != JsonToken.key && jsonTokens.peek() != JsonToken.array))
- throw new JsonException("Sysntax error. Unexpected element '['..");
+ JsonToken token = stack.peek();
+ //if (token != JsonToken.key && token != JsonToken.array)
+ if (token != null && token != JsonToken.key && token != JsonToken.array)
+ {
+ throw new JsonException("Sysntax error. Unexpected element '['.");
+ }
try
{
- if (commaFirst) // needed ',' before
+ if (commaFirst)
+ {
+ // needed ',' before
writer.write(',');
+ }
writer.write('[');
- if (jsonTokens.peek() == JsonToken.key)
+ if (token == JsonToken.key)
+ {
// if at the top of stack is 'key' then remove it.
- jsonTokens.pop();
- jsonTokens.push(JsonToken.array); // remember new array opened
+ stack.pop();
+ }
+ // remember new array opened
+ stack.push(JsonToken.array);
commaFirst = false;
}
catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
@@ -147,16 +408,20 @@
*/
public void writeEndArray() throws JsonException
{
+ JsonToken token = stack.pop();
try
{
- if (jsonTokens.pop() != JsonToken.array) // wrong JSON structure
+ if (token != JsonToken.array)
+ {
+ // wrong JSON structure
throw new JsonException("Sysntax error. Unexpected element ']'.");
+ }
writer.write(']');
commaFirst = true;
}
catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
@@ -166,22 +431,30 @@
public void writeKey(String key) throws JsonException
{
if (key == null)
+ {
throw new JsonException("Key is null.");
- if (jsonTokens.isEmpty() || jsonTokens.peek() != JsonToken.object)
- throw new JsonException("Sysntax error. Unexpected characters '" + key + "'." + jsonTokens);
+ }
+
+ JsonToken token = stack.peek();
+ if (token != JsonToken.object)
+ {
+ throw new JsonException("Sysntax error. Unexpected characters '" + key + "'.");
+ }
try
{
if (commaFirst)
+ {
writer.write(',');
+ }
// create JSON representation for given string.
writer.write(JsonUtils.getJsonString(key));
writer.write(':');
commaFirst = false;
- jsonTokens.push(JsonToken.key);
+ stack.push(JsonToken.key);
}
catch (IOException e)
{
- throw new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
@@ -226,57 +499,66 @@
}
/**
- * {@inheritDoc}
+ * Write single String.
+ *
+ * @param value String.
+ * @throws JsonException if any errors occurs.
*/
- public void flush() throws JsonException
+ private void write(String value) throws JsonException
{
+ JsonToken token = stack.peek();
try
{
- writer.flush();
+ if (token != JsonToken.key && token != JsonToken.array)
+ {
+ throw new JsonException("Sysntax error. Unexpected characters '" + value + "'.");
+ }
+ if (commaFirst)
+ {
+ writer.write(',');
+ }
+ writer.write(value);
+ commaFirst = true;
+ if (token == JsonToken.key)
+ {
+ // if at the top of stack is 'key' then remove it.
+ stack.pop();
+ }
}
catch (IOException e)
{
- new JsonException(e);
+ throw new JsonException(e.getMessage(), e);
}
}
/**
* {@inheritDoc}
*/
- public void close() throws JsonException
+ public void flush() throws JsonException
{
try
{
- writer.close();
+ writer.flush();
}
catch (IOException e)
{
- new JsonException(e);
+ new JsonException(e.getMessage(), e);
}
}
/**
- * Write single String.
- *
- * @param value String.
- * @throws JsonException if any errors occurs.
+ * {@inheritDoc}
*/
- private void write(String value) throws JsonException
+ public void close() throws JsonException
{
try
{
- if (jsonTokens.isEmpty() || (jsonTokens.peek() != JsonToken.key && jsonTokens.peek() != JsonToken.array))
- throw new JsonException("Sysntax error. Unexpected characters '" + value + "'.");
- if (commaFirst)
- writer.write(',');
- writer.write(value);
- commaFirst = true;
- if (jsonTokens.peek() == JsonToken.key)
- jsonTokens.pop();
+ writer.close();
}
catch (IOException e)
{
- throw new JsonException(e);
+ new JsonException(e.getMessage(), e);
}
}
+
}
Added: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilder.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilder.java (rev 0)
+++ ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilder.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -0,0 +1,586 @@
+/*
+ * Copyright (C) 2009 eXo Platform SAS.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.exoplatform.ws.frameworks.json.impl;
+
+import org.exoplatform.ws.frameworks.json.impl.JsonUtils.Types;
+import org.exoplatform.ws.frameworks.json.value.JsonValue;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.Map;
+
+/**
+ * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+public class ObjectBuilder
+{
+ static final Collection<String> SKIP_METHODS = new HashSet<String>();
+ static
+ {
+ // Since we need support for Groovy must skip this.
+ // All "Groovy Objects" implements interface groovy.lang.GroovyObject
+ // and has method setMetaClass. Not need to process it.
+ SKIP_METHODS.add("setMetaClass");
+ }
+
+ /**
+ * Create array of Java Object from JSON source include multi-dimension
+ * array.
+ *
+ * @param clazz the Class of target Object.
+ * @param jsonArray the JSON representation of array
+ * @return result array
+ * @throws JsonException if any errors occurs
+ */
+ public static Object createArray(Class<?> clazz, JsonValue jsonArray) throws JsonException
+ {
+ Object array = null;
+ if (jsonArray != null && !jsonArray.isNull())
+ {
+ Class<?> componentType = clazz.getComponentType();
+ array = Array.newInstance(componentType, jsonArray.size());
+ Iterator<JsonValue> values = jsonArray.getElements();
+ int i = 0;
+
+ if (componentType.isArray())
+ {
+ if (JsonUtils.isKnownType(componentType))
+ {
+ while (values.hasNext())
+ {
+ JsonValue v = values.next();
+ Array.set(array, i++, createObjectKnownTypes(componentType, v));
+ }
+ }
+ else
+ {
+ while (values.hasNext())
+ {
+ JsonValue v = values.next();
+ Array.set(array, i++, createArray(componentType, v));
+ }
+ }
+ }
+ else
+ {
+ if (JsonUtils.isKnownType(componentType))
+ {
+ while (values.hasNext())
+ {
+ JsonValue v = values.next();
+ Array.set(array, i++, createObjectKnownTypes(componentType, v));
+ }
+ }
+ else
+ {
+ while (values.hasNext())
+ {
+ JsonValue v = values.next();
+ Array.set(array, i++, createObject(componentType, v));
+ }
+ }
+ }
+ }
+ return array;
+ }
+
+ /**
+ * Create instance of <code>collectionClass</code> from JSON representation.
+ * If <code>collectionClass</code> is interface then appropriate
+ * implementation of interface will be returned.
+ *
+ * @param collectionClass collection type
+ * @param genericType generic type of collection
+ * @param jsonArray the JSON representation of collection
+ * @return result collection
+ * @throws JsonException if any errors occurs
+ */
+ public static <T extends Collection<?>> T createCollection(Class<T> collectionClass, Type genericType,
+ JsonValue jsonArray) throws JsonException
+ {
+ T collection = null;
+ if (jsonArray != null && !jsonArray.isNull())
+ {
+ Class<?> actualType = null;
+ if (genericType instanceof ParameterizedType)
+ {
+ // Collection can't be parameterized by other Collection, Array, etc.
+ ParameterizedType parameterizedType = (ParameterizedType)genericType;
+ try
+ {
+ actualType = (Class<?>)parameterizedType.getActualTypeArguments()[0];
+ }
+ catch (ClassCastException e)
+ {
+ throw new JsonException("This type of Collection can't be restored from JSON source. "
+ + "\nCollection is parameterized by wrong Type: " + parameterizedType + ".");
+ }
+ }
+ else
+ {
+ throw new JsonException("Collection is not parameterized. Collection<?> is not supported. "
+ + "\nCollection must be parameterized by any types, or by JavaBean with 'get' and 'set' methods.");
+ }
+
+ Constructor<? extends T> constructor = null;
+ if (collectionClass.isInterface() || Modifier.isAbstract(collectionClass.getModifiers()))
+ {
+ try
+ {
+ constructor = ArrayList.class.asSubclass(collectionClass).getConstructor(new Class[]{Collection.class});
+ }
+ catch (Exception e)
+ {
+ try
+ {
+ constructor = HashSet.class.asSubclass(collectionClass).getConstructor(new Class[]{Collection.class});
+ }
+ catch (Exception e1)
+ {
+ try
+ {
+ constructor =
+ LinkedList.class.asSubclass(collectionClass).getConstructor(new Class[]{Collection.class});
+ }
+ catch (Exception e2)
+ {
+ // ignore exception here
+ }
+ }
+ }
+ }
+ else
+ {
+ try
+ {
+ constructor = collectionClass.getConstructor(new Class[]{Collection.class});
+ }
+ catch (Exception e)
+ {
+ throw new JsonException(e.getMessage(), e);
+ }
+ }
+
+ if (constructor == null)
+ {
+ throw new JsonException("Can't find satisfied constructor for : " + collectionClass);
+ }
+
+ ArrayList<Object> sourceCollection = new ArrayList<Object>(jsonArray.size());
+ Iterator<JsonValue> values = jsonArray.getElements();
+ while (values.hasNext())
+ {
+ JsonValue v = values.next();
+ if (!JsonUtils.isKnownType(actualType))
+ {
+ sourceCollection.add(createObject(actualType, v));
+ }
+ else
+ {
+ sourceCollection.add(createObjectKnownTypes(actualType, v));
+ }
+ }
+ try
+ {
+ collection = constructor.newInstance(sourceCollection);
+ }
+ catch (Exception e)
+ {
+ throw new JsonException(e.getMessage(), e);
+ }
+ }
+ return collection;
+ }
+
+ /**
+ * Create instance of <code>mapClass</code> from JSON representation. If
+ * <code>mapClass</code> is interface then appropriate implementation of
+ * interface will be returned.
+ *
+ * @param mapClass map type
+ * @param genericType actual type of map
+ * @param jsonObject source JSON object
+ * @return map
+ * @throws JsonException if any errors occurs
+ */
+ public static <T extends Map<String, ?>> T createObject(Class<T> mapClass, Type genericType, JsonValue jsonObject)
+ throws JsonException
+ {
+ T map = null;
+ if (jsonObject != null && !jsonObject.isNull())
+ {
+ Class<?> valueActualType = null;
+ if (genericType instanceof ParameterizedType)
+ {
+ ParameterizedType parameterizedType = (ParameterizedType)genericType;
+ if (!String.class.isAssignableFrom((Class<?>)parameterizedType.getActualTypeArguments()[0]))
+ {
+ throw new JsonException("Key of Map must be String. ");
+ }
+ try
+ {
+ valueActualType = (Class<?>)parameterizedType.getActualTypeArguments()[1];
+ }
+ catch (ClassCastException e)
+ {
+ throw new JsonException("This type of Map can't be restored from JSON source."
+ + "\nMap is parameterized by wrong Type: " + parameterizedType + ".");
+ }
+ }
+ else
+ {
+ throw new JsonException("Map is not parameterized. Map<Sting, ?> is not supported."
+ + "\nMap must be parameterized by String and any types or JavaBean with 'get' and 'set' methods.");
+ }
+ Constructor<? extends T> constructor = null;
+ if (mapClass.isInterface() || Modifier.isAbstract(mapClass.getModifiers()))
+ {
+ try
+ {
+ constructor = HashMap.class.asSubclass(mapClass).getConstructor(new Class[]{Map.class});
+ }
+ catch (Exception e)
+ {
+ try
+ {
+ constructor = Hashtable.class.asSubclass(mapClass).getConstructor(new Class[]{Map.class});
+ }
+ catch (Exception e1)
+ {
+ try
+ {
+ constructor = LinkedHashMap.class.asSubclass(mapClass).getConstructor(new Class[]{Map.class});
+ }
+ catch (Exception e2)
+ {
+ // ignore exception here
+ }
+ }
+ }
+ }
+ else
+ {
+ try
+ {
+ constructor = mapClass.getConstructor(new Class[]{Map.class});
+ }
+ catch (Exception e)
+ {
+ throw new JsonException(e.getMessage(), e);
+ }
+ }
+
+ if (constructor == null)
+ {
+ throw new JsonException("Can't find satisfied constructor for : " + mapClass);
+ }
+
+ HashMap<String, Object> sourceMap = new HashMap<String, Object>(jsonObject.size());
+ Iterator<String> keys = jsonObject.getKeys();
+ while (keys.hasNext())
+ {
+ String k = keys.next();
+ JsonValue v = jsonObject.getElement(k);
+ if (!JsonUtils.isKnownType(valueActualType))
+ {
+ sourceMap.put(k, createObject(valueActualType, v));
+ }
+ else
+ {
+ sourceMap.put(k, createObjectKnownTypes(valueActualType, v));
+ }
+ }
+ try
+ {
+ map = constructor.newInstance(sourceMap);
+ }
+ catch (Exception e)
+ {
+ throw new JsonException(e.getMessage(), e);
+ }
+ }
+ return map;
+ }
+
+ /**
+ * Create Java Bean from Json Source.
+ *
+ * @param clazz the Class of target Object.
+ * @param jsonValue the Json representation.
+ * @return Object.
+ * @throws JsonException if any errors occurs.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T createObject(Class<T> clazz, JsonValue jsonValue) throws JsonException
+ {
+ if (jsonValue == null || jsonValue.isNull())
+ {
+ return null;
+ }
+
+ Types type = JsonUtils.getType(clazz);
+ if (type == Types.ENUM)
+ {
+ // Enum is not instantiable via CLass.getInstance().
+ // This is used when enum is member of array or collection.
+ Class c = clazz;
+ return (T)Enum.valueOf(c, jsonValue.getStringValue());
+ }
+
+ if (!jsonValue.isObject())
+ {
+ throw new JsonException("Unsupported type of jsonValue. ");
+ }
+
+ T object = null;
+ try
+ {
+ object = clazz.newInstance();
+ }
+ catch (Exception e)
+ {
+ throw new JsonException("Unable instantiate object. " + e.getMessage(), e);
+ }
+
+ Method[] methods = clazz.getMethods();
+
+ for (Method method : methods)
+ {
+ String methodName = method.getName();
+ Class<?>[] parameterTypes = method.getParameterTypes();
+ // 3 is length of prefix 'set'
+ if (!SKIP_METHODS.contains(methodName) && methodName.startsWith("set") && parameterTypes.length == 1
+ && methodName.length() > 3)
+ {
+ Class<?> methodParameterClass = parameterTypes[0];
+ // 3 is length of prefix 'set'
+ String key = methodName.substring(3);
+ // first letter to lower case
+ key = (key.length() > 1) ? Character.toLowerCase(key.charAt(0)) + key.substring(1) : key.toLowerCase();
+
+ JsonValue childJsonValue = jsonValue.getElement(key);
+ if (childJsonValue == null)
+ {
+ continue;
+ }
+ // if one of known primitive type or array of primitive type
+ try
+ {
+
+ if (JsonUtils.isKnownType(methodParameterClass))
+ {
+ method.invoke(object, new Object[]{createObjectKnownTypes(methodParameterClass, childJsonValue)});
+ }
+ else
+ {
+ Types parameterType = JsonUtils.getType(methodParameterClass);
+ // other type Collection, Map or Object[].
+ if (parameterType != null)
+ {
+ if (parameterType == Types.ENUM)
+ {
+ Class c = methodParameterClass;
+ Enum<?> en = Enum.valueOf(c, childJsonValue.getStringValue());
+ method.invoke(object, new Object[]{en});
+ }
+ else if (parameterType == Types.ARRAY_OBJECT)
+ {
+ Object array = createArray(methodParameterClass, childJsonValue);
+ method.invoke(object, new Object[]{array});
+ }
+ else if (parameterType == Types.COLLECTION)
+ {
+ Class c = methodParameterClass;
+ method
+ .invoke(object, createCollection(c, method.getGenericParameterTypes()[0], childJsonValue));
+ }
+ else if (parameterType == Types.MAP)
+ {
+ Class c = methodParameterClass;
+ method.invoke(object, createObject(c, method.getGenericParameterTypes()[0], childJsonValue));
+ }
+ else
+ {
+ // it must never happen!
+ throw new JsonException("Can't restore parameter of method : " + clazz.getName() + "#"
+ + method.getName() + " from JSON source.");
+ }
+ }
+ else
+ {
+ method.invoke(object, createObject(methodParameterClass, childJsonValue));
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ throw new JsonException("Unable restore parameter via method " + clazz.getName() + "#"
+ + method.getName() + ". " + e.getMessage(), e);
+ }
+ }
+ }
+ return object;
+ }
+
+ /**
+ * Create Objects of known types.
+ *
+ * @param clazz class.
+ * @param jsonValue JsonValue , @see {@link JsonValue}
+ * @return Object.
+ * @throws JsonException if type is unknown.
+ */
+ private static Object createObjectKnownTypes(Class<?> clazz, JsonValue jsonValue) throws JsonException
+ {
+ Types t = JsonUtils.getType(clazz);
+ switch (t)
+ {
+ case NULL :
+ return null;
+ case BOOLEAN :
+ return jsonValue.getBooleanValue();
+ case BYTE :
+ return jsonValue.getByteValue();
+ case SHORT :
+ return jsonValue.getShortValue();
+ case INT :
+ return jsonValue.getIntValue();
+ case LONG :
+ return jsonValue.getLongValue();
+ case FLOAT :
+ return jsonValue.getFloatValue();
+ case DOUBLE :
+ return jsonValue.getDoubleValue();
+ case CHAR :
+ // TODO check String length
+ return jsonValue.getStringValue().charAt(0);
+ case STRING :
+ return jsonValue.getStringValue();
+ case ARRAY_BOOLEAN : {
+ boolean[] params = new boolean[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getBooleanValue();
+ }
+ return params;
+ }
+ case ARRAY_BYTE : {
+ byte[] params = new byte[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getByteValue();
+ }
+ return params;
+ }
+ case ARRAY_SHORT : {
+ short[] params = new short[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getShortValue();
+ }
+ return params;
+ }
+ case ARRAY_INT : {
+ int[] params = new int[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getIntValue();
+ }
+ return params;
+ }
+ case ARRAY_LONG : {
+ long[] params = new long[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getLongValue();
+ }
+ return params;
+ }
+ case ARRAY_FLOAT : {
+ float[] params = new float[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getFloatValue();
+ }
+ return params;
+ }
+ case ARRAY_DOUBLE : {
+ double[] params = new double[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getDoubleValue();
+ }
+ return params;
+ }
+ case ARRAY_CHAR : {
+ char[] params = new char[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ // TODO better checking an transformation string to char
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getStringValue().charAt(0);
+ }
+ return params;
+ }
+ case ARRAY_STRING : {
+ String[] params = new String[jsonValue.size()];
+ Iterator<JsonValue> values = jsonValue.getElements();
+ int i = 0;
+ while (values.hasNext())
+ {
+ params[i++] = values.next().getStringValue();
+ }
+ return params;
+ }
+ default :
+ // Nothing to do for other type. Exception will be thrown.
+ break;
+ }
+ throw new JsonException("Unknown type " + clazz.getName());
+ }
+
+}
Property changes on: ws/trunk/exo.ws.frameworks.json/src/main/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilder.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Modified: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/Book.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/Book.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/Book.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -20,7 +20,7 @@
/**
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
- * @version $Id: Book.java 34417 2009-07-23 14:42:56Z dkatayev $
+ * @version $Id: Book.java 45 2010-10-05 06:51:11Z andrew00x $
*/
public class Book
{
@@ -135,10 +135,33 @@
return sb.toString();
}
- public boolean equals(Book book)
+ public int hashCode()
{
- return book.getAuthor().equals(author) && book.getTitle().equals(title) && book.getIsdn() == isdn
- && book.getPages() == pages && book.getPrice() == price && book.isAvailability() == availability
- && book.getDelivery() == delivery;
+ int hash = 8;
+ hash = hash * 31 + (author != null ? author.hashCode() : 0);
+ hash = hash * 31 + (title != null ? title.hashCode() : 0);
+ hash = (int)(hash * 31 + isdn);
+ hash = hash * 31 + pages;
+ hash = (int)(hash * 31 + Double.doubleToLongBits(pages));
+ hash = (int)(hash * 31 + Double.doubleToLongBits(pages));
+ hash = hash + (availability ? 1 : 0);
+ hash = hash + (delivery ? 1 : 0);
+ return hash;
}
+
+ public boolean equals(Object other)
+ {
+ if (other == null)
+ return false;
+ if (other.getClass() != getClass())
+ return false;
+ Book book = (Book)other;
+ return (author != null && author.equals(book.getAuthor())) //
+ && (title != null && title.equals(book.getTitle())) //
+ && (isdn == book.getIsdn()) //
+ && (pages == book.getPages()) //
+ && (price == book.getPrice()) //
+ && (availability == book.isAvailability()) //
+ && (delivery == book.getDelivery());
+ }
}
Deleted: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JavaNumericTypeTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JavaNumericTypeTest.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JavaNumericTypeTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2009 eXo Platform SAS.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.exoplatform.ws.frameworks.json.impl;
-
-import junit.framework.TestCase;
-
-import org.exoplatform.ws.frameworks.json.JsonHandler;
-import org.exoplatform.ws.frameworks.json.value.JsonValue;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStreamReader;
-import java.util.Iterator;
-
-/**
- * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
- * @version $Id: JavaNumericTypeTest.java 34417 2009-07-23 14:42:56Z dkatayev $
- */
-public class JavaNumericTypeTest extends TestCase
-{
-
- @Override
- protected void setUp() throws Exception
- {
- super.setUp();
- }
-
- public void testLong() throws Exception
- {
- JsonParserImpl jsonParser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- String jsonString =
- "{" + "\"long\":[" + "1, 0xAA, 077, 123, 32765, 77787, 123456789," + "0x123456, 0123456, -2387648, -123456789"
- + "]" + "}";
-
- jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), jsonHandler);
- JsonValue jv = jsonHandler.getJsonObject();
- assertTrue(jv.getElement("long").isArray());
- Iterator<JsonValue> values = jv.getElement("long").getElements();
- int i = 0;
- while (values.hasNext())
- {
- JsonValue v = values.next();
- assertTrue(v.isNumeric());
- assertTrue(v.isLong());
- assertFalse(v.isDouble());
- if (i == 0)
- assertEquals(1L, v.getLongValue());
- if (i == 3)
- assertEquals(123L, v.getLongValue());
- if (i == 6)
- assertEquals(123456789L, v.getLongValue());
- i++;
- }
- }
-
- public void testDouble() throws Exception
- {
- JsonParserImpl jsonParser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- String jsonString =
- "{" + "\"double\":[" + "1.0, 0.0006382746, 111111.2222222, 9999999999999.9999999999999,"
- + "9827394873249.8, 1.23456789E8, 123456.789E8, 3215478352478651238.0,"
- + "982.8, 0.00000000000023456789E8, 1.789E8, 0.0000000000000000000321547835247865123,"
- + "982.8, -0.00000000000023456789E8, -1.789E-8, -0.0000000000000000000321547835247865123" + "]" + "}";
-
- jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), jsonHandler);
- JsonValue jv = jsonHandler.getJsonObject();
- assertTrue(jv.getElement("double").isArray());
- Iterator<JsonValue> values = jv.getElement("double").getElements();
- int i = 0;
- while (values.hasNext())
- {
- JsonValue v = values.next();
- assertTrue(v.isNumeric());
- assertFalse(v.isLong());
- assertTrue(v.isDouble());
- if (i == 0)
- assertEquals(1.0, v.getDoubleValue());
- if (i == 2)
- assertEquals(111111.2222222, v.getDoubleValue());
- if (i == 9)
- assertEquals(0.00000000000023456789E8, v.getDoubleValue());
- i++;
- }
- }
-
-}
Modified: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonGeneratorTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonGeneratorTest.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonGeneratorTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -18,8 +18,6 @@
*/
package org.exoplatform.ws.frameworks.json.impl;
-import junit.framework.TestCase;
-
import org.exoplatform.ws.frameworks.json.BeanWithBookEnum;
import org.exoplatform.ws.frameworks.json.BeanWithSimpleEnum;
import org.exoplatform.ws.frameworks.json.BeanWithTransientField;
@@ -42,7 +40,7 @@
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
* @version $Id: JsonGeneratorTest.java 34417 2009-07-23 14:42:56Z dkatayev $
*/
-public class JsonGeneratorTest extends TestCase
+public class JsonGeneratorTest extends JsonTest
{
@Override
@@ -51,98 +49,103 @@
super.setUp();
}
- public void testSimpleObject() throws Exception
+ public void testBean() throws Exception
{
- int _pages = 386;
- long _isdn = 93011099534534L;
- double _price = 19.37;
- String _title = "JUnit in Action";
- String _author = "Vincent Masson";
- boolean _delivery = true;
- boolean _availability = true;
- Book book = new Book();
- book.setAuthor(_author);
- book.setTitle(_title);
- book.setPages(_pages);
- book.setPrice(_price);
- book.setIsdn(_isdn);
- book.setAvailability(_availability);
- book.setDelivery(_delivery);
+ JsonValue jsonValue = new JsonGeneratorImpl().createJsonObject(junitBook);
+ assertTrue(jsonValue.isObject());
+ assertEquals(junitBook.getAuthor(), jsonValue.getElement("author").getStringValue());
+ assertEquals(junitBook.getTitle(), jsonValue.getElement("title").getStringValue());
+ assertEquals(junitBook.getPages(), jsonValue.getElement("pages").getIntValue());
+ assertEquals(junitBook.getPrice(), jsonValue.getElement("price").getDoubleValue());
+ assertEquals(junitBook.getIsdn(), jsonValue.getElement("isdn").getLongValue());
+ assertEquals(junitBook.getDelivery(), jsonValue.getElement("delivery").getBooleanValue());
+ assertEquals(junitBook.isAvailability(), jsonValue.getElement("availability").getBooleanValue());
+ }
- JsonValue jsonValue = new JsonGeneratorImpl().createJsonObject(book);
+ public void testArray() throws Exception
+ {
+ Book[] a = new Book[]{junitBook, csharpBook, javaScriptBook};
+ JsonValue jsonValue = new JsonGeneratorImpl().createJsonArray(a);
+ assertTrue(jsonValue.isArray());
+ Iterator<JsonValue> iterator = jsonValue.getElements();
+ assertEquals(a[0].getTitle(), iterator.next().getElement("title").getStringValue());
+ assertEquals(a[1].getTitle(), iterator.next().getElement("title").getStringValue());
+ assertEquals(a[2].getTitle(), iterator.next().getElement("title").getStringValue());
+ //System.out.println(jsonValue);
+ }
+
+ public void testArrayNull() throws Exception
+ {
+ Book[] a = null;
+ JsonValue jsonValue = new JsonGeneratorImpl().createJsonArray(a);
+ assertTrue(jsonValue.isNull());
+ }
+
+ public void testCollection() throws Exception
+ {
+ List<Book> l = Arrays.asList(junitBook, csharpBook, javaScriptBook);
+ JsonValue jsonValue = new JsonGeneratorImpl().createJsonArray(l);
+ assertTrue(jsonValue.isArray());
+ Iterator<JsonValue> iterator = jsonValue.getElements();
+ assertEquals(l.get(0).getTitle(), iterator.next().getElement("title").getStringValue());
+ assertEquals(l.get(1).getTitle(), iterator.next().getElement("title").getStringValue());
+ assertEquals(l.get(2).getTitle(), iterator.next().getElement("title").getStringValue());
+ //System.out.println(jsonValue);
+ }
+
+ public void testCollectionNull() throws Exception
+ {
+ List<Book> l = null;
+ JsonValue jsonValue = new JsonGeneratorImpl().createJsonArray(l);
+ assertTrue(jsonValue.isNull());
+ }
+
+ public void testMap() throws Exception
+ {
+ Map<String, Book> m = new HashMap<String, Book>();
+ m.put("junit", junitBook);
+ m.put("csharp", csharpBook);
+ m.put("js", javaScriptBook);
+ JsonValue jsonValue = new JsonGeneratorImpl().createJsonObjectFromMap(m);
assertTrue(jsonValue.isObject());
- assertEquals(_author, jsonValue.getElement("author").getStringValue());
- assertEquals(_title, jsonValue.getElement("title").getStringValue());
- assertEquals(_pages, jsonValue.getElement("pages").getIntValue());
- assertEquals(_price, jsonValue.getElement("price").getDoubleValue());
- assertEquals(_isdn, jsonValue.getElement("isdn").getLongValue());
- assertEquals(_delivery, jsonValue.getElement("delivery").getBooleanValue());
- assertEquals(_availability, jsonValue.getElement("availability").getBooleanValue());
+ assertEquals(junitBook.getTitle(), jsonValue.getElement("junit").getElement("title").getStringValue());
+ assertEquals(csharpBook.getTitle(), jsonValue.getElement("csharp").getElement("title").getStringValue());
+ assertEquals(javaScriptBook.getTitle(), jsonValue.getElement("js").getElement("title").getStringValue());
+ //System.out.println(jsonValue);
}
- public void testSimpleObject2() throws Exception
+ public void testMapNull() throws Exception
{
- int _pages = 386;
- int _isdn = 930110995;
- double _price = 19.37;
- String _title = "JUnit in Action";
- String _author = "Vincent Masson";
- boolean _delivery = false;
- boolean _availability = true;
- Book book = new Book();
- book.setAuthor(_author);
- book.setTitle(_title);
- book.setPages(_pages);
- book.setPrice(_price);
- book.setIsdn(_isdn);
- book.setAvailability(_availability);
- book.setDelivery(_delivery);
+ Map<String, Book> m = null;
+ JsonValue jsonValue = new JsonGeneratorImpl().createJsonObjectFromMap(m);
+ assertTrue(jsonValue.isNull());
+ }
+ public void testBeanWrapper() throws Exception
+ {
BookWrapper bookWrapper = new BookWrapper();
- bookWrapper.setBook(book);
+ bookWrapper.setBook(junitBook);
JsonValue jsonValue = new JsonGeneratorImpl().createJsonObject(bookWrapper);
assertTrue(jsonValue.isObject());
- assertEquals(_author, jsonValue.getElement("book").getElement("author").getStringValue());
- assertEquals(_title, jsonValue.getElement("book").getElement("title").getStringValue());
- assertEquals(_pages, jsonValue.getElement("book").getElement("pages").getIntValue());
- assertEquals(_price, jsonValue.getElement("book").getElement("price").getDoubleValue());
- assertEquals(_isdn, jsonValue.getElement("book").getElement("isdn").getLongValue());
- assertEquals(_delivery, jsonValue.getElement("book").getElement("delivery").getBooleanValue());
- assertEquals(_availability, jsonValue.getElement("book").getElement("availability").getBooleanValue());
+ assertEquals(junitBook.getAuthor(), jsonValue.getElement("book").getElement("author").getStringValue());
+ assertEquals(junitBook.getTitle(), jsonValue.getElement("book").getElement("title").getStringValue());
+ assertEquals(junitBook.getPages(), jsonValue.getElement("book").getElement("pages").getIntValue());
+ assertEquals(junitBook.getPrice(), jsonValue.getElement("book").getElement("price").getDoubleValue());
+ assertEquals(junitBook.getIsdn(), jsonValue.getElement("book").getElement("isdn").getLongValue());
+ assertEquals(junitBook.getDelivery(), jsonValue.getElement("book").getElement("delivery").getBooleanValue());
+ assertEquals(junitBook.isAvailability(), jsonValue.getElement("book").getElement("availability")
+ .getBooleanValue());
}
- public void testSimpleObject3() throws Exception
+ public void testBeanCollection() throws Exception
{
- Book book = new Book();
- book.setAuthor("Vincent Masson");
- book.setTitle("JUnit in Action");
- book.setPages(386);
- book.setPrice(19.37);
- book.setIsdn(93011099534534L);
- book.setAvailability(true);
- book.setDelivery(true);
List<Book> l = new ArrayList<Book>();
- l.add(book);
- book = new Book();
- book.setAuthor("Christian Gross");
- book.setTitle("Beginning C# 2008 from novice to professional");
- book.setPages(511);
- book.setPrice(23.56);
- book.setIsdn(9781590598696L);
- book.setAvailability(true);
- book.setDelivery(true);
- l.add(book);
- book = new Book();
- book.setAuthor("Chuck Easttom");
- book.setTitle("Advanced JavaScript, Third Edition");
- book.setPages(617);
- book.setPrice(25.99);
- book.setIsdn(9781598220339L);
- book.setAvailability(true);
- book.setDelivery(true);
- l.add(book);
+ l.add(junitBook);
+ l.add(csharpBook);
+ l.add(javaScriptBook);
BookStorage bookStorage = new BookStorage();
bookStorage.setBooks(l);
+
JsonValue jsonValue = new JsonGeneratorImpl().createJsonObject(bookStorage);
assertTrue(jsonValue.isObject());
Iterator<JsonValue> iterator = jsonValue.getElement("books").getElements();
@@ -151,35 +154,19 @@
assertEquals(l.get(2).getTitle(), iterator.next().getElement("title").getStringValue());
}
- public void testBeanWithCollections() throws Exception
+ public void testBeanMap() throws Exception
{
JavaMapBean mb = new JavaMapBean();
+
Map<String, Book> m = new HashMap<String, Book>();
- Book book = new Book();
- book.setAuthor("Vincent Masson");
- book.setTitle("JUnit in Action");
- book.setPages(386);
- book.setPrice(19.37);
- book.setIsdn(93011099534534L);
- m.put("test", book);
+ m.put("test", junitBook);
mb.setHashMap((HashMap<String, Book>)m);
List<Book> l = new ArrayList<Book>();
- l.add(book);
- book = new Book();
- book.setAuthor("Christian Gross");
- book.setTitle("Beginning C# 2008 from novice to professional");
- book.setPages(511);
- book.setPrice(23.56);
- book.setIsdn(9781590598696L);
- l.add(book);
- book = new Book();
- book.setAuthor("Chuck Easttom");
- book.setTitle("Advanced JavaScript, Third Edition");
- book.setPages(617);
- book.setPrice(25.99);
- book.setIsdn(9781598220339L);
- l.add(book);
+ l.add(junitBook);
+ l.add(csharpBook);
+ l.add(javaScriptBook);
+
Map<String, List<Book>> hu = new HashMap<String, List<Book>>();
hu.put("1", l);
hu.put("2", l);
@@ -195,31 +182,22 @@
JsonValue jsonValue = new JsonGeneratorImpl().createJsonObject(mb);
assertEquals(str.get("key2"), jsonValue.getElement("strings").getElement("key2").getStringValue());
-
assertNotNull(jsonValue.getElement("hashMap"));
-
assertNotNull(jsonValue.getElement("mapList"));
- assertEquals("JUnit in Action", jsonValue.getElement("mapList").getElement("3").getElements().next().getElement(
- "title").getStringValue());
- System.out.println(jsonValue);
+ assertEquals("JUnit in Action",
+ jsonValue.getElement("mapList").getElement("3").getElements().next().getElement("title").getStringValue());
+ // System.out.println(jsonValue);
}
- public void testBeanWithTransientField() throws Exception
+ public void testBeanTransientField() throws Exception
{
BeanWithTransientField trBean = new BeanWithTransientField();
JsonValue jsonValue = new JsonGeneratorImpl().createJsonObject(trBean);
assertEquals("visible", jsonValue.getElement("field").getStringValue());
- try
- {
- assertEquals("invisible", jsonValue.getElement("transientField").getStringValue());
- fail("It must not be serialized");
- }
- catch (NullPointerException e)
- {
- }
+ assertNull(jsonValue.getElement("transientField"));
}
- public void testEnumSerialization() throws Exception
+ public void testBeanEnum() throws Exception
{
BeanWithSimpleEnum be = new BeanWithSimpleEnum();
be.setName("name");
@@ -227,7 +205,7 @@
be.setCounts(new StringEnum[]{StringEnum.ONE, StringEnum.TWO});
be.setCountList(Arrays.asList(StringEnum.ONE, StringEnum.TWO, StringEnum.TREE));
JsonValue jsonValue = new JsonGeneratorImpl().createJsonObject(be);
- System.out.println(jsonValue);
+ //System.out.println(jsonValue);
assertEquals("name", jsonValue.getElement("name").getStringValue());
@@ -255,12 +233,12 @@
assertTrue(tmp.contains(StringEnum.TREE.name()));
}
- public void testEnumSerialization2() throws Exception
+ public void testBeanEnumObject() throws Exception
{
BeanWithBookEnum be = new BeanWithBookEnum();
be.setBook(BookEnum.JUNIT_IN_ACTION);
JsonValue jsonValue = new JsonGeneratorImpl().createJsonObject(be);
- System.out.println(jsonValue);
+ //System.out.println(jsonValue);
assertEquals(BookEnum.JUNIT_IN_ACTION.name(), jsonValue.getElement("book").getStringValue());
}
Modified: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonParserTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonParserTest.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonParserTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -18,271 +18,189 @@
*/
package org.exoplatform.ws.frameworks.json.impl;
-import junit.framework.TestCase;
-
-import org.exoplatform.ws.frameworks.json.BeanWithBookEnum;
-import org.exoplatform.ws.frameworks.json.BeanWithSimpleEnum;
-import org.exoplatform.ws.frameworks.json.Book;
-import org.exoplatform.ws.frameworks.json.BookEnum;
-import org.exoplatform.ws.frameworks.json.BookStorage;
-import org.exoplatform.ws.frameworks.json.JavaCollectionBean;
-import org.exoplatform.ws.frameworks.json.JavaMapBean;
-import org.exoplatform.ws.frameworks.json.JsonHandler;
import org.exoplatform.ws.frameworks.json.JsonParser;
-import org.exoplatform.ws.frameworks.json.StringEnum;
import org.exoplatform.ws.frameworks.json.value.JsonValue;
+import org.exoplatform.ws.frameworks.json.value.impl.ArrayValue;
+import org.exoplatform.ws.frameworks.json.value.impl.BooleanValue;
+import org.exoplatform.ws.frameworks.json.value.impl.DoubleValue;
+import org.exoplatform.ws.frameworks.json.value.impl.LongValue;
+import org.exoplatform.ws.frameworks.json.value.impl.ObjectValue;
+import org.exoplatform.ws.frameworks.json.value.impl.StringValue;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
/**
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
* @version $Id: JsonParserTest.java 34417 2009-07-23 14:42:56Z dkatayev $
*/
-public class JsonParserTest extends TestCase
+public class JsonParserTest extends JsonTest
{
- ArrayList<Book> sourceCollection_;
-
@Override
protected void setUp() throws Exception
{
super.setUp();
- sourceCollection_ = new ArrayList<Book>(3);
- Book book = new Book();
- book.setAuthor("Vincent Masson");
- book.setTitle("JUnit in Action");
- book.setPages(386);
- book.setPrice(19.37);
- book.setIsdn(93011099534534L);
- sourceCollection_.add(book);
- Book book1 = new Book();
- book1.setAuthor("Christian Gross");
- book1.setTitle("Beginning C# 2008 from novice to professional");
- book1.setPages(511);
- book1.setPrice(23.56);
- book1.setIsdn(9781590598696L);
- sourceCollection_.add(book1);
- Book book2 = new Book();
- book2.setAuthor("Chuck Easttom");
- book2.setTitle("Advanced JavaScript. Third Edition");
- book2.setPages(617);
- book2.setPrice(25.99);
- book2.setIsdn(9781598220339L);
- sourceCollection_.add(book2);
}
- public void testCollection() throws Exception
+ public void testArrayString() throws Exception
{
- // test restore Collection of standard Java Object from JSON source
- JsonParserImpl jsonParser = new JsonParserImpl();
- String jsonString =
- "{" + "\"strings\":[\"JUnit in Action\",\"Advanced JavaScript\",\"Beginning C# 2008\"],"
- + "\"chars\":[\"b\",\"o\",\"o\",\"k\"]," + "\"integers\":[386, 421, 565]" + "}";
- JsonHandler jsonHandler = new JsonDefaultHandler();
- jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), jsonHandler);
- JsonValue jsonValue = jsonHandler.getJsonObject();
- Object o = new BeanBuilder().createObject(JavaCollectionBean.class, jsonValue);
- List<String> s = ((JavaCollectionBean)o).getStrings();
+ String jsonString = "[\"JUnit in Action\",\"Advanced JavaScript\",\"Beginning C# 2008\"]";
+ JsonParser jsonParser = new JsonParserImpl();
+
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ assertTrue(jsonValue.isArray());
+ Set<String> s = new HashSet<String>();
+ for (Iterator<JsonValue> elements = jsonValue.getElements(); elements.hasNext();)
+ {
+ JsonValue next = elements.next();
+ assertTrue(next.isString());
+ s.add(next.getStringValue());
+ }
assertEquals(3, s.size());
- assertEquals("JUnit in Action", s.get(0));
- assertEquals("Advanced JavaScript", s.get(1));
- assertEquals("Beginning C# 2008", s.get(2));
- List<Character> c = ((JavaCollectionBean)o).getChars();
- assertEquals('b', c.get(0).charValue());
- assertEquals('o', c.get(1).charValue());
- assertEquals('o', c.get(2).charValue());
- assertEquals('k', c.get(3).charValue());
- List<Integer> i = ((JavaCollectionBean)o).getIntegers();
- assertEquals(386, i.get(0).intValue());
- assertEquals(421, i.get(1).intValue());
- assertEquals(565, i.get(2).intValue());
- // more testing for other type of Collection with custom object
+ assertTrue(s.contains("JUnit in Action"));
+ assertTrue(s.contains("Advanced JavaScript"));
+ assertTrue(s.contains("Beginning C# 2008"));
}
- public void testCollection2() throws Exception
+ public void testArrayLong() throws Exception
{
- // test restore Collection of other Java Object from JSON source
- JsonParserImpl jsonParser = new JsonParserImpl();
- // check restore different type of Collection
- JsonHandler jsonHandler = new JsonDefaultHandler();
- jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
- "CollectionTest.txt")), jsonHandler);
- JsonValue jsonValue = jsonHandler.getJsonObject();
- Object o = new BeanBuilder().createObject(JavaCollectionBean.class, jsonValue);
+ String jsonString = "[1, 0xAA, 077, 123, 32765, 77787, 123456789, 0x123456, 0123456, -2387648, -123456789]";
- assertEquals(3, ((JavaCollectionBean)o).getArrayList().size());
- assertTrue(((JavaCollectionBean)o).getArrayList().get(0).equals(sourceCollection_.get(0)));
- assertTrue(((JavaCollectionBean)o).getArrayList().get(1).equals(sourceCollection_.get(1)));
- assertTrue(((JavaCollectionBean)o).getArrayList().get(2).equals(sourceCollection_.get(2)));
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), handler);
+ JsonValue jsonValue = handler.getJsonObject();
- assertEquals(3, ((JavaCollectionBean)o).getVector().size());
- assertTrue(((JavaCollectionBean)o).getVector().get(0).equals(sourceCollection_.get(0)));
- assertTrue(((JavaCollectionBean)o).getVector().get(1).equals(sourceCollection_.get(1)));
- assertTrue(((JavaCollectionBean)o).getVector().get(2).equals(sourceCollection_.get(2)));
-
- assertEquals(3, ((JavaCollectionBean)o).getLinkedList().size());
- assertTrue(((JavaCollectionBean)o).getLinkedList().get(0).equals(sourceCollection_.get(0)));
- assertTrue(((JavaCollectionBean)o).getLinkedList().get(1).equals(sourceCollection_.get(1)));
- assertTrue(((JavaCollectionBean)o).getLinkedList().get(2).equals(sourceCollection_.get(2)));
-
- assertEquals(3, ((JavaCollectionBean)o).getLinkedHashSet().size());
-
- assertEquals(3, ((JavaCollectionBean)o).getHashSet().size());
-
- assertEquals(3, ((JavaCollectionBean)o).getList().size());
- assertTrue(((JavaCollectionBean)o).getList().get(0).equals(sourceCollection_.get(0)));
- assertTrue(((JavaCollectionBean)o).getList().get(1).equals(sourceCollection_.get(1)));
- assertTrue(((JavaCollectionBean)o).getList().get(2).equals(sourceCollection_.get(2)));
-
- assertEquals(3, ((JavaCollectionBean)o).getSet().size());
-
- assertEquals(3, ((JavaCollectionBean)o).getQueue().size());
-
- assertEquals(3, ((JavaCollectionBean)o).getCollection().size());
-
- assertEquals(3, ((JavaCollectionBean)o).getArray().length);
- assertTrue(((JavaCollectionBean)o).getArray()[0].equals(sourceCollection_.get(0)));
- assertTrue(((JavaCollectionBean)o).getArray()[1].equals(sourceCollection_.get(1)));
- assertTrue(((JavaCollectionBean)o).getArray()[2].equals(sourceCollection_.get(2)));
+ assertTrue(jsonValue.isArray());
+ int i = 0;
+ for (Iterator<JsonValue> elements = jsonValue.getElements(); elements.hasNext(); i++)
+ {
+ JsonValue next = elements.next();
+ assertTrue(next.isNumeric());
+ assertTrue(next.isLong());
+ assertFalse(next.isDouble());
+ if (i == 0)
+ assertEquals(1L, next.getLongValue());
+ if (i == 3)
+ assertEquals(123L, next.getLongValue());
+ if (i == 6)
+ assertEquals(123456789L, next.getLongValue());
+ }
}
- public void testMap() throws Exception
+ public void testArrayDouble() throws Exception
{
- JsonParserImpl jsonParser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
String jsonString =
- "{" + "\"strings\":{" + "\"book\":\"Beginning C# 2008\"," + "\"author\":\"Christian Gross\"" + "},"
- + "\"integers\":{" + "\"one\":1," + "\"two\":2," + "\"three\":3" + "}," + "\"booleans\":{"
- + "\"true\":true," + "\"false\":false" + "}" + "}";
- jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), jsonHandler);
- JsonValue jsonValue = jsonHandler.getJsonObject();
- Object o = new BeanBuilder().createObject(JavaMapBean.class, jsonValue);
+ "[1.0, 0.0006382746, 111111.2222222, 9999999999999.9999999999999,"
+ + "9827394873249.8, 1.23456789E8, 123456.789E8, 3215478352478651238.0,"
+ + "982.8, 0.00000000000023456789E8, 1.789E8, 0.0000000000000000000321547835247865123,"
+ + "982.8, -0.00000000000023456789E8, -1.789E-8, -0.0000000000000000000321547835247865123]";
- assertEquals("Beginning C# 2008", ((JavaMapBean)o).getStrings().get("book"));
- assertEquals("Christian Gross", ((JavaMapBean)o).getStrings().get("author"));
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), handler);
+ JsonValue jsonValue = handler.getJsonObject();
- assertEquals(1, ((JavaMapBean)o).getIntegers().get("one").intValue());
- assertEquals(2, ((JavaMapBean)o).getIntegers().get("two").intValue());
- assertEquals(3, ((JavaMapBean)o).getIntegers().get("three").intValue());
-
- assertTrue(((JavaMapBean)o).getBooleans().get("true"));
- assertFalse(((JavaMapBean)o).getBooleans().get("false"));
+ assertTrue(jsonValue.isArray());
+ int i = 0;
+ for (Iterator<JsonValue> elements = jsonValue.getElements(); elements.hasNext(); i++)
+ {
+ JsonValue next = elements.next();
+ assertTrue(next.isNumeric());
+ assertFalse(next.isLong());
+ assertTrue(next.isDouble());
+ if (i == 0)
+ assertEquals(1.0, next.getDoubleValue());
+ if (i == 2)
+ assertEquals(111111.2222222, next.getDoubleValue());
+ if (i == 9)
+ assertEquals(0.00000000000023456789E8, next.getDoubleValue());
+ }
}
- public void testMap2() throws Exception
+ public void testArrayMixed() throws Exception
{
- JsonParserImpl jsonParser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
- "MapTest.txt")), jsonHandler);
- JsonValue jv = jsonHandler.getJsonObject();
- Object o = new BeanBuilder().createObject(JavaMapBean.class, jv);
+ String jsonString = "[1.0, \"to be or not to be\", 111, true, {\"object\":{\"foo\":\"bar\"}}]";
- assertTrue(((JavaMapBean)o).getMap().get("JUnit").equals(sourceCollection_.get(0)));
- assertTrue(((JavaMapBean)o).getMap().get("C#").equals(sourceCollection_.get(1)));
- assertTrue(((JavaMapBean)o).getMap().get("JavaScript").equals(sourceCollection_.get(2)));
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), handler);
+ JsonValue jsonValue = handler.getJsonObject();
- assertTrue(((JavaMapBean)o).getHashMap().get("JUnit").equals(sourceCollection_.get(0)));
- assertTrue(((JavaMapBean)o).getHashMap().get("C#").equals(sourceCollection_.get(1)));
- assertTrue(((JavaMapBean)o).getHashMap().get("JavaScript").equals(sourceCollection_.get(2)));
+ assertTrue(jsonValue.isArray());
+ ArrayValue exp = new ArrayValue();
+ exp.addElement(new DoubleValue(1.0D));
+ exp.addElement(new StringValue("to be or not to be"));
+ exp.addElement(new LongValue(111));
+ exp.addElement(new BooleanValue(true));
+ ObjectValue o = new ObjectValue();
+ o.addElement("foo", new StringValue("bar"));
+ ObjectValue o1 = new ObjectValue();
+ o1.addElement("object", o);
+ exp.addElement(o1);
- assertTrue(((JavaMapBean)o).getHashtable().get("JUnit").equals(sourceCollection_.get(0)));
- assertTrue(((JavaMapBean)o).getHashtable().get("C#").equals(sourceCollection_.get(1)));
- assertTrue(((JavaMapBean)o).getHashtable().get("JavaScript").equals(sourceCollection_.get(2)));
-
- assertTrue(((JavaMapBean)o).getLinkedHashMap().get("JUnit").equals(sourceCollection_.get(0)));
- assertTrue(((JavaMapBean)o).getLinkedHashMap().get("C#").equals(sourceCollection_.get(1)));
- assertTrue(((JavaMapBean)o).getLinkedHashMap().get("JavaScript").equals(sourceCollection_.get(2)));
-
+ Iterator<JsonValue> elements = jsonValue.getElements();
+ Iterator<JsonValue> expElements = jsonValue.getElements();
+ for (; elements.hasNext() && expElements.hasNext();)
+ {
+ JsonValue next = elements.next();
+ JsonValue expNext = expElements.next();
+ assertEquals(expNext.toString(), next.toString());
+ }
+ // Both must be empty
+ assertFalse(elements.hasNext() || expElements.hasNext());
}
- public void testBean() throws Exception
+ public void testObject() throws Exception
{
- JsonParserImpl jsonParser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
- "BookStorage.txt")), jsonHandler);
- JsonValue jv = jsonHandler.getJsonObject();
- Object o = new BeanBuilder().createObject(BookStorage.class, jv);
- assertTrue(((BookStorage)o).getBooks().get(0).equals(sourceCollection_.get(0)));
- assertTrue(((BookStorage)o).getBooks().get(1).equals(sourceCollection_.get(1)));
- assertTrue(((BookStorage)o).getBooks().get(2).equals(sourceCollection_.get(2)));
- }
+ String jsonString =
+ "{\"foo\":\"bar\", \"book\":{\"author\":\"Christian Gross\",\"title\":\"Beginning C# 2008\"}}";
- public void testMultiDimensionArray() throws Exception
- {
JsonParser jsonParser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
- "MultiDimension.txt")), jsonHandler);
- JsonValue jsonValue = jsonHandler.getJsonObject();
- // System.out.println(jsonValue);
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
assertTrue(jsonValue.isObject());
- assertTrue(jsonValue.getElement("books").isArray());
- assertTrue(jsonValue.getElement("books").getElements().next().isArray());
- assertTrue(jsonValue.getElement("books").getElements().next().getElements().next().isArray());
- assertTrue(jsonValue.getElement("books").getElements().next().getElements().next().getElements().next()
- .isObject());
- assertEquals("JUnit in Action", jsonValue.getElement("books").getElements().next().getElements().next()
- .getElements().next().getElement("title").getStringValue());
+ JsonValue sValue = jsonValue.getElement("foo");
+ assertTrue(sValue.isString());
+ assertEquals("bar", sValue.getStringValue());
+ JsonValue bookValue = jsonValue.getElement("book");
+ assertTrue(bookValue.isObject());
+ assertEquals("Beginning C# 2008", bookValue.getElement("title").getStringValue());
+ assertEquals("Christian Gross", bookValue.getElement("author").getStringValue());
}
- public void testEnumSerialization() throws Exception
+ public void testMultiDimensionArray() throws Exception
{
- String source =
- "{\"countList\":[\"ONE\",\"TWO\",\"TREE\"], \"name\":\"andrew\",\"count\":\"TREE\",\"counts\":[\"TWO\",\"TREE\"]}";
- JsonParser parser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- parser.parse(new ByteArrayInputStream(source.getBytes()), jsonHandler);
- JsonValue jsonValue = jsonHandler.getJsonObject();
- // System.out.println(jsonValue);
+ String jsonString = "[\"foo0\", [\"foo1\", \"bar1\", [\"foo2\", \"bar2\"]], \"bar0\"]";
- BeanWithSimpleEnum o = (BeanWithSimpleEnum)new BeanBuilder().createObject(BeanWithSimpleEnum.class, jsonValue);
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(new ByteArrayInputStream(jsonString.getBytes())), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+ //System.out.println(jsonValue);
- assertEquals("andrew", o.getName());
+ ArrayValue exp = new ArrayValue();
+ exp.addElement(new StringValue("foo0"));
+ ArrayValue l1 = new ArrayValue();
+ exp.addElement(l1);
+ l1.addElement(new StringValue("foo1"));
+ l1.addElement(new StringValue("bar1"));
+ ArrayValue l2 = new ArrayValue();
+ l1.addElement(l2);
+ l2.addElement(new StringValue("foo2"));
+ l2.addElement(new StringValue("bar2"));
+ exp.addElement(new StringValue("bar0"));
- assertEquals(StringEnum.TREE, o.getCount());
-
- StringEnum[] counts = o.getCounts();
- assertEquals(2, counts.length);
-
- List<StringEnum> tmp = Arrays.asList(counts);
- assertTrue(tmp.contains(StringEnum.TWO));
- assertTrue(tmp.contains(StringEnum.TREE));
-
- tmp = o.getCountList();
- assertEquals(3, tmp.size());
- assertTrue(tmp.contains(StringEnum.ONE));
- assertTrue(tmp.contains(StringEnum.TWO));
- assertTrue(tmp.contains(StringEnum.TREE));
+ assertEquals(exp.toString(), jsonValue.toString());
}
- public void testEnumSerialization2() throws Exception
- {
- String source = "{\"book\":\"BEGINNING_C\"}";
- JsonParser parser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- parser.parse(new ByteArrayInputStream(source.getBytes()), jsonHandler);
- JsonValue jsonValue = jsonHandler.getJsonObject();
- //System.out.println(jsonValue);
- BeanWithBookEnum o = (BeanWithBookEnum)new BeanBuilder().createObject(BeanWithBookEnum.class, jsonValue);
- assertEquals(BookEnum.BEGINNING_C, o.getBook());
- }
-
- public void testArray() throws Exception
- {
- String source = "{\"array\":[\"a\",\"b\",\"c\"]}";
- JsonParser parser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- parser.parse(new ByteArrayInputStream(source.getBytes()), jsonHandler);
- JsonValue jsonValue = jsonHandler.getJsonObject();
- System.out.println(jsonValue.getElement("array").isArray());
-
-
- }
-
}
Added: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonTest.java (rev 0)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2009 eXo Platform SAS.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.exoplatform.ws.frameworks.json.impl;
+
+import junit.framework.TestCase;
+
+import org.exoplatform.ws.frameworks.json.Book;
+
+/**
+ * @author <a href="andrew00x at gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+public abstract class JsonTest extends TestCase
+{
+
+ protected Book junitBook;
+
+ protected Book csharpBook;
+
+ protected Book javaScriptBook;
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ junitBook = new Book();
+ junitBook.setAuthor("Vincent Masson");
+ junitBook.setTitle("JUnit in Action");
+ junitBook.setPages(386);
+ junitBook.setPrice(19.37);
+ junitBook.setIsdn(93011099534534L);
+ junitBook.setAvailability(false);
+ junitBook.setDelivery(false);
+
+ csharpBook = new Book();
+ csharpBook.setAuthor("Christian Gross");
+ csharpBook.setTitle("Beginning C# 2008 from novice to professional");
+ csharpBook.setPages(511);
+ csharpBook.setPrice(23.56);
+ csharpBook.setIsdn(9781590598696L);
+ csharpBook.setAvailability(false);
+ csharpBook.setDelivery(false);
+
+ javaScriptBook = new Book();
+ javaScriptBook.setAuthor("Chuck Easttom");
+ javaScriptBook.setTitle("Advanced JavaScript. Third Edition");
+ javaScriptBook.setPages(617);
+ javaScriptBook.setPrice(25.99);
+ javaScriptBook.setIsdn(9781598220339L);
+ javaScriptBook.setAvailability(false);
+ javaScriptBook.setDelivery(false);
+ }
+
+}
Property changes on: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Modified: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonUtilsTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonUtilsTest.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonUtilsTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -18,13 +18,11 @@
*/
package org.exoplatform.ws.frameworks.json.impl;
-import junit.framework.TestCase;
-
/**
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
* @version $Id: JsonUtilsTest.java 34417 2009-07-23 14:42:56Z dkatayev $
*/
-public class JsonUtilsTest extends TestCase
+public class JsonUtilsTest extends JsonTest
{
@Override
@@ -42,34 +40,34 @@
assertEquals(JsonUtils.getJsonString("str\\ing"), "\"str\\\\ing\"");
assertEquals(JsonUtils.getJsonString("stri\"ng"), "\"stri\\\"ng\"");
assertEquals(JsonUtils.getJsonString("stri/ng"), "\"stri/ng\"");
- int i = 0;
- for (char c = '\u0000'; c < '\u0020'; c++, i++)
- {
- System.out.print(JsonUtils.getJsonString(c + "") + " ");
- if (i > 10)
- {
- System.out.println();
- i = 0;
- }
- }
- for (char c = '\u0080'; c < '\u00a0'; c++, i++)
- {
- System.out.print(JsonUtils.getJsonString(c + " "));
- if (i > 10)
- {
- System.out.println();
- i = 0;
- }
- }
- for (char c = '\u2000'; c < '\u2100'; c++, i++)
- {
- System.out.print(JsonUtils.getJsonString(c + " "));
- if (i > 10)
- {
- System.out.println();
- i = 0;
- }
- }
+ // int i = 0;
+ // for (char c = '\u0000'; c < '\u0020'; c++, i++)
+ // {
+ // System.out.print(JsonUtils.getJsonString(c + "") + " ");
+ // if (i > 10)
+ // {
+ // System.out.println();
+ // i = 0;
+ // }
+ // }
+ // for (char c = '\u0080'; c < '\u00a0'; c++, i++)
+ // {
+ // System.out.print(JsonUtils.getJsonString(c + " "));
+ // if (i > 10)
+ // {
+ // System.out.println();
+ // i = 0;
+ // }
+ // }
+ // for (char c = '\u2000'; c < '\u2100'; c++, i++)
+ // {
+ // System.out.print(JsonUtils.getJsonString(c + " "));
+ // if (i > 10)
+ // {
+ // System.out.println();
+ // i = 0;
+ // }
+ // }
}
}
Modified: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonWriterTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonWriterTest.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/JsonWriterTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -18,15 +18,13 @@
*/
package org.exoplatform.ws.frameworks.json.impl;
-import junit.framework.TestCase;
-
import java.io.ByteArrayOutputStream;
/**
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
* @version $Id: JsonWriterTest.java 34417 2009-07-23 14:42:56Z dkatayev $
*/
-public class JsonWriterTest extends TestCase
+public class JsonWriterTest extends JsonTest
{
@Override
Added: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilderTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilderTest.java (rev 0)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilderTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -0,0 +1,363 @@
+/*
+ * Copyright (C) 2009 eXo Platform SAS.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.exoplatform.ws.frameworks.json.impl;
+
+import org.exoplatform.ws.frameworks.json.BeanWithBookEnum;
+import org.exoplatform.ws.frameworks.json.BeanWithSimpleEnum;
+import org.exoplatform.ws.frameworks.json.Book;
+import org.exoplatform.ws.frameworks.json.BookEnum;
+import org.exoplatform.ws.frameworks.json.BookStorage;
+import org.exoplatform.ws.frameworks.json.JavaCollectionBean;
+import org.exoplatform.ws.frameworks.json.JavaMapBean;
+import org.exoplatform.ws.frameworks.json.JsonParser;
+import org.exoplatform.ws.frameworks.json.StringEnum;
+import org.exoplatform.ws.frameworks.json.value.JsonValue;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * @author <a href="andrew00x at gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+public class ObjectBuilderTest extends JsonTest
+{
+ private ArrayList<Book> sourceCollection;
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ sourceCollection = new ArrayList<Book>(3);
+ sourceCollection.add(junitBook);
+ sourceCollection.add(csharpBook);
+ sourceCollection.add(javaScriptBook);
+ }
+
+ public void testCollectionArrayList() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getArrayList().size());
+ assertTrue(o.getArrayList().get(0).equals(sourceCollection.get(0)));
+ assertTrue(o.getArrayList().get(1).equals(sourceCollection.get(1)));
+ assertTrue(o.getArrayList().get(2).equals(sourceCollection.get(2)));
+ }
+
+ public void testCollectionVector() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getVector().size());
+ assertTrue(o.getVector().get(0).equals(sourceCollection.get(0)));
+ assertTrue(o.getVector().get(1).equals(sourceCollection.get(1)));
+ assertTrue(o.getVector().get(2).equals(sourceCollection.get(2)));
+ }
+
+ public void testCollectionLinkedList() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getLinkedList().size());
+ assertTrue(o.getLinkedList().get(0).equals(sourceCollection.get(0)));
+ assertTrue(o.getLinkedList().get(1).equals(sourceCollection.get(1)));
+ assertTrue(o.getLinkedList().get(2).equals(sourceCollection.get(2)));
+ }
+
+ public void testCollectionLinkedHashSet() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getLinkedHashSet().size());
+ assertTrue(o.getLinkedHashSet().contains(sourceCollection.get(0)));
+ assertTrue(o.getLinkedHashSet().contains(sourceCollection.get(1)));
+ assertTrue(o.getLinkedHashSet().contains(sourceCollection.get(2)));
+ }
+
+ public void testCollectionHashSet() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getHashSet().size());
+ assertTrue(o.getHashSet().contains(sourceCollection.get(0)));
+ assertTrue(o.getHashSet().contains(sourceCollection.get(1)));
+ assertTrue(o.getHashSet().contains(sourceCollection.get(2)));
+ }
+
+ public void testCollectionList() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getList().size());
+ assertTrue(o.getList().get(0).equals(sourceCollection.get(0)));
+ assertTrue(o.getList().get(1).equals(sourceCollection.get(1)));
+ assertTrue(o.getList().get(2).equals(sourceCollection.get(2)));
+ }
+
+ public void testCollectionSet() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getSet().size());
+ assertTrue(o.getSet().contains(sourceCollection.get(0)));
+ assertTrue(o.getSet().contains(sourceCollection.get(1)));
+ assertTrue(o.getSet().contains(sourceCollection.get(2)));
+ }
+
+ public void testCollectionQueue() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getQueue().size());
+ assertTrue(o.getQueue().contains(sourceCollection.get(0)));
+ assertTrue(o.getQueue().contains(sourceCollection.get(1)));
+ assertTrue(o.getQueue().contains(sourceCollection.get(2)));
+ }
+
+ public void testCollectionCollection() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getCollection().size());
+ assertTrue(o.getCollection().contains(sourceCollection.get(0)));
+ assertTrue(o.getCollection().contains(sourceCollection.get(1)));
+ assertTrue(o.getCollection().contains(sourceCollection.get(2)));
+ }
+
+ public void testCollectionArray() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ // check restore different type of Collection
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "CollectionTest.txt")), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ JavaCollectionBean o = ObjectBuilder.createObject(JavaCollectionBean.class, jsonValue);
+
+ assertEquals(3, o.getArray().length);
+ assertTrue(o.getArray()[0].equals(sourceCollection.get(0)));
+ assertTrue(o.getArray()[1].equals(sourceCollection.get(1)));
+ assertTrue(o.getArray()[2].equals(sourceCollection.get(2)));
+ }
+
+ public void testMap2() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "MapTest.txt")), handler);
+ JsonValue jv = handler.getJsonObject();
+ JavaMapBean o = ObjectBuilder.createObject(JavaMapBean.class, jv);
+
+ assertTrue(o.getMap().get("JUnit").equals(sourceCollection.get(0)));
+ assertTrue(o.getMap().get("C#").equals(sourceCollection.get(1)));
+ assertTrue(o.getMap().get("JavaScript").equals(sourceCollection.get(2)));
+
+ assertTrue(o.getHashMap().get("JUnit").equals(sourceCollection.get(0)));
+ assertTrue(o.getHashMap().get("C#").equals(sourceCollection.get(1)));
+ assertTrue(o.getHashMap().get("JavaScript").equals(sourceCollection.get(2)));
+
+ assertTrue(o.getHashtable().get("JUnit").equals(sourceCollection.get(0)));
+ assertTrue(o.getHashtable().get("C#").equals(sourceCollection.get(1)));
+ assertTrue(o.getHashtable().get("JavaScript").equals(sourceCollection.get(2)));
+
+ assertTrue(o.getLinkedHashMap().get("JUnit").equals(sourceCollection.get(0)));
+ assertTrue(o.getLinkedHashMap().get("C#").equals(sourceCollection.get(1)));
+ assertTrue(o.getLinkedHashMap().get("JavaScript").equals(sourceCollection.get(2)));
+
+ }
+
+ public void testMapMap() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "MapTest.txt")), handler);
+ JsonValue jv = handler.getJsonObject();
+ JavaMapBean o = ObjectBuilder.createObject(JavaMapBean.class, jv);
+
+ assertTrue(o.getMap().get("JUnit").equals(sourceCollection.get(0)));
+ assertTrue(o.getMap().get("C#").equals(sourceCollection.get(1)));
+ assertTrue(o.getMap().get("JavaScript").equals(sourceCollection.get(2)));
+ }
+
+ public void testMapHashMap() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "MapTest.txt")), handler);
+ JsonValue jv = handler.getJsonObject();
+ JavaMapBean o = ObjectBuilder.createObject(JavaMapBean.class, jv);
+
+ assertTrue(o.getHashMap().get("JUnit").equals(sourceCollection.get(0)));
+ assertTrue(o.getHashMap().get("C#").equals(sourceCollection.get(1)));
+ assertTrue(o.getHashMap().get("JavaScript").equals(sourceCollection.get(2)));
+ }
+
+ public void testMapHashtable() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "MapTest.txt")), handler);
+ JsonValue jv = handler.getJsonObject();
+ JavaMapBean o = ObjectBuilder.createObject(JavaMapBean.class, jv);
+
+ assertTrue(o.getHashtable().get("JUnit").equals(sourceCollection.get(0)));
+ assertTrue(o.getHashtable().get("C#").equals(sourceCollection.get(1)));
+ assertTrue(o.getHashtable().get("JavaScript").equals(sourceCollection.get(2)));
+ }
+
+ public void testMapLinkedHashMap() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "MapTest.txt")), handler);
+ JsonValue jv = handler.getJsonObject();
+ JavaMapBean o = ObjectBuilder.createObject(JavaMapBean.class, jv);
+
+ assertTrue(o.getLinkedHashMap().get("JUnit").equals(sourceCollection.get(0)));
+ assertTrue(o.getLinkedHashMap().get("C#").equals(sourceCollection.get(1)));
+ assertTrue(o.getLinkedHashMap().get("JavaScript").equals(sourceCollection.get(2)));
+ }
+
+ public void testBean() throws Exception
+ {
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
+ "BookStorage.txt")), handler);
+ JsonValue jv = handler.getJsonObject();
+ BookStorage o = ObjectBuilder.createObject(BookStorage.class, jv);
+ assertTrue(o.getBooks().get(0).equals(sourceCollection.get(0)));
+ assertTrue(o.getBooks().get(1).equals(sourceCollection.get(1)));
+ assertTrue(o.getBooks().get(2).equals(sourceCollection.get(2)));
+ }
+
+ public void testEnumSerialization() throws Exception
+ {
+ String source =
+ "{\"countList\":[\"ONE\",\"TWO\",\"TREE\"], \"name\":\"andrew\",\"count\":\"TREE\",\"counts\":[\"TWO\",\"TREE\"]}";
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new ByteArrayInputStream(source.getBytes()), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+ //System.out.println(jsonValue);
+
+ BeanWithSimpleEnum o = ObjectBuilder.createObject(BeanWithSimpleEnum.class, jsonValue);
+
+ assertEquals("andrew", o.getName());
+
+ assertEquals(StringEnum.TREE, o.getCount());
+
+ StringEnum[] counts = o.getCounts();
+ assertEquals(2, counts.length);
+
+ List<StringEnum> tmp = Arrays.asList(counts);
+ assertTrue(tmp.contains(StringEnum.TWO));
+ assertTrue(tmp.contains(StringEnum.TREE));
+
+ tmp = o.getCountList();
+ assertEquals(3, tmp.size());
+ assertTrue(tmp.contains(StringEnum.ONE));
+ assertTrue(tmp.contains(StringEnum.TWO));
+ assertTrue(tmp.contains(StringEnum.TREE));
+ }
+
+ public void testEnumSerialization2() throws Exception
+ {
+ String source = "{\"book\":\"BEGINNING_C\"}";
+ JsonParser jsonParser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ jsonParser.parse(new ByteArrayInputStream(source.getBytes()), handler);
+ JsonValue jsonValue = handler.getJsonObject();
+ //System.out.println(jsonValue);
+ BeanWithBookEnum o = ObjectBuilder.createObject(BeanWithBookEnum.class, jsonValue);
+ assertEquals(BookEnum.BEGINNING_C, o.getBook());
+ }
+}
Property changes on: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/ObjectBuilderTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Modified: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/TransferJavaBeanTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/TransferJavaBeanTest.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/TransferJavaBeanTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -18,8 +18,6 @@
*/
package org.exoplatform.ws.frameworks.json.impl;
-import junit.framework.TestCase;
-
import org.exoplatform.ws.frameworks.json.Book;
import org.exoplatform.ws.frameworks.json.JsonHandler;
import org.exoplatform.ws.frameworks.json.JsonParser;
@@ -33,7 +31,7 @@
* @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
* @version $Id: TransferJavaBeanTest.java 34417 2009-07-23 14:42:56Z dkatayev $
*/
-public class TransferJavaBeanTest extends TestCase
+public class TransferJavaBeanTest extends JsonTest
{
@Override
@@ -71,7 +69,7 @@
jsonParser.parse(in, jsonHandler);
JsonValue jsonValue = jsonHandler.getJsonObject();
- Book newBook = (Book)new BeanBuilder().createObject(Book.class, jsonValue);
+ Book newBook = ObjectBuilder.createObject(Book.class, jsonValue);
assertEquals(author, newBook.getAuthor());
assertEquals(title, newBook.getTitle());
assertEquals(pages, newBook.getPages());
Modified: ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/groovy/GroovyBeanTest.java
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/groovy/GroovyBeanTest.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/java/org/exoplatform/ws/frameworks/json/impl/groovy/GroovyBeanTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -23,10 +23,10 @@
import junit.framework.TestCase;
import org.exoplatform.ws.frameworks.json.JsonHandler;
-import org.exoplatform.ws.frameworks.json.impl.BeanBuilder;
import org.exoplatform.ws.frameworks.json.impl.JsonDefaultHandler;
import org.exoplatform.ws.frameworks.json.impl.JsonGeneratorImpl;
import org.exoplatform.ws.frameworks.json.impl.JsonParserImpl;
+import org.exoplatform.ws.frameworks.json.impl.ObjectBuilder;
import org.exoplatform.ws.frameworks.json.value.JsonValue;
import org.exoplatform.ws.frameworks.json.value.impl.ObjectValue;
import org.exoplatform.ws.frameworks.json.value.impl.StringValue;
@@ -46,7 +46,7 @@
JsonValue ov = new ObjectValue();
StringValue sv = new StringValue("test restore groovy bean");
ov.addElement("value", sv);
- assertEquals("test restore groovy bean", new BeanBuilder().createObject(c, ov).toString());
+ assertEquals("test restore groovy bean", ObjectBuilder.createObject(c, ov).toString());
}
@SuppressWarnings("unchecked")
@@ -89,7 +89,7 @@
jsonParser.parse(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(
"BookStorage.txt")), jsonHandler);
JsonValue jv = jsonHandler.getJsonObject();
- GroovyObject o = (GroovyObject)new BeanBuilder().createObject(c, jv);
+ GroovyObject o = (GroovyObject)ObjectBuilder.createObject(c, jv);
//System.out.println(o);
List<GroovyObject> books = (List<GroovyObject>)o.getProperty("books");
assertEquals(3, books.size());
Deleted: ws/trunk/exo.ws.frameworks.json/src/test/resources/MultiDimension.txt
===================================================================
--- ws/trunk/exo.ws.frameworks.json/src/test/resources/MultiDimension.txt 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.frameworks.json/src/test/resources/MultiDimension.txt 2010-10-05 14:59:07 UTC (rev 3246)
@@ -1,36 +0,0 @@
-/* don't edit me */
-{
-"books":[
-[
- [ {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"}],
- [ {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"},
- {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"}]
-],
-[
- [ {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"},
- {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"}],
- [ {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"},
- {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"},
- {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"},
- {"title":"JUnit in Action","pages":386,"isdn":93011099534534,"price":19.37,"author":"Vincent Masson"},
- {"title":"Beginning C# 2008 from novice to professional","pages":511,"isdn":9781590598696,"price":23.56,"author":"Christian Gross"},
- {"title":"Advanced JavaScript. Third Edition","pages":617,"isdn":9781598220339,"price":25.99,"author":"Chuck Easttom"}]
-]
-]
-}
\ No newline at end of file
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/provider/JsonEntityProvider.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/provider/JsonEntityProvider.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/provider/JsonEntityProvider.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -19,15 +19,14 @@
package org.exoplatform.services.rest.impl.provider;
import org.exoplatform.services.rest.provider.EntityProvider;
-import org.exoplatform.ws.frameworks.json.JsonHandler;
-import org.exoplatform.ws.frameworks.json.JsonParser;
-import org.exoplatform.ws.frameworks.json.JsonWriter;
-import org.exoplatform.ws.frameworks.json.impl.BeanBuilder;
import org.exoplatform.ws.frameworks.json.impl.JsonDefaultHandler;
import org.exoplatform.ws.frameworks.json.impl.JsonException;
import org.exoplatform.ws.frameworks.json.impl.JsonGeneratorImpl;
import org.exoplatform.ws.frameworks.json.impl.JsonParserImpl;
+import org.exoplatform.ws.frameworks.json.impl.JsonUtils;
import org.exoplatform.ws.frameworks.json.impl.JsonWriterImpl;
+import org.exoplatform.ws.frameworks.json.impl.ObjectBuilder;
+import org.exoplatform.ws.frameworks.json.impl.JsonUtils.Types;
import org.exoplatform.ws.frameworks.json.value.JsonValue;
import java.io.IOException;
@@ -35,6 +34,8 @@
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
+import java.util.Collection;
+import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
@@ -71,19 +72,38 @@
/**
* {@inheritDoc}
*/
+ @SuppressWarnings("unchecked")
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException
{
try
{
- JsonParser jsonParser = new JsonParserImpl();
- JsonHandler jsonHandler = new JsonDefaultHandler();
- jsonParser.parse(entityStream, jsonHandler);
- JsonValue jsonValue = jsonHandler.getJsonObject();
- // jsonValue can be null if stream empty
- if (jsonValue == null)
- return null;
- return new BeanBuilder().createObject(type, jsonValue);
+ JsonParserImpl parser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+
+ parser.parse(entityStream, handler);
+ JsonValue jsonValue = handler.getJsonObject();
+
+ Types jtype = JsonUtils.getType(type);
+ if (jtype == Types.ARRAY_BOOLEAN || jtype == Types.ARRAY_BYTE || jtype == Types.ARRAY_SHORT
+ || jtype == Types.ARRAY_INT || jtype == Types.ARRAY_LONG || jtype == Types.ARRAY_FLOAT
+ || jtype == Types.ARRAY_DOUBLE || jtype == Types.ARRAY_CHAR || jtype == Types.ARRAY_STRING
+ || jtype == Types.ARRAY_OBJECT)
+ {
+ return ObjectBuilder.createArray(type, jsonValue);
+ }
+ if (jtype == Types.COLLECTION)
+ {
+ Class c = type;
+ return ObjectBuilder.createCollection(c, genericType, jsonValue);
+ }
+ if (jtype == Types.MAP)
+ {
+ Class c = type;
+ return ObjectBuilder.createObject(c, genericType, jsonValue);
+ }
+ return ObjectBuilder.createObject(type, jsonValue);
+
}
catch (Exception e)
{
@@ -111,14 +131,37 @@
/**
* {@inheritDoc}
*/
+ @SuppressWarnings("unchecked")
public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException
{
try
{
- JsonValue jv = new JsonGeneratorImpl().createJsonObject(t);
- JsonWriter jsonWriter = new JsonWriterImpl(entityStream);
- jv.writeTo(jsonWriter);
+ JsonGeneratorImpl generator = new JsonGeneratorImpl();
+ JsonValue jsonValue = null;
+ Types jtype = JsonUtils.getType(type);
+ if (jtype == Types.ARRAY_BOOLEAN || jtype == Types.ARRAY_BYTE || jtype == Types.ARRAY_SHORT
+ || jtype == Types.ARRAY_INT || jtype == Types.ARRAY_LONG || jtype == Types.ARRAY_FLOAT
+ || jtype == Types.ARRAY_DOUBLE || jtype == Types.ARRAY_CHAR || jtype == Types.ARRAY_STRING
+ || jtype == Types.ARRAY_OBJECT)
+ {
+ jsonValue = generator.createJsonArray(t);
+ }
+ else if (jtype == Types.COLLECTION)
+ {
+ jsonValue = generator.createJsonArray((Collection<?>)t);
+ }
+ else if (jtype == Types.MAP)
+ {
+ jsonValue = generator.createJsonObjectFromMap((Map<String, ?>)t);
+ }
+ else
+ {
+ jsonValue = generator.createJsonObject(t);
+ }
+
+ JsonWriterImpl jsonWriter = new JsonWriterImpl(entityStream);
+ jsonValue.writeTo(jsonWriter);
jsonWriter.flush();
}
catch (JsonException e)
Deleted: ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java 2010-10-05 11:33:24 UTC (rev 3245)
+++ ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2009 eXo Platform SAS.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.exoplatform.services.rest.impl.provider;
-
-import org.exoplatform.services.rest.BaseTest;
-import org.exoplatform.services.rest.generated.Book;
-import org.exoplatform.services.rest.impl.ContainerResponse;
-import org.exoplatform.services.rest.impl.MultivaluedMapImpl;
-import org.exoplatform.services.rest.tools.ByteArrayContainerResponseWriter;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MultivaluedMap;
-
-/**
- * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
- * @version $Id: $
- */
-public class JsonEntityTest extends BaseTest
-{
-
- @Path("/")
- public static class Resource1
- {
- @POST
- @Consumes("application/json")
- public void m1(Book book)
- {
- assertEquals("Hamlet", book.getTitle());
- assertEquals("William Shakespeare", book.getAuthor());
- assertTrue(book.isSendByPost());
- }
- }
-
- @Path("/")
- public static class Resource2
- {
- @GET
- @Produces("application/json")
- public Book m1()
- {
- Book book = new Book();
- book.setTitle("Hamlet");
- book.setAuthor("William Shakespeare");
- book.setSendByPost(true);
- return book;
- }
-
- // Without @Produces annotation also should work.
- @POST
- public Book m2()
- {
- Book book = new Book();
- book.setTitle("Hamlet\n");
- book.setAuthor("William Shakespeare\n");
- book.setSendByPost(false);
- return book;
- }
- }
-
- private byte[] jsonData;
-
- public void setUp() throws Exception
- {
- super.setUp();
- jsonData =
- ("{\"title\":\"Hamlet\"," + "\"author\":\"William Shakespeare\"," + "\"sendByPost\":true}").getBytes("UTF-8");
- }
-
- public void testJsonEntityParameter() throws Exception
- {
- Resource1 r1 = new Resource1();
- registry(r1);
- MultivaluedMap<String, String> h = new MultivaluedMapImpl();
- // Object is transfered via JSON
- h.putSingle("content-type", "application/json");
- // with JSON transformation for Book have restriction can't pass BigDecimal
- // (has not simple constructor and it is not in JSON known types)
- h.putSingle("content-length", "" + jsonData.length);
- assertEquals(204, launcher.service("POST", "/", "", h, jsonData, null).getStatus());
- unregistry(r1);
- }
-
- public void testJsonReturn() throws Exception
- {
- Resource2 r2 = new Resource2();
- registry(r2);
- MultivaluedMap<String, String> h = new MultivaluedMapImpl();
- h.putSingle("accept", "application/json");
- ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter();
-
- // Resource2#m1()
- ContainerResponse response = launcher.service("GET", "/", "", h, null, writer, null);
- assertEquals(200, response.getStatus());
- assertEquals("application/json", response.getContentType().toString());
- Book book = (Book)response.getEntity();
- assertEquals("Hamlet", book.getTitle());
- assertEquals("William Shakespeare", book.getAuthor());
- assertTrue(book.isSendByPost());
-
- // Resource2#m2()
- response = launcher.service("POST", "/", "", h, null, writer, null);
- assertEquals(200, response.getStatus());
- assertEquals("application/json", response.getContentType().toString());
- book = (Book)response.getEntity();
- assertEquals("Hamlet\n", book.getTitle());
- assertEquals("William Shakespeare\n", book.getAuthor());
- assertFalse(book.isSendByPost());
-// writer = new ByteArrayContainerResponseWriter();
- unregistry(r2);
- }
-
-}
Added: ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java (rev 0)
+++ ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java 2010-10-05 14:59:07 UTC (rev 3246)
@@ -0,0 +1,475 @@
+/*
+ * Copyright (C) 2009 eXo Platform SAS.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.exoplatform.services.rest.impl.provider;
+
+import org.exoplatform.services.rest.BaseTest;
+import org.exoplatform.services.rest.generated.Book;
+import org.exoplatform.services.rest.impl.ContainerResponse;
+import org.exoplatform.services.rest.impl.MultivaluedMapImpl;
+import org.exoplatform.services.rest.tools.ByteArrayContainerResponseWriter;
+import org.exoplatform.ws.frameworks.json.impl.JsonDefaultHandler;
+import org.exoplatform.ws.frameworks.json.impl.JsonParserImpl;
+import org.exoplatform.ws.frameworks.json.impl.ObjectBuilder;
+
+import java.io.ByteArrayInputStream;
+import java.lang.reflect.ParameterizedType;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MultivaluedMap;
+
+/**
+ * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+public class JsonEntityTest extends BaseTest
+{
+
+ @Path("/")
+ public static class ResourceBook
+ {
+ @POST
+ @Consumes("application/json")
+ public void m1(Book book)
+ {
+ assertEquals("Hamlet", book.getTitle());
+ assertEquals("William Shakespeare", book.getAuthor());
+ assertTrue(book.isSendByPost());
+ }
+ }
+
+ @Path("/")
+ public static class ResourceBookArray
+ {
+ @POST
+ @Consumes("application/json")
+ public void m1(Book[] b)
+ {
+ assertEquals("Hamlet", b[0].getTitle());
+ assertEquals("William Shakespeare", b[0].getAuthor());
+ assertTrue(b[0].isSendByPost());
+ assertEquals("Collected Stories", b[1].getTitle());
+ assertEquals("Gabriel Garcia Marquez", b[1].getAuthor());
+ assertTrue(b[1].isSendByPost());
+ }
+ }
+
+ @Path("/")
+ public static class ResourceBookCollection
+ {
+ @POST
+ @Consumes("application/json")
+ public void m1(List<Book> b)
+ {
+ assertEquals("Hamlet", b.get(0).getTitle());
+ assertEquals("William Shakespeare", b.get(0).getAuthor());
+ assertTrue(b.get(0).isSendByPost());
+ assertEquals("Collected Stories", b.get(1).getTitle());
+ assertEquals("Gabriel Garcia Marquez", b.get(1).getAuthor());
+ assertTrue(b.get(1).isSendByPost());
+ }
+ }
+
+ @Path("/")
+ public static class ResourceBookMap
+ {
+ @POST
+ @Consumes("application/json")
+ public void m1(Map<String, Book> b)
+ {
+ assertEquals("Hamlet", b.get("12345").getTitle());
+ assertEquals("William Shakespeare", b.get("12345").getAuthor());
+ assertTrue(b.get("12345").isSendByPost());
+ assertEquals("Collected Stories", b.get("54321").getTitle());
+ assertEquals("Gabriel Garcia Marquez", b.get("54321").getAuthor());
+ assertTrue(b.get("54321").isSendByPost());
+ }
+ }
+
+ @Path("/")
+ public static class ResourceBook2
+ {
+ @GET
+ @Produces("application/json")
+ public Book m1()
+ {
+ Book book = new Book();
+ book.setTitle("Hamlet");
+ book.setAuthor("William Shakespeare");
+ book.setSendByPost(true);
+ return book;
+ }
+
+ // Without @Produces annotation also should work.
+ @POST
+ public Book m2()
+ {
+ return m1();
+ }
+ }
+
+ @Path("/")
+ public static class ResourceBookArray2
+ {
+ @GET
+ @Produces("application/json")
+ public Book[] m1()
+ {
+ return createArray();
+ }
+
+ // Without @Produces annotation also should work.
+ @POST
+ public Book[] m2()
+ {
+ return createArray();
+ }
+
+ private Book[] createArray()
+ {
+ Book book1 = new Book();
+ book1.setTitle("Hamlet");
+ book1.setAuthor("William Shakespeare");
+ book1.setSendByPost(true);
+ Book book2 = new Book();
+ book2.setTitle("Collected Stories");
+ book2.setAuthor("Gabriel Garcia Marquez");
+ book2.setSendByPost(true);
+ return new Book[]{book1, book2};
+ }
+ }
+
+ @Path("/")
+ public static class ResourceBookCollection2
+ {
+ @GET
+ @Produces("application/json")
+ public List<Book> m1()
+ {
+ return createCollection();
+ }
+
+ // Without @Produces annotation also should work.
+ @POST
+ public List<Book> m2()
+ {
+ return createCollection();
+ }
+
+ private List<Book> createCollection()
+ {
+ Book book1 = new Book();
+ book1.setTitle("Hamlet");
+ book1.setAuthor("William Shakespeare");
+ book1.setSendByPost(true);
+ Book book2 = new Book();
+ book2.setTitle("Collected Stories");
+ book2.setAuthor("Gabriel Garcia Marquez");
+ book2.setSendByPost(true);
+ return Arrays.asList(book1, book2);
+ }
+ }
+
+ @Path("/")
+ public static class ResourceBookMap2
+ {
+ @GET
+ @Produces("application/json")
+ public Map<String, Book> m1()
+ {
+ return createMap();
+ }
+
+ // Without @Produces annotation also should work.
+ @POST
+ public Map<String, Book> m2()
+ {
+ return createMap();
+ }
+
+ private Map<String, Book> createMap()
+ {
+ Book book1 = new Book();
+ book1.setTitle("Hamlet");
+ book1.setAuthor("William Shakespeare");
+ book1.setSendByPost(true);
+ Book book2 = new Book();
+ book2.setTitle("Collected Stories");
+ book2.setAuthor("Gabriel Garcia Marquez");
+ book2.setSendByPost(true);
+ Map<String, Book> m = new HashMap<String, Book>();
+ m.put("12345", book1);
+ m.put("54321", book2);
+ return m;
+ }
+ }
+
+ private byte[] jsonBookData;
+
+ private byte[] jsonArrayData;
+
+ private byte[] jsonMapData;
+
+ public void setUp() throws Exception
+ {
+ super.setUp();
+ jsonBookData =
+ ("{\"title\":\"Hamlet\", \"author\":\"William Shakespeare\", \"sendByPost\":true}").getBytes("UTF-8");
+ jsonArrayData =
+ ("[{\"title\":\"Hamlet\", \"author\":\"William Shakespeare\", \"sendByPost\":true},"
+ + "{\"title\":\"Collected Stories\", \"author\":\"Gabriel Garcia Marquez\", \"sendByPost\":true}]")
+ .getBytes("UTF-8");
+ jsonMapData =
+ ("{\"12345\":{\"title\":\"Hamlet\", \"author\":\"William Shakespeare\", \"sendByPost\":true},"
+ + "\"54321\":{\"title\":\"Collected Stories\", \"author\":\"Gabriel Garcia Marquez\", \"sendByPost\":true}}")
+ .getBytes("UTF-8");
+ }
+
+ public void testJsonEntityBean() throws Exception
+ {
+ ResourceBook r1 = new ResourceBook();
+ registry(r1);
+ MultivaluedMap<String, String> h = new MultivaluedMapImpl();
+ // Object is transfered via JSON
+ h.putSingle("content-type", "application/json");
+ // with JSON transformation for Book have restriction can't pass BigDecimal
+ // (has not simple constructor and it is not in JSON known types)
+ h.putSingle("content-length", "" + jsonBookData.length);
+ assertEquals(204, launcher.service("POST", "/", "", h, jsonBookData, null).getStatus());
+ unregistry(r1);
+ }
+
+ public void testJsonEntityArray() throws Exception
+ {
+ ResourceBookArray r1 = new ResourceBookArray();
+ registry(r1);
+ MultivaluedMap<String, String> h = new MultivaluedMapImpl();
+ // Object is transfered via JSON
+ h.putSingle("content-type", "application/json");
+ h.putSingle("content-length", "" + jsonArrayData.length);
+ assertEquals(204, launcher.service("POST", "/", "", h, jsonArrayData, null).getStatus());
+ unregistry(r1);
+ }
+
+ public void testJsonEntityCollection() throws Exception
+ {
+ ResourceBookCollection r1 = new ResourceBookCollection();
+ registry(r1);
+ MultivaluedMap<String, String> h = new MultivaluedMapImpl();
+ // Object is transfered via JSON
+ h.putSingle("content-type", "application/json");
+ h.putSingle("content-length", "" + jsonArrayData.length);
+ assertEquals(204, launcher.service("POST", "/", "", h, jsonArrayData, null).getStatus());
+ unregistry(r1);
+ }
+
+ public void testJsonEntityMap() throws Exception
+ {
+ ResourceBookMap r1 = new ResourceBookMap();
+ registry(r1);
+ MultivaluedMap<String, String> h = new MultivaluedMapImpl();
+ // Object is transfered via JSON
+ h.putSingle("content-type", "application/json");
+ h.putSingle("content-length", "" + jsonMapData.length);
+ assertEquals(204, launcher.service("POST", "/", "", h, jsonMapData, null).getStatus());
+ unregistry(r1);
+ }
+
+ public void testJsonReturnBean() throws Exception
+ {
+ ResourceBook2 r2 = new ResourceBook2();
+ registry(r2);
+ MultivaluedMap<String, String> h = new MultivaluedMapImpl();
+ h.putSingle("accept", "application/json");
+ ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter();
+
+ // ResourceBook2#m1()
+ ContainerResponse response = launcher.service("GET", "/", "", h, null, writer, null);
+ assertEquals(200, response.getStatus());
+ assertEquals("application/json", response.getContentType().toString());
+ JsonParserImpl parser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ parser.parse(new ByteArrayInputStream(writer.getBody()), handler);
+ Book book = ObjectBuilder.createObject(Book.class, handler.getJsonObject());
+ assertEquals("Hamlet", book.getTitle());
+ assertEquals("William Shakespeare", book.getAuthor());
+ assertTrue(book.isSendByPost());
+
+ // ResourceBook2#m2()
+ writer.reset();
+ handler.reset();
+ response = launcher.service("POST", "/", "", h, null, writer, null);
+ assertEquals(200, response.getStatus());
+ assertEquals("application/json", response.getContentType().toString());
+ parser.parse(new ByteArrayInputStream(writer.getBody()), handler);
+ book = ObjectBuilder.createObject(Book.class, handler.getJsonObject());
+ assertEquals("Hamlet", book.getTitle());
+ assertEquals("William Shakespeare", book.getAuthor());
+ assertTrue(book.isSendByPost());
+
+ unregistry(r2);
+ }
+
+ public void testJsonReturnBeanArray() throws Exception
+ {
+ ResourceBookArray2 r2 = new ResourceBookArray2();
+ registry(r2);
+ MultivaluedMap<String, String> h = new MultivaluedMapImpl();
+ h.putSingle("accept", "application/json");
+ ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter();
+
+ // ResourceBookArray2#m1()
+ ContainerResponse response = launcher.service("GET", "/", "", h, null, writer, null);
+ assertEquals(200, response.getStatus());
+ assertEquals("application/json", response.getContentType().toString());
+ JsonParserImpl parser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ parser.parse(new ByteArrayInputStream(writer.getBody()), handler);
+ Book[] book = (Book[])ObjectBuilder.createArray(new Book[0].getClass(), handler.getJsonObject());
+ assertEquals("Hamlet", book[0].getTitle());
+ assertEquals("William Shakespeare", book[0].getAuthor());
+ assertTrue(book[0].isSendByPost());
+ assertEquals("Collected Stories", book[1].getTitle());
+ assertEquals("Gabriel Garcia Marquez", book[1].getAuthor());
+ assertTrue(book[1].isSendByPost());
+ //System.out.println("array: " + new String(writer.getBody()));
+
+ // ResourceBookArray2#m2()
+ writer.reset();
+ handler.reset();
+ response = launcher.service("POST", "/", "", h, null, writer, null);
+ assertEquals(200, response.getStatus());
+ assertEquals("application/json", response.getContentType().toString());
+ parser.parse(new ByteArrayInputStream(writer.getBody()), handler);
+ book = (Book[])ObjectBuilder.createArray(new Book[0].getClass(), handler.getJsonObject());
+ assertEquals("Hamlet", book[0].getTitle());
+ assertEquals("William Shakespeare", book[0].getAuthor());
+ assertTrue(book[0].isSendByPost());
+ assertEquals("Collected Stories", book[1].getTitle());
+ assertEquals("Gabriel Garcia Marquez", book[1].getAuthor());
+ assertTrue(book[1].isSendByPost());
+ //System.out.println("array: " + new String(writer.getBody()));
+
+ unregistry(r2);
+ }
+
+ @SuppressWarnings({"unchecked", "serial"})
+ public void testJsonReturnBeanCollection() throws Exception
+ {
+ ResourceBookCollection2 r2 = new ResourceBookCollection2();
+ registry(r2);
+ MultivaluedMap<String, String> h = new MultivaluedMapImpl();
+ h.putSingle("accept", "application/json");
+ ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter();
+
+ // ResourceBookCollection2#m1()
+ ContainerResponse response = launcher.service("GET", "/", "", h, null, writer, null);
+ assertEquals(200, response.getStatus());
+ assertEquals("application/json", response.getContentType().toString());
+ JsonParserImpl parser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ parser.parse(new ByteArrayInputStream(writer.getBody()), handler);
+ ParameterizedType genericType = (ParameterizedType)new ArrayList<Book>()
+ {
+ }.getClass().getGenericSuperclass();
+ //System.out.println(">>>>>"+genericType);
+ List<Book> book = ObjectBuilder.createCollection(List.class, genericType, handler.getJsonObject());
+ assertEquals("Hamlet", book.get(0).getTitle());
+ assertEquals("William Shakespeare", book.get(0).getAuthor());
+ assertTrue(book.get(0).isSendByPost());
+ assertEquals("Collected Stories", book.get(1).getTitle());
+ assertEquals("Gabriel Garcia Marquez", book.get(1).getAuthor());
+ assertTrue(book.get(1).isSendByPost());
+ //System.out.println("collection: " + new String(writer.getBody()));
+
+ // ResourceBookCollection2#m2()
+ writer.reset();
+ handler.reset();
+ response = launcher.service("POST", "/", "", h, null, writer, null);
+ assertEquals(200, response.getStatus());
+ assertEquals("application/json", response.getContentType().toString());
+ parser.parse(new ByteArrayInputStream(writer.getBody()), handler);
+ book = ObjectBuilder.createCollection(List.class, genericType, handler.getJsonObject());
+ assertEquals("Hamlet", book.get(0).getTitle());
+ assertEquals("William Shakespeare", book.get(0).getAuthor());
+ assertTrue(book.get(0).isSendByPost());
+ assertEquals("Collected Stories", book.get(1).getTitle());
+ assertEquals("Gabriel Garcia Marquez", book.get(1).getAuthor());
+ assertTrue(book.get(1).isSendByPost());
+ //System.out.println("collection: " + new String(writer.getBody()));
+
+ unregistry(r2);
+ }
+
+ @SuppressWarnings({"unchecked", "serial"})
+ public void testJsonReturnBeanMap() throws Exception
+ {
+ ResourceBookMap2 r2 = new ResourceBookMap2();
+ registry(r2);
+ MultivaluedMap<String, String> h = new MultivaluedMapImpl();
+ h.putSingle("accept", "application/json");
+ ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter();
+
+ // ResourceBookMap2#m1()
+ ContainerResponse response = launcher.service("GET", "/", "", h, null, writer, null);
+ assertEquals(200, response.getStatus());
+ assertEquals("application/json", response.getContentType().toString());
+ JsonParserImpl parser = new JsonParserImpl();
+ JsonDefaultHandler handler = new JsonDefaultHandler();
+ parser.parse(new ByteArrayInputStream(writer.getBody()), handler);
+ ParameterizedType genericType = (ParameterizedType)new HashMap<String, Book>()
+ {
+ }.getClass().getGenericSuperclass();
+ //System.out.println(">>>>>" + genericType);
+ Map<String, Book> book = ObjectBuilder.createObject(Map.class, genericType, handler.getJsonObject());
+ assertEquals("Hamlet", book.get("12345").getTitle());
+ assertEquals("William Shakespeare", book.get("12345").getAuthor());
+ assertTrue(book.get("12345").isSendByPost());
+ assertEquals("Collected Stories", book.get("54321").getTitle());
+ assertEquals("Gabriel Garcia Marquez", book.get("54321").getAuthor());
+ assertTrue(book.get("54321").isSendByPost());
+ //System.out.println("map: " + new String(writer.getBody()));
+
+ // ResourceBookMap2#m2()
+ writer.reset();
+ handler.reset();
+ response = launcher.service("POST", "/", "", h, null, writer, null);
+ assertEquals(200, response.getStatus());
+ assertEquals("application/json", response.getContentType().toString());
+ parser.parse(new ByteArrayInputStream(writer.getBody()), handler);
+ book = ObjectBuilder.createObject(Map.class, genericType, handler.getJsonObject());
+ assertEquals("Hamlet", book.get("12345").getTitle());
+ assertEquals("William Shakespeare", book.get("12345").getAuthor());
+ assertTrue(book.get("12345").isSendByPost());
+ assertEquals("Collected Stories", book.get("54321").getTitle());
+ assertEquals("Gabriel Garcia Marquez", book.get("54321").getAuthor());
+ assertTrue(book.get("54321").isSendByPost());
+ //System.out.println("map: " + new String(writer.getBody()));
+
+ unregistry(r2);
+ }
+}
Property changes on: ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/provider/JsonEntityTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
More information about the exo-jcr-commits
mailing list