You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pivot.apache.org by gb...@apache.org on 2010/06/10 21:26:43 UTC

svn commit: r953424 - in /pivot/trunk: core/src/org/apache/pivot/json/ core/src/org/apache/pivot/serialization/ core/test/org/apache/pivot/json/test/ tutorials-server/src/org/apache/pivot/tutorials/webqueries/server/

Author: gbrown
Date: Thu Jun 10 19:26:42 2010
New Revision: 953424

URL: http://svn.apache.org/viewvc?rev=953424&view=rev
Log:
Merge in JSON/bean binding changes from 1.5.1 tree.

Modified:
    pivot/trunk/core/src/org/apache/pivot/json/JSON.java
    pivot/trunk/core/src/org/apache/pivot/json/JSONSerializer.java
    pivot/trunk/core/src/org/apache/pivot/serialization/CSVSerializer.java
    pivot/trunk/core/test/org/apache/pivot/json/test/BindTest.java
    pivot/trunk/core/test/org/apache/pivot/json/test/SampleBean.java
    pivot/trunk/core/test/org/apache/pivot/json/test/sample.json
    pivot/trunk/tutorials-server/src/org/apache/pivot/tutorials/webqueries/server/ExpenseServlet.java

Modified: pivot/trunk/core/src/org/apache/pivot/json/JSON.java
URL: http://svn.apache.org/viewvc/pivot/trunk/core/src/org/apache/pivot/json/JSON.java?rev=953424&r1=953423&r2=953424&view=diff
==============================================================================
--- pivot/trunk/core/src/org/apache/pivot/json/JSON.java (original)
+++ pivot/trunk/core/src/org/apache/pivot/json/JSON.java Thu Jun 10 19:26:42 2010
@@ -16,10 +16,6 @@
  */
 package org.apache.pivot.json;
 
-import java.lang.reflect.Array;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-
 import org.apache.pivot.beans.BeanAdapter;
 import org.apache.pivot.collections.ArrayList;
 import org.apache.pivot.collections.Dictionary;
@@ -455,139 +451,4 @@ public class JSON {
 
         return keys;
     }
-
-    /**
-     * Binds a JSON value to a Java type.
-     *
-     * @param source
-     * The source value.
-     *
-     * @param type
-     * The Java class to which to which the value will be bound.
-     *
-     * @return
-     * The bound instance of the Java type.
-     */
-    @SuppressWarnings("unchecked")
-    public static <T> T bind(Object source, Class<? extends T> targetType) {
-        return (T)bind(source, (Type)targetType);
-    }
-
-    @SuppressWarnings("unchecked")
-    private static <T> T bind(Object source, Type targetType) {
-        if (targetType == null) {
-            throw new IllegalArgumentException();
-        }
-
-        Object target;
-        if (source == null) {
-            target = null;
-        } else if (source instanceof Boolean
-            || source instanceof Number
-            || source instanceof String) {
-            if (!(targetType instanceof Class<?>)) {
-                throw new IllegalArgumentException(source + " cannot be bound to " + targetType + ".");
-            }
-
-            target = BeanAdapter.coerce(source, (Class<?>)targetType);
-        } else if (source instanceof List<?>) {
-            List<?> sourceList = (List<?>)source;
-
-            if (targetType instanceof ParameterizedType) {
-                // Instantiate the target sequence
-                ParameterizedType parameterizedType = (ParameterizedType)targetType;
-                Class<?> rawType = (Class<?>)parameterizedType.getRawType();
-                if (!Sequence.class.isAssignableFrom(rawType)) {
-                    throw new IllegalArgumentException(source + " cannot be bound to "
-                        + rawType.getName() + ".");
-                }
-
-                try {
-                    target = rawType.newInstance();
-                } catch (InstantiationException exception) {
-                    throw new RuntimeException(exception);
-                } catch (IllegalAccessException exception) {
-                    throw new RuntimeException(exception);
-                }
-
-                Sequence<Object> targetSequence = (Sequence<Object>)target;
-
-                // Get the target item type
-                Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
-                Type targetItemType = actualTypeArguments[0];
-
-                // Populate the sequence
-                for (Object item : sourceList) {
-                    targetSequence.add(bind(item, targetItemType));
-                }
-            } else {
-                Class<?> targetClass = (Class<?>)targetType;
-                if (!targetClass.isArray()) {
-                    throw new IllegalArgumentException(source + " cannot be bound to "
-                        + targetClass.getName() + ".");
-                }
-
-                // Instantiate the target array
-                Class<?> targetComponentType = targetClass.getComponentType();
-                target = Array.newInstance(targetComponentType, sourceList.getLength());
-
-                // Populate the array
-                int i = 0;
-                for (Object item : sourceList) {
-                    Array.set(target, i++, bind(item, targetComponentType));
-                }
-            }
-        } else if (source instanceof Map<?, ?>) {
-            Map<String, ?> sourceMap = (Map<String, ?>)source;
-
-            if (targetType instanceof ParameterizedType) {
-                // Instantiate the target dictionary
-                ParameterizedType parameterizedType = (ParameterizedType)targetType;
-                Class<?> rawType = (Class<?>)parameterizedType.getRawType();
-                if (!Dictionary.class.isAssignableFrom(rawType)) {
-                    throw new IllegalArgumentException(source + " cannot be bound to "
-                        + rawType.getName() + ".");
-                }
-
-                try {
-                    target = rawType.newInstance();
-                } catch (InstantiationException exception) {
-                    throw new RuntimeException(exception);
-                } catch (IllegalAccessException exception) {
-                    throw new RuntimeException(exception);
-                }
-
-                Dictionary<String, Object> targetDictionary = (Dictionary<String, Object>)target;
-
-                // Get the target value type
-                Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
-                Type targetValueType = actualTypeArguments[1];
-
-                // Populate the dictionary
-                for (String key : sourceMap) {
-                    targetDictionary.put(key, bind(sourceMap.get(key), targetValueType));
-                }
-            } else {
-                Class<?> targetClass = (Class<?>)targetType;
-
-                try {
-                    target = targetClass.newInstance();
-                } catch (InstantiationException exception) {
-                    throw new RuntimeException(exception);
-                } catch (IllegalAccessException exception) {
-                    throw new RuntimeException(exception);
-                }
-
-                BeanAdapter targetAdapter = new BeanAdapter(target);
-
-                for (String key : sourceMap) {
-                    targetAdapter.put(key, bind(sourceMap.get(key), targetAdapter.getGenericType(key)));
-                }
-            }
-        } else {
-            throw new IllegalArgumentException(source.getClass() + " is not a supported source type.");
-        }
-
-        return (T)target;
-    }
 }

Modified: pivot/trunk/core/src/org/apache/pivot/json/JSONSerializer.java
URL: http://svn.apache.org/viewvc/pivot/trunk/core/src/org/apache/pivot/json/JSONSerializer.java?rev=953424&r1=953423&r2=953424&view=diff
==============================================================================
--- pivot/trunk/core/src/org/apache/pivot/json/JSONSerializer.java (original)
+++ pivot/trunk/core/src/org/apache/pivot/json/JSONSerializer.java Thu Jun 10 19:26:42 2010
@@ -28,15 +28,17 @@ import java.io.Reader;
 import java.io.StringReader;
 import java.io.StringWriter;
 import java.io.Writer;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
 import java.nio.charset.Charset;
 
 import org.apache.pivot.beans.BeanAdapter;
 import org.apache.pivot.collections.ArrayList;
+import org.apache.pivot.collections.Dictionary;
 import org.apache.pivot.collections.HashMap;
 import org.apache.pivot.collections.List;
 import org.apache.pivot.collections.Map;
-import org.apache.pivot.collections.immutable.ImmutableList;
-import org.apache.pivot.collections.immutable.ImmutableMap;
+import org.apache.pivot.collections.Sequence;
 import org.apache.pivot.io.EchoReader;
 import org.apache.pivot.io.EchoWriter;
 import org.apache.pivot.serialization.SerializationException;
@@ -48,7 +50,7 @@ import org.apache.pivot.serialization.Se
  */
 public class JSONSerializer implements Serializer<Object> {
     private Charset charset;
-    private boolean immutable;
+    private Class<?> type;
 
     private int c = -1;
     private boolean alwaysDelimitMapKeys = false;
@@ -59,24 +61,24 @@ public class JSONSerializer implements S
     public static final int BUFFER_SIZE = 2048;
 
     public JSONSerializer() {
-        this(Charset.forName(DEFAULT_CHARSET_NAME), false);
+        this(Charset.forName(DEFAULT_CHARSET_NAME), Object.class);
     }
 
     public JSONSerializer(Charset charset) {
-        this(charset, false);
+        this(charset, Object.class);
     }
 
-    public JSONSerializer(boolean immutable) {
-        this(Charset.forName(DEFAULT_CHARSET_NAME), immutable);
+    public JSONSerializer(Class<?> type) {
+        this(Charset.forName(DEFAULT_CHARSET_NAME), type);
     }
 
-    public JSONSerializer(Charset charset, boolean immutable) {
+    public JSONSerializer(Charset charset, Class<?> type) {
         if (charset == null) {
             throw new IllegalArgumentException("charset is null.");
         }
 
         this.charset = charset;
-        this.immutable = immutable;
+        this.type = type;
     }
 
     /**
@@ -87,13 +89,10 @@ public class JSONSerializer implements S
     }
 
     /**
-     * Returns the serializer's immutable flag.
-     *
-     * @return
-     * If <tt>true</tt>, all list and map values will be wrapped in an immutable equivalent.
+     * Returns the type of the object that will be returned by {@link #readObject(Reader)}.
      */
-    public boolean isImmutable() {
-        return immutable;
+    public Class<?> getType() {
+        return type;
     }
 
     /**
@@ -186,7 +185,7 @@ public class JSONSerializer implements S
         Object object;
 
         try {
-            object = readValue(lineNumberReader);
+            object = readValue(lineNumberReader, type);
         } catch (SerializationException exception) {
             System.err.println("An error occurred while processing input at line number "
                 + (lineNumberReader.getLineNumber() + 1));
@@ -194,12 +193,10 @@ public class JSONSerializer implements S
             throw exception;
         }
 
-        lineNumberReader = null;
-
         return object;
     }
 
-    private Object readValue(Reader reader)
+    private Object readValue(Reader reader, Type type)
         throws IOException, SerializationException {
         Object object = null;
 
@@ -212,15 +209,15 @@ public class JSONSerializer implements S
         if (c == 'n') {
             object = readNull(reader);
         } else if (c == '"' || c == '\'') {
-            object = readString(reader);
+            object = readString(reader, type);
         } else if (c == '+' || c == '-' || Character.isDigit(c)) {
-            object = readNumber(reader);
+            object = readNumber(reader, type);
         } else if (c == 't' || c == 'f') {
-            object = readBoolean(reader);
+            object = readBoolean(reader, type);
         } else if (c == '[') {
-            object = readList(reader);
+            object = readList(reader, type);
         } else if (c == '{') {
-            object = readMap(reader);
+            object = readMap(reader, type);
         } else {
             throw new SerializationException("Unexpected character in input stream.");
         }
@@ -297,8 +294,12 @@ public class JSONSerializer implements S
         return null;
     }
 
-    private String readString(Reader reader)
+    private Object readString(Reader reader, Type type)
         throws IOException, SerializationException {
+        if (!(type instanceof Class<?>)) {
+            throw new SerializationException("Cannot convert string to " + type + ".");
+        }
+
         StringBuilder stringBuilder = new StringBuilder();
 
         // Use the same delimiter to close the string
@@ -355,10 +356,15 @@ public class JSONSerializer implements S
         // Move to the next character after the delimiter
         c = reader.read();
 
-        return stringBuilder.toString();
+        return BeanAdapter.coerce(stringBuilder.toString(), (Class<?>)type);
     }
 
-    private Number readNumber(Reader reader) throws IOException {
+    private Object readNumber(Reader reader, Type type)
+        throws IOException, SerializationException {
+        if (!(type instanceof Class<?>)) {
+            throw new SerializationException("Cannot convert number to " + type + ".");
+        }
+
         Number number = null;
 
         StringBuilder stringBuilder = new StringBuilder();
@@ -392,17 +398,21 @@ public class JSONSerializer implements S
             number = Double.parseDouble(stringBuilder.toString()) * (negative ? -1.0d : 1.0d);
         }
 
-        return number;
+        return BeanAdapter.coerce(number, (Class<?>)type);
     }
 
-    private Boolean readBoolean(Reader reader)
+    private Object readBoolean(Reader reader, Type type)
         throws IOException, SerializationException {
-        String booleanString = (c == 't') ? "true" : "false";
-        int n = booleanString.length();
+        if (!(type instanceof Class<?>)) {
+            throw new SerializationException("Cannot convert number to " + type + ".");
+        }
+
+        String text = (c == 't') ? "true" : "false";
+        int n = text.length();
         int i = 0;
 
         while (c != -1 && i < n) {
-            if (booleanString.charAt(i) != c) {
+            if (text.charAt(i) != c) {
                 throw new SerializationException("Unexpected character in input stream.");
             }
 
@@ -414,19 +424,47 @@ public class JSONSerializer implements S
             throw new SerializationException("Incomplete boolean value in input stream.");
         }
 
-        return Boolean.parseBoolean(booleanString);
+        return BeanAdapter.coerce(Boolean.parseBoolean(text), (Class<?>)type);
     }
 
-    private List<Object> readList(Reader reader)
+    @SuppressWarnings("unchecked")
+    private Object readList(Reader reader, Type type)
         throws IOException, SerializationException {
-        List<Object> list = new ArrayList<Object>();
+        Sequence<Object> sequence;
+        Type itemType;
+
+        if (type instanceof ParameterizedType) {
+            ParameterizedType parameterizedType = (ParameterizedType)type;
+            Class<?> rawType = (Class<?>)parameterizedType.getRawType();
+            if (!Sequence.class.isAssignableFrom(rawType)) {
+                throw new IllegalArgumentException("Cannot convert array to "
+                    + rawType.getName() + ".");
+            }
+
+            try {
+                sequence = (Sequence<Object>)rawType.newInstance();
+            } catch (InstantiationException exception) {
+                throw new RuntimeException(exception);
+            } catch (IllegalAccessException exception) {
+                throw new RuntimeException(exception);
+            }
+
+            // Get the target item type
+            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
+            itemType = actualTypeArguments[0];
+        } else if (type == Object.class) {
+            sequence = new ArrayList<Object>();
+            itemType = Object.class;
+        } else {
+            throw new IllegalArgumentException("Cannot convert array to " + type + ".");
+        }
 
         // Move to the next character after '['
         c = reader.read();
         skipWhitespaceAndComments(reader);
 
         while (c != -1 && c != ']') {
-            list.add(readValue(reader));
+            sequence.add(readValue(reader, itemType));
             skipWhitespaceAndComments(reader);
 
             if (c == ',') {
@@ -444,16 +482,50 @@ public class JSONSerializer implements S
         // Move to the next character after ']'
         c = reader.read();
 
-        if (immutable) {
-            list = new ImmutableList<Object>(list);
-        }
-
-        return list;
+        return sequence;
     }
 
-    private Map<String, Object> readMap(Reader reader)
+    @SuppressWarnings("unchecked")
+    private Object readMap(Reader reader, Type type)
         throws IOException, SerializationException {
-        Map<String, Object> map = new HashMap<String, Object>();
+        Dictionary<String, Object> dictionary;
+        Type valueType;
+
+        if (type instanceof ParameterizedType) {
+            // Instantiate the target dictionary
+            ParameterizedType parameterizedType = (ParameterizedType)type;
+            Class<?> rawType = (Class<?>)parameterizedType.getRawType();
+            if (!Dictionary.class.isAssignableFrom(rawType)) {
+                throw new IllegalArgumentException("Cannot convert object to "
+                    + rawType.getName() + ".");
+            }
+
+            try {
+                dictionary = (Dictionary<String, Object>)rawType.newInstance();
+            } catch (InstantiationException exception) {
+                throw new RuntimeException(exception);
+            } catch (IllegalAccessException exception) {
+                throw new RuntimeException(exception);
+            }
+
+            // Get the target value type
+            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
+            valueType = actualTypeArguments[1];
+        } else if (type == Object.class){
+            dictionary = new HashMap<String, Object>();
+            valueType = Object.class;
+        } else {
+            Class<?> beanType = (Class<?>)type;
+            try {
+                dictionary = new BeanAdapter(beanType.newInstance());
+            } catch (InstantiationException exception) {
+                throw new RuntimeException(exception);
+            } catch (IllegalAccessException exception) {
+                throw new RuntimeException(exception);
+            }
+
+            valueType = null;
+        }
 
         // Move to the next character after '{'
         c = reader.read();
@@ -464,7 +536,7 @@ public class JSONSerializer implements S
 
             if (c == '"' || c == '\'') {
                 // The key is a delimited string
-                key = readString(reader);
+                key = (String)readString(reader, String.class);
             } else {
                 // The key is an undelimited string; it must adhere to Java
                 // identifier syntax
@@ -504,8 +576,9 @@ public class JSONSerializer implements S
 
             // Move to the first character after ':'
             c = reader.read();
+            dictionary.put(key, readValue(reader, (valueType == null) ?
+                ((BeanAdapter)dictionary).getGenericType(key) : valueType));
 
-            map.put(key, readValue(reader));
             skipWhitespaceAndComments(reader);
 
             if (c == ',') {
@@ -523,11 +596,7 @@ public class JSONSerializer implements S
         // Move to the first character after '}'
         c = reader.read();
 
-        if (immutable) {
-            map = new ImmutableMap<String, Object>(map);
-        }
-
-        return map;
+        return (dictionary instanceof BeanAdapter) ? ((BeanAdapter)dictionary).getBean() : dictionary;
     }
 
     /**

Modified: pivot/trunk/core/src/org/apache/pivot/serialization/CSVSerializer.java
URL: http://svn.apache.org/viewvc/pivot/trunk/core/src/org/apache/pivot/serialization/CSVSerializer.java?rev=953424&r1=953423&r2=953424&view=diff
==============================================================================
--- pivot/trunk/core/src/org/apache/pivot/serialization/CSVSerializer.java (original)
+++ pivot/trunk/core/src/org/apache/pivot/serialization/CSVSerializer.java Thu Jun 10 19:26:42 2010
@@ -273,8 +273,6 @@ public class CSVSerializer implements Se
             throw exception;
         }
 
-        lineNumberReader = null;
-
         return items;
     }
 

Modified: pivot/trunk/core/test/org/apache/pivot/json/test/BindTest.java
URL: http://svn.apache.org/viewvc/pivot/trunk/core/test/org/apache/pivot/json/test/BindTest.java?rev=953424&r1=953423&r2=953424&view=diff
==============================================================================
--- pivot/trunk/core/test/org/apache/pivot/json/test/BindTest.java (original)
+++ pivot/trunk/core/test/org/apache/pivot/json/test/BindTest.java Thu Jun 10 19:26:42 2010
@@ -28,9 +28,11 @@ import org.junit.Test;
 public class BindTest {
     @Test
     public void testBind() throws IOException, SerializationException {
-        JSONSerializer jsonSerializer = new JSONSerializer();
-        Object sampleObject = jsonSerializer.readObject(getClass().getResourceAsStream("sample.json"));
-        SampleBean sampleBean = JSON.bind(sampleObject, SampleBean.class);
+        JSONSerializer objectSerializer = new JSONSerializer();
+        Object sampleObject = objectSerializer.readObject(getClass().getResourceAsStream("sample.json"));
+
+        JSONSerializer beanSerializer = new JSONSerializer(SampleBean.class);
+        SampleBean sampleBean = (SampleBean)beanSerializer.readObject(getClass().getResourceAsStream("sample.json"));
 
         assertEquals(sampleBean.getA(), JSON.get(sampleObject, "a"));
         assertEquals(sampleBean.getB(), JSON.get(sampleObject, "b"));
@@ -38,6 +40,5 @@ public class BindTest {
         assertEquals(sampleBean.getD(), JSON.get(sampleObject, "d"));
         assertEquals(sampleBean.getE(), JSON.get(sampleObject, "e"));
         assertEquals(sampleBean.getI().getA(), JSON.get(sampleObject, "i.a"));
-        assertEquals(sampleBean.getJ()[0], JSON.get(sampleObject, "j[0]"));
     }
 }

Modified: pivot/trunk/core/test/org/apache/pivot/json/test/SampleBean.java
URL: http://svn.apache.org/viewvc/pivot/trunk/core/test/org/apache/pivot/json/test/SampleBean.java?rev=953424&r1=953423&r2=953424&view=diff
==============================================================================
--- pivot/trunk/core/test/org/apache/pivot/json/test/SampleBean.java (original)
+++ pivot/trunk/core/test/org/apache/pivot/json/test/SampleBean.java Thu Jun 10 19:26:42 2010
@@ -26,7 +26,6 @@ public class SampleBean {
     private ArrayList<String> d = null;
     private HashMap<String, Integer> e = null;
     private SampleBean i = null;
-    private int[] j = null;
 
     public int getA() {
         return a;
@@ -75,12 +74,4 @@ public class SampleBean {
     public void setI(SampleBean i) {
         this.i = i;
     }
-
-    public int[] getJ() {
-        return j;
-    }
-
-    public void setJ(int[] j) {
-        this.j = j;
-    }
 }

Modified: pivot/trunk/core/test/org/apache/pivot/json/test/sample.json
URL: http://svn.apache.org/viewvc/pivot/trunk/core/test/org/apache/pivot/json/test/sample.json?rev=953424&r1=953423&r2=953424&view=diff
==============================================================================
--- pivot/trunk/core/test/org/apache/pivot/json/test/sample.json (original)
+++ pivot/trunk/core/test/org/apache/pivot/json/test/sample.json Thu Jun 10 19:26:42 2010
@@ -19,6 +19,5 @@
     c: false,
     d: ["1", "2", "3"],
     e: {f: 4, g: 5, h: 6},
-    i: { a: 200, b: "Goodbye", c: true},
-    j: [10, 20, 30]
+    i: { a: 200, b: "Goodbye", c: true}
 }

Modified: pivot/trunk/tutorials-server/src/org/apache/pivot/tutorials/webqueries/server/ExpenseServlet.java
URL: http://svn.apache.org/viewvc/pivot/trunk/tutorials-server/src/org/apache/pivot/tutorials/webqueries/server/ExpenseServlet.java?rev=953424&r1=953423&r2=953424&view=diff
==============================================================================
--- pivot/trunk/tutorials-server/src/org/apache/pivot/tutorials/webqueries/server/ExpenseServlet.java (original)
+++ pivot/trunk/tutorials-server/src/org/apache/pivot/tutorials/webqueries/server/ExpenseServlet.java Thu Jun 10 19:26:42 2010
@@ -25,7 +25,6 @@ import javax.servlet.ServletException;
 
 import org.apache.pivot.collections.HashMap;
 import org.apache.pivot.collections.List;
-import org.apache.pivot.json.JSON;
 import org.apache.pivot.json.JSONSerializer;
 import org.apache.pivot.serialization.CSVSerializer;
 import org.apache.pivot.serialization.SerializationException;
@@ -103,8 +102,7 @@ public class ExpenseServlet extends Quer
             throw new QueryException(Query.Status.BAD_REQUEST);
         }
 
-        // Create the new expense and bind the data to it
-        Expense expense = JSON.bind(value, Expense.class);
+        Expense expense = (Expense)value;
 
         // Add the expense to the list/map
         int id;
@@ -137,7 +135,7 @@ public class ExpenseServlet extends Quer
         int id = Integer.parseInt(path.get(0));
 
         // Create the new expense and bind the data to it
-        Expense expense = JSON.bind(value, Expense.class);
+        Expense expense = (Expense)value;
         expense.setID(id);
 
         // Update the list/map
@@ -174,6 +172,6 @@ public class ExpenseServlet extends Quer
 
     @Override
     protected Serializer<?> createSerializer(Path path) throws QueryException {
-        return new JSONSerializer();
+        return new JSONSerializer(Expense.class);
     }
 }