1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.mortbay.cometd.filter;
16
17 import java.lang.reflect.Array;
18 import java.util.Collection;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Map;
22
23 import org.cometd.Channel;
24 import org.cometd.Client;
25 import org.cometd.DataFilter;
26 import org.mortbay.cometd.ClientImpl;
27 import org.mortbay.log.Log;
28 import org.mortbay.util.ajax.JSON;
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public class JSONDataFilter implements DataFilter
45 {
46 public void init(Object init)
47 {}
48
49 public Object filter(Client from, Channel to, Object data) throws IllegalStateException
50 {
51 if (data==null)
52 return null;
53
54 if (data instanceof Map)
55 return filterMap(from,to,(Map)data);
56 if (data instanceof List)
57 return filterArray(from,to,((List) data).toArray ());
58 if (data instanceof Collection)
59 return filterArray(from,to,((Collection)data).toArray());
60 if (data.getClass().isArray() )
61 return filterArray(from,to,data);
62 if (data instanceof Number)
63 return filterNumber((Number)data);
64 if (data instanceof Boolean)
65 return filterBoolean((Boolean)data);
66 if (data instanceof String)
67 return filterString((String)data);
68 if (data instanceof JSON.Literal)
69 return filterJSON(from,to,(JSON.Literal)data);
70 if (data instanceof JSON.Generator)
71 return filterJSON(from,to,(JSON.Generator)data);
72 return filterObject(from,to,data);
73 }
74
75 protected Object filterString(String string)
76 {
77 return string;
78 }
79
80 protected Object filterBoolean(Boolean bool)
81 {
82 return bool;
83 }
84
85 protected Object filterNumber(Number number)
86 {
87 return number;
88 }
89
90 protected Object filterArray(Client from, Channel to, Object array)
91 {
92 if (array==null)
93 return null;
94
95 int length = Array.getLength(array);
96
97 for (int i=0;i<length;i++)
98 Array.set(array,i,filter(from, to, Array.get(array,i)));
99
100 return array;
101 }
102
103 protected Object filterMap(Client from, Channel to, Map object)
104 {
105 if (object==null)
106 return null;
107
108 Iterator iter = object.entrySet().iterator();
109 while(iter.hasNext())
110 {
111 Map.Entry entry = (Map.Entry)iter.next();
112 entry.setValue(filter(from, to, entry.getValue()));
113 }
114
115 return object;
116 }
117
118 protected Object filterJSON(Client from, Channel to, JSON.Generator generator)
119 {
120 String json = JSON.toString(generator);
121 Object data = JSON.parse (json);
122 return filter(from,to,data);
123 }
124
125 protected Object filterJSON(Client from, Channel to, JSON.Literal json)
126 {
127 Object data = JSON.parse(json.toString());
128 return filter(from,to,data);
129 }
130
131 protected Object filterObject(Client from, Channel to, Object obj)
132 {
133 Log.warn(this+": Cannot Filter "+obj.getClass());
134 return obj;
135 }
136
137 }