Utils.java revision 8b0ea2285c1327a686ff0b6ab245915e7fd20094
1package autotest.common;
2
3import com.google.gwt.dom.client.Document;
4import com.google.gwt.dom.client.Element;
5import com.google.gwt.http.client.URL;
6import com.google.gwt.json.client.JSONArray;
7import com.google.gwt.json.client.JSONNumber;
8import com.google.gwt.json.client.JSONObject;
9import com.google.gwt.json.client.JSONString;
10import com.google.gwt.json.client.JSONValue;
11import com.google.gwt.user.client.Window;
12import com.google.gwt.user.client.ui.HTMLPanel;
13
14import java.util.ArrayList;
15import java.util.Collection;
16import java.util.List;
17import java.util.Map;
18
19public class Utils {
20    public static final String JSON_NULL = "<null>";
21    public static final String RETRIEVE_LOGS_URL = "/tko/retrieve_logs.cgi";
22
23    private static final String[][] escapeMappings = {
24        {"&", "&amp;"},
25        {">", "&gt;"},
26        {"<", "&lt;"},
27        {"\"", "&quot;"},
28        {"'", "&apos;"},
29    };
30
31    /**
32     * Converts a collection of Java <code>String</code>s into a <code>JSONArray
33     * </code> of <code>JSONString</code>s.
34     */
35    public static JSONArray stringsToJSON(Collection<String> strings) {
36        JSONArray result = new JSONArray();
37        for(String s : strings) {
38            result.set(result.size(), new JSONString(s));
39        }
40        return result;
41    }
42
43    /**
44     * Converts a <code>JSONArray</code> of <code>JSONStrings</code> to an
45     * array of Java <code>Strings</code>.
46     */
47    public static String[] JSONtoStrings(JSONArray strings) {
48        String[] result = new String[strings.size()];
49        for (int i = 0; i < strings.size(); i++) {
50            result[i] = jsonToString(strings.get(i));
51        }
52        return result;
53    }
54
55    /**
56     * Converts a <code>JSONArray</code> of <code>JSONObjects</code> to an
57     * array of Java <code>Strings</code> by grabbing the specified field from
58     * each object.
59     */
60    public static String[] JSONObjectsToStrings(JSONArray objects, String field) {
61        String[] result = new String[objects.size()];
62        for (int i = 0; i < objects.size(); i++) {
63            JSONValue fieldValue = objects.get(i).isObject().get(field);
64            result[i] = jsonToString(fieldValue);
65        }
66        return result;
67    }
68
69    public static JSONObject mapToJsonObject(Map<String, String> map) {
70        JSONObject result = new JSONObject();
71        for (Map.Entry<String, String> entry : map.entrySet()) {
72            result.put(entry.getKey(), new JSONString(entry.getValue()));
73        }
74        return result;
75    }
76
77    /**
78     * Get a value out of a JSONObject list of size 1.
79     * @return list[0]
80     * @throws IllegalArgumentException if the list is not of size 1
81     */
82    public static JSONObject getSingleObjectFromList(List<JSONObject> list) {
83        if(list.size() != 1) {
84            throw new IllegalArgumentException("List is not of size 1");
85        }
86        return list.get(0);
87    }
88
89    public static JSONObject getSingleObjectFromArray(JSONArray array) {
90        return getSingleObjectFromList(new JSONArrayList<JSONObject>(array));
91    }
92
93    public static JSONObject copyJSONObject(JSONObject source) {
94        JSONObject dest = new JSONObject();
95        for(String key : source.keySet()) {
96            dest.put(key, source.get(key));
97        }
98        return dest;
99    }
100
101    public static String escape(String text) {
102        for (String[] mapping : escapeMappings) {
103            text = text.replace(mapping[0], mapping[1]);
104        }
105        return text;
106    }
107
108    public static String unescape(String text) {
109        // must iterate in reverse order
110        for (int i = escapeMappings.length - 1; i >= 0; i--) {
111            text = text.replace(escapeMappings[i][1], escapeMappings[i][0]);
112        }
113        return text;
114    }
115
116    public static <T> List<T> wrapObjectWithList(T object) {
117        List<T> list = new ArrayList<T>();
118        list.add(object);
119        return list;
120    }
121
122    public static <T> String joinStrings(String joiner, List<T> objects, boolean wantBlanks) {
123        StringBuilder result = new StringBuilder();
124        boolean first = true;
125        for (T object : objects) {
126            String piece = object.toString();
127            if (piece.equals("") && !wantBlanks) {
128                continue;
129            }
130            if (first) {
131                first = false;
132            } else {
133                result.append(joiner);
134            }
135            result.append(piece);
136        }
137        return result.toString();
138    }
139
140    public static <T> String joinStrings(String joiner, List<T> objects) {
141        return joinStrings(joiner, objects, false);
142    }
143
144    public static Map<String,String> decodeUrlArguments(String urlArguments,
145                                                        Map<String, String> arguments) {
146        String[] components = urlArguments.split("&");
147        for (String component : components) {
148            String[] parts = component.split("=");
149            if (parts.length > 2) {
150                throw new IllegalArgumentException();
151            }
152            String key = decodeComponent(parts[0]);
153            String value = "";
154            if (parts.length == 2) {
155                value = URL.decodeComponent(parts[1]);
156            }
157            arguments.put(key, value);
158        }
159        return arguments;
160    }
161
162    private static String decodeComponent(String component) {
163        return URL.decodeComponent(component.replace("%27", "'"));
164    }
165
166    public static String encodeUrlArguments(Map<String, String> arguments) {
167        List<String> components = new ArrayList<String>();
168        for (Map.Entry<String, String> entry : arguments.entrySet()) {
169            String key = encodeComponent(entry.getKey());
170            String value = encodeComponent(entry.getValue());
171            components.add(key + "=" + value);
172        }
173        return joinStrings("&", components);
174    }
175
176    private static String encodeComponent(String component) {
177        return URL.encodeComponent(component).replace("'", "%27");
178    }
179
180    /**
181     * @param path should be of the form "123-showard/status.log" or just "123-showard"
182     */
183    public static String getLogsUrl(String path) {
184        return "/results/" + path;
185    }
186
187    public static String getRetrieveLogsUrl(String path) {
188        String logUrl = URL.encode(getLogsUrl(path));
189        return RETRIEVE_LOGS_URL + "?job=" + logUrl;
190    }
191
192    public static String jsonToString(JSONValue value) {
193        JSONString string;
194        JSONNumber number;
195        assert value != null;
196        if ((string = value.isString()) != null) {
197            return string.stringValue();
198        }
199        if ((number = value.isNumber()) != null) {
200            double doubleValue = number.doubleValue();
201            if (doubleValue == (int) doubleValue) {
202                return Integer.toString((int) doubleValue);
203            }
204            return Double.toString(doubleValue);
205
206        }
207        if (value.isNull() != null) {
208            return JSON_NULL;
209        }
210        return value.toString();
211    }
212
213    public static String setDefaultValue(Map<String, String> map, String key, String defaultValue) {
214        if (map.containsKey(key)) {
215            return map.get(key);
216        }
217        map.put(key, defaultValue);
218        return defaultValue;
219    }
220
221    public static JSONValue setDefaultValue(JSONObject object, String key, JSONValue defaultValue) {
222        if (object.containsKey(key)) {
223            return object.get(key);
224        }
225        object.put(key, defaultValue);
226        return defaultValue;
227    }
228
229    public static List<String> splitList(String list, String splitRegex) {
230        String[] parts = list.split(splitRegex);
231        List<String> finalParts = new ArrayList<String>();
232        for (String part : parts) {
233            if (!part.equals("")) {
234                finalParts.add(part);
235            }
236        }
237        return finalParts;
238    }
239
240    public static List<String> splitList(String list) {
241        return splitList(list, ",");
242    }
243
244    public static List<String> splitListWithSpaces(String list) {
245        return splitList(list, "[,\\s]+");
246    }
247
248    public static void updateObject(JSONObject destination, JSONObject source) {
249        if (source == null) {
250            return;
251        }
252        for (String key : source.keySet()) {
253            destination.put(key, source.get(key));
254        }
255    }
256
257    public static void openUrlInNewWindow(String url) {
258        Window.open(url, "_blank", "");
259    }
260
261    public static HTMLPanel divToPanel(String elementId) {
262        Element divElement = Document.get().getElementById(elementId);
263        divElement.getParentElement().removeChild(divElement);
264        return new HTMLPanel(divElement.getInnerHTML());
265    }
266
267    public static void setElementVisible(String elementId, boolean visible) {
268        String display = visible ? "block" : "none";
269        Document.get().getElementById(elementId).getStyle().setProperty("display", display);
270    }
271}
272