View Javadoc

1   /*
2    * $Id: JSONCleaner.java 799110 2009-07-29 22:44:26Z musachy $
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  package org.apache.struts2.json;
22  
23  import java.util.Iterator;
24  import java.util.List;
25  import java.util.Map;
26  
27  /***
28   * Isolate the process of cleaning JSON data from the Interceptor class itself.
29   */
30  public abstract class JSONCleaner {
31  
32      public Object clean(String ognlPrefix, Object data) throws JSONException {
33          if (data == null)
34              return null;
35          else if (data instanceof List)
36              return cleanList(ognlPrefix, data);
37          else if (data instanceof Map)
38              return cleanMap(ognlPrefix, data);
39          else
40              return cleanValue(ognlPrefix, data);
41      }
42  
43      protected Object cleanList(String ognlPrefix, Object data) throws JSONException {
44          List list = (List) data;
45          int count = list.size();
46          for (int i = 0; i < count; i++) {
47              list.set(i, clean(ognlPrefix + "[" + i + "]", list.get(i)));
48          }
49          return list;
50      }
51  
52      protected Object cleanMap(String ognlPrefix, Object data) throws JSONException {
53          Map map = (Map) data;
54          Iterator iter = map.entrySet().iterator();
55          while (iter.hasNext()) {
56              Map.Entry e = (Map.Entry) iter.next();
57              e.setValue(clean((ognlPrefix.length() > 0 ? ognlPrefix + "." : "") + e.getKey(), e.getValue()));
58          }
59          return map;
60      }
61  
62      protected abstract Object cleanValue(String ognlName, Object data) throws JSONException;
63  
64  }