Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.lib.json; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.lang.reflect.*; |
| 5 | import java.util.*; |
| 6 | import java.util.concurrent.*; |
| 7 | |
| 8 | public class CollectionHandler extends Handler { |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 9 | Class< ? > rawClass; |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 10 | Type componentType; |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 11 | |
| 12 | CollectionHandler(Class< ? > rawClass, Type componentType) { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 13 | 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 McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 32 | throw new IllegalArgumentException("Unknown interface type for collection: " + rawClass); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 33 | } |
| 34 | this.rawClass = rawClass; |
| 35 | } |
| 36 | |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 37 | @Override |
| 38 | void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception { |
| 39 | Iterable< ? > collection = (Iterable< ? >) object; |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 40 | |
| 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 McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 51 | @Override |
| 52 | Object decodeArray(Decoder r) throws Exception { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 53 | Collection<Object> c = (Collection<Object>) rawClass.newInstance(); |
| 54 | r.codec.parseArray(c, componentType, r); |
| 55 | return c; |
| 56 | } |
| 57 | } |