blob: aacbb0a535141476a066685dc6a39cbb43eb23e3 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.json;
2
3import java.io.*;
4import java.lang.reflect.*;
5import java.util.*;
6import java.util.concurrent.*;
7
8public class CollectionHandler extends Handler {
Stuart McCulloch2286f232012-06-15 13:27:53 +00009 Class< ? > rawClass;
Stuart McCullochbb014372012-06-07 21:57:32 +000010 Type componentType;
Stuart McCulloch2286f232012-06-15 13:27:53 +000011
12 CollectionHandler(Class< ? > rawClass, Type componentType) {
Stuart McCullochbb014372012-06-07 21:57:32 +000013 this.componentType = componentType;
14 if (rawClass.isInterface()) {
15 if (rawClass.isAssignableFrom(ArrayList.class))
16 rawClass = ArrayList.class;
17 else if (rawClass.isAssignableFrom(LinkedList.class))
18 rawClass = LinkedList.class;
19 else if (rawClass.isAssignableFrom(HashSet.class))
20 rawClass = HashSet.class;
21 else if (rawClass.isAssignableFrom(TreeSet.class))
22 rawClass = TreeSet.class;
23 else if (rawClass.isAssignableFrom(Vector.class))
24 rawClass = Vector.class;
25 else if (rawClass.isAssignableFrom(ConcurrentLinkedQueue.class))
26 rawClass = ConcurrentLinkedQueue.class;
27 else if (rawClass.isAssignableFrom(CopyOnWriteArrayList.class))
28 rawClass = CopyOnWriteArrayList.class;
29 else if (rawClass.isAssignableFrom(CopyOnWriteArraySet.class))
30 rawClass = CopyOnWriteArraySet.class;
31 else
Stuart McCulloch2286f232012-06-15 13:27:53 +000032 throw new IllegalArgumentException("Unknown interface type for collection: " + rawClass);
Stuart McCullochbb014372012-06-07 21:57:32 +000033 }
34 this.rawClass = rawClass;
35 }
36
Stuart McCulloch2286f232012-06-15 13:27:53 +000037 @Override
38 void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception {
39 Iterable< ? > collection = (Iterable< ? >) object;
Stuart McCullochbb014372012-06-07 21:57:32 +000040
41 app.append("[");
42 String del = "";
43 for (Object o : collection) {
44 app.append(del);
45 app.encode(o, componentType, visited);
46 del = ",";
47 }
48 app.append("]");
49 }
50
Stuart McCulloch2286f232012-06-15 13:27:53 +000051 @Override
52 Object decodeArray(Decoder r) throws Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000053 Collection<Object> c = (Collection<Object>) rawClass.newInstance();
54 r.codec.parseArray(c, componentType, r);
55 return c;
56 }
57}