Utils.java revision 21085f22a3c616ff12bf80b997187a00e44f851b
1package autotest.common;
2
3import com.google.gwt.http.client.URL;
4import com.google.gwt.json.client.JSONArray;
5import com.google.gwt.json.client.JSONNumber;
6import com.google.gwt.json.client.JSONObject;
7import com.google.gwt.json.client.JSONString;
8import com.google.gwt.json.client.JSONValue;
9
10import java.util.ArrayList;
11import java.util.Collection;
12import java.util.HashMap;
13import java.util.List;
14import java.util.Map;
15
16public class Utils {
17    public static final String JSON_NULL = "<null>";
18    private static final String[][] escapeMappings = {
19        {"&", "&amp;"},
20        {">", "&gt;"},
21        {"<", "&lt;"},
22        {"\"", "&quot;"},
23        {"'", "&apos;"},
24    };
25
26    /**
27     * Converts a collection of Java <code>String</code>s into a <code>JSONArray
28     * </code> of <code>JSONString</code>s.
29     */
30    public static JSONArray stringsToJSON(Collection<String> strings) {
31        JSONArray result = new JSONArray();
32        for(String s : strings) {
33            result.set(result.size(), new JSONString(s));
34        }
35        return result;
36    }
37
38    /**
39     * Converts a <code>JSONArray</code> of <code>JSONStrings</code> to an
40     * array of Java <code>Strings</code>.
41     */
42    public static String[] JSONtoStrings(JSONArray strings) {
43        String[] result = new String[strings.size()];
44        for (int i = 0; i < strings.size(); i++) {
45            result[i] = jsonToString(strings.get(i));
46        }
47        return result;
48    }
49
50    /**
51     * Converts a <code>JSONArray</code> of <code>JSONObjects</code> to an
52     * array of Java <code>Strings</code> by grabbing the specified field from
53     * each object.
54     */
55    public static String[] JSONObjectsToStrings(JSONArray objects, String field) {
56        String[] result = new String[objects.size()];
57        for (int i = 0; i < objects.size(); i++) {
58            JSONValue fieldValue = objects.get(i).isObject().get(field);
59            result[i] = jsonToString(fieldValue);
60        }
61        return result;
62    }
63
64    /**
65     * Get a value out of an array of size 1.
66     * @return array[0]
67     * @throws IllegalArgumentException if the array is not of size 1
68     */
69    public static JSONValue getSingleValueFromArray(JSONArray array) {
70        if(array.size() != 1) {
71            throw new IllegalArgumentException("Array is not of size 1");
72        }
73        return array.get(0);
74    }
75
76    public static JSONObject copyJSONObject(JSONObject source) {
77        JSONObject dest = new JSONObject();
78        for(String key : source.keySet()) {
79            dest.put(key, source.get(key));
80        }
81        return dest;
82    }
83
84    public static String escape(String text) {
85        for (String[] mapping : escapeMappings) {
86            text = text.replace(mapping[0], mapping[1]);
87        }
88        return text;
89    }
90
91    public static String unescape(String text) {
92        // must iterate in reverse order
93        for (int i = escapeMappings.length - 1; i >= 0; i--) {
94            text = text.replace(escapeMappings[i][1], escapeMappings[i][0]);
95        }
96        return text;
97    }
98
99    public static <T> List<T> wrapObjectWithList(T object) {
100        List<T> list = new ArrayList<T>();
101        list.add(object);
102        return list;
103    }
104
105    public static <T> String joinStrings(String joiner, List<T> objects) {
106        if (objects.size() == 0) {
107            return "";
108        }
109
110        StringBuilder result = new StringBuilder(objects.get(0).toString());
111        for (int i = 1; i < objects.size(); i++) {
112            result.append(joiner);
113            result.append(objects.get(i).toString());
114        }
115        return result.toString();
116    }
117
118    public static Map<String,String> decodeUrlArguments(String urlArguments) {
119        Map<String, String> arguments = new HashMap<String, String>();
120        String[] components = urlArguments.split("&");
121        for (String component : components) {
122            String[] parts = component.split("=");
123            if (parts.length > 2) {
124                throw new IllegalArgumentException();
125            }
126            String key = decodeComponent(parts[0]);
127            String value = "";
128            if (parts.length == 2) {
129                value = URL.decodeComponent(parts[1]);
130            }
131            arguments.put(key, value);
132        }
133        return arguments;
134    }
135
136    private static String decodeComponent(String component) {
137        return URL.decodeComponent(component.replace("%27", "'"));
138    }
139
140    public static String encodeUrlArguments(Map<String, String> arguments) {
141        List<String> components = new ArrayList<String>();
142        for (Map.Entry<String, String> entry : arguments.entrySet()) {
143            String key = encodeComponent(entry.getKey());
144            String value = encodeComponent(entry.getValue());
145            components.add(key + "=" + value);
146        }
147        return joinStrings("&", components);
148    }
149
150    private static String encodeComponent(String component) {
151        return URL.encodeComponent(component).replace("'", "%27");
152    }
153
154    /**
155     * @param path should be of the form "123-showard/status.log" or just "123-showard"
156     */
157    public static String getLogsURL(String path) {
158        String val = URL.encode("/results/" + path);
159        return "/tko/retrieve_logs.cgi?job=" + val;
160    }
161
162    public static String jsonToString(JSONValue value) {
163        JSONString string;
164        JSONNumber number;
165        if ((string = value.isString()) != null) {
166            return string.stringValue();
167        }
168        if ((number = value.isNumber()) != null) {
169            return Integer.toString((int) number.doubleValue());
170        }
171        if (value.isNull() != null) {
172            return JSON_NULL;
173        }
174        return value.toString();
175    }
176
177    public static void setDefaultValue(Map<String, String> map, String key, String value) {
178        if (map.get(key) == null) {
179            map.put(key, value);
180        }
181    }
182}
183