• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package autotest.afe;
2 
3 import autotest.afe.create.CreateJobViewPresenter.JobCreateListener;
4 import autotest.common.JSONArrayList;
5 import autotest.common.JsonRpcCallback;
6 import autotest.common.JsonRpcProxy;
7 import autotest.common.SimpleCallback;
8 import autotest.common.StaticDataRepository;
9 import autotest.common.Utils;
10 import autotest.common.table.JSONObjectSet;
11 import autotest.common.ui.NotifyManager;
12 import autotest.common.ui.SimplifiedList;
13 
14 import com.google.gwt.json.client.JSONArray;
15 import com.google.gwt.json.client.JSONBoolean;
16 import com.google.gwt.json.client.JSONObject;
17 import com.google.gwt.json.client.JSONString;
18 import com.google.gwt.json.client.JSONValue;
19 import com.google.gwt.user.client.DOM;
20 import com.google.gwt.user.client.Element;
21 import com.google.gwt.user.client.ui.ListBox;
22 
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Set;
28 
29 /**
30  * Utility methods.
31  */
32 public class AfeUtils {
33     public static final String PLATFORM_SUFFIX = " (platform)";
34 
35     public static final ClassFactory factory = new SiteClassFactory();
36 
37     private static StaticDataRepository staticData = StaticDataRepository.getRepository();
38 
formatStatusCounts(JSONObject counts, String joinWith)39     public static String formatStatusCounts(JSONObject counts, String joinWith) {
40         StringBuilder result = new StringBuilder();
41         Set<String> statusSet = counts.keySet();
42         for (Iterator<String> i = statusSet.iterator(); i.hasNext();) {
43             String status = i.next();
44             int count = (int) counts.get(status).isNumber().doubleValue();
45             result.append(Integer.toString(count));
46             result.append(" ");
47             result.append(status);
48             if (i.hasNext()) {
49                 result.append(joinWith);
50             }
51         }
52         return result.toString();
53     }
54 
getLabelStrings()55     public static String[] getLabelStrings() {
56         return getFilteredLabelStrings(false, false);
57     }
58 
getFilteredLabelStrings(boolean onlyPlatforms, boolean onlyNonPlatforms)59     protected static String[] getFilteredLabelStrings(boolean onlyPlatforms,
60                                                       boolean onlyNonPlatforms) {
61         assert !(onlyPlatforms && onlyNonPlatforms);
62         JSONArray labels = staticData.getData("labels").isArray();
63         List<String> result = new ArrayList<String>();
64         for (int i = 0; i < labels.size(); i++) {
65             JSONObject label = labels.get(i).isObject();
66             String name = label.get("name").isString().stringValue();
67             boolean labelIsPlatform = label.get("platform").isBoolean().booleanValue();
68             if (onlyPlatforms && labelIsPlatform ||
69                 onlyNonPlatforms && !labelIsPlatform) {
70                     result.add(name);
71             } else if (!onlyPlatforms && !onlyNonPlatforms) {
72                 if (labelIsPlatform) {
73                     name += PLATFORM_SUFFIX;
74                 }
75                 result.add(name);
76             }
77         }
78         return result.toArray(new String[result.size()]);
79     }
80 
getPlatformStrings()81     public static String[] getPlatformStrings() {
82         return getFilteredLabelStrings(true, false);
83     }
84 
getNonPlatformLabelStrings()85     public static String[] getNonPlatformLabelStrings() {
86         return getFilteredLabelStrings(false, true);
87     }
88 
decodeLabelName(String labelName)89     public static String decodeLabelName(String labelName) {
90         String name = labelName;
91         if (name.endsWith(PLATFORM_SUFFIX)) {
92             int nameLength = name.length() - PLATFORM_SUFFIX.length();
93             name = name.substring(0, nameLength);
94         }
95         return name;
96     }
97 
getLockedText(JSONObject host)98     public static JSONString getLockedText(JSONObject host) {
99         boolean locked = host.get("locked").isBoolean().booleanValue();
100         return new JSONString(locked ? "Yes" : "No");
101     }
102 
abortHostQueueEntries(Collection<JSONObject> entries, final SimpleCallback onSuccess)103     public static void abortHostQueueEntries(Collection<JSONObject> entries,
104                                              final SimpleCallback onSuccess) {
105         if (entries.isEmpty()) {
106             NotifyManager.getInstance().showError("No entries selected to abort");
107             return;
108         }
109 
110         final JSONArray asynchronousEntryIds = new JSONArray();
111         Set<JSONObject> synchronousEntries = new JSONObjectSet<JSONObject>();
112         for (JSONObject entry : entries) {
113             JSONObject job = entry.get("job").isObject();
114             int synchCount = (int) job.get("synch_count").isNumber().doubleValue();
115             boolean hasExecutionSubdir =
116                 entry.containsKey("execution_subdir") &&
117                 !Utils.jsonToString(entry.get("execution_subdir")).equals("");
118             if (synchCount > 1 && hasExecutionSubdir) {
119                 synchronousEntries.add(entry);
120                 continue;
121             }
122 
123             JSONValue idListValue = entry.get("id_list");
124             if (idListValue != null) {
125                 // metahost row
126                 extendJsonArray(asynchronousEntryIds, idListValue.isArray());
127             } else {
128                 JSONValue id = entry.get("id");
129                 if (entry.containsKey("oid"))
130                     id = entry.get("oid");
131                 asynchronousEntryIds.set(asynchronousEntryIds.size(), id);
132             }
133         }
134 
135         SimpleCallback abortAsynchronousEntries = new SimpleCallback() {
136             public void doCallback(Object source) {
137                 JSONObject params = new JSONObject();
138                 params.put("id__in", asynchronousEntryIds);
139                 AfeUtils.callAbort(params, onSuccess);
140             }
141         };
142 
143         if (synchronousEntries.size() == 0) {
144             abortAsynchronousEntries.doCallback(null);
145         } else {
146             AbortSynchronousDialog dialog = new AbortSynchronousDialog(
147                 abortAsynchronousEntries, synchronousEntries, asynchronousEntryIds.size() != 0);
148             dialog.center();
149         }
150     }
151 
abortSpecialTasks(final JSONArray specialTaskIds, final SimpleCallback onSuccess)152     public static void abortSpecialTasks(final JSONArray specialTaskIds,
153                                          final SimpleCallback onSuccess) {
154         if (specialTaskIds.size() == 0) {
155             NotifyManager.getInstance().showError("No entries selected to abort");
156             return;
157         }
158 
159         SimpleCallback abortSpecialTasks = new SimpleCallback() {
160             public void doCallback(Object source) {
161                 JSONObject params = new JSONObject();
162                 params.put("id__in", specialTaskIds);
163                 AfeUtils.callAbortSpecialTasks(params, onSuccess);
164             }
165         };
166 
167         abortSpecialTasks.doCallback(null);
168     }
169 
extendJsonArray(JSONArray array, JSONArray newValues)170     private static void extendJsonArray(JSONArray array, JSONArray newValues) {
171         for (JSONValue value : new JSONArrayList<JSONValue>(newValues)) {
172             array.set(array.size(), value);
173         }
174     }
175 
callAbort(JSONObject params, final SimpleCallback onSuccess, final boolean showMessage)176     public static void callAbort(JSONObject params, final SimpleCallback onSuccess,
177                                  final boolean showMessage) {
178         JsonRpcProxy rpcProxy = JsonRpcProxy.getProxy();
179         rpcProxy.rpcCall("abort_host_queue_entries", params, new JsonRpcCallback() {
180             @Override
181             public void onSuccess(JSONValue result) {
182                 if (showMessage) {
183                     NotifyManager.getInstance().showMessage("Jobs aborted");
184                 }
185                 if (onSuccess != null) {
186                     onSuccess.doCallback(null);
187                 }
188             }
189         });
190     }
191 
callAbort(JSONObject params, final SimpleCallback onSuccess)192     public static void callAbort(JSONObject params, final SimpleCallback onSuccess) {
193         callAbort(params, onSuccess, true);
194     }
195 
callAbortSpecialTasks(JSONObject params, final SimpleCallback onSuccess, final boolean showMessage)196     public static void callAbortSpecialTasks(JSONObject params, final SimpleCallback onSuccess,
197                                  final boolean showMessage) {
198         JsonRpcProxy rpcProxy = JsonRpcProxy.getProxy();
199         rpcProxy.rpcCall("abort_special_tasks", params, new JsonRpcCallback() {
200             @Override
201             public void onSuccess(JSONValue result) {
202                 if (showMessage) {
203                     NotifyManager.getInstance().showMessage("Special tasks aborted");
204                 }
205                 if (onSuccess != null) {
206                     onSuccess.doCallback(null);
207                 }
208             }
209         });
210     }
211 
callAbortSpecialTasks(JSONObject params, final SimpleCallback onSuccess)212     public static void callAbortSpecialTasks(JSONObject params, final SimpleCallback onSuccess) {
213         callAbortSpecialTasks(params, onSuccess, true);
214     }
215 
callReverify(JSONObject params, final SimpleCallback onSuccess, final String messagePrefix)216     public static void callReverify(JSONObject params, final SimpleCallback onSuccess,
217                                     final String messagePrefix) {
218         JsonRpcProxy rpcProxy = JsonRpcProxy.getProxy();
219         rpcProxy.rpcCall("reverify_hosts", params, new JsonRpcCallback() {
220             @Override
221             public void onSuccess(JSONValue result) {
222 
223                 NotifyManager.getInstance().showMessage(
224                         messagePrefix + " scheduled for reverification");
225 
226                 if (onSuccess != null) {
227                     onSuccess.doCallback(null);
228                 }
229             }
230         });
231     }
232 
callRepair(JSONObject params, final SimpleCallback onSuccess, final String messagePrefix)233     public static void callRepair(JSONObject params, final SimpleCallback onSuccess,
234                                   final String messagePrefix) {
235         JsonRpcProxy rpcProxy = JsonRpcProxy.getProxy();
236         rpcProxy.rpcCall("repair_hosts", params, new JsonRpcCallback() {
237             @Override
238             public void onSuccess(JSONValue result) {
239 
240                 NotifyManager.getInstance().showMessage(
241                         messagePrefix + " scheduled for repair");
242 
243                 if (onSuccess != null) {
244                     onSuccess.doCallback(null);
245                 }
246             }
247         });
248     }
249 
callModifyHosts(JSONObject params, final SimpleCallback onSuccess)250     public static void callModifyHosts(JSONObject params, final SimpleCallback onSuccess) {
251         JsonRpcProxy rpcProxy = JsonRpcProxy.getProxy();
252         rpcProxy.rpcCall("modify_hosts", params, new JsonRpcCallback() {
253             @Override
254             public void onSuccess(JSONValue result) {
255                 if (onSuccess != null) {
256                     onSuccess.doCallback(null);
257                 }
258             }
259         });
260     }
261 
changeHostLocks(JSONArray hostIds, final boolean lock, String lockReason, final String messagePrefix, final SimpleCallback callback)262     public static void changeHostLocks(JSONArray hostIds, final boolean lock,
263                                        String lockReason, final String messagePrefix,
264                                        final SimpleCallback callback) {
265         JSONObject hostFilterData = new JSONObject();
266         JSONObject updateData = new JSONObject();
267         JSONObject params = new JSONObject();
268 
269         hostFilterData.put("id__in", hostIds);
270         updateData.put("locked", JSONBoolean.getInstance(lock));
271         updateData.put("lock_reason", new JSONString(""));
272 
273         if (lockReason != null && !lockReason.trim().isEmpty()) {
274             updateData.put("lock_reason", new JSONString(lockReason.trim()));
275         }
276 
277         params.put("host_filter_data", hostFilterData);
278         params.put("update_data", updateData);
279 
280         callModifyHosts(params, new SimpleCallback() {
281             public void doCallback(Object source) {
282                 String message = messagePrefix + " ";
283                 if (!lock) {
284                     message += "un";
285                 }
286                 message += "locked";
287 
288                 NotifyManager.getInstance().showMessage(message);
289 
290                 callback.doCallback(source);
291             }
292         });
293     }
294 
getJobTag(JSONObject job)295     public static String getJobTag(JSONObject job) {
296         return Utils.jsonToString(job.get("id")) + "-" + Utils.jsonToString(job.get("owner"));
297     }
298 
populateRadioChooser(RadioChooser chooser, String name)299     public static void populateRadioChooser(RadioChooser chooser, String name) {
300         JSONArray options = staticData.getData(name + "_options").isArray();
301         for (JSONString jsonOption : new JSONArrayList<JSONString>(options)) {
302             chooser.addChoice(Utils.jsonToString(jsonOption));
303         }
304     }
305 
populateListBox(ListBox box, String staticDataKey)306     public static void populateListBox(ListBox box, String staticDataKey) {
307         JSONArray options = staticData.getData(staticDataKey).isArray();
308         for (JSONString jsonOption : new JSONArrayList<JSONString>(options)) {
309             box.addItem(Utils.jsonToString(jsonOption));
310         }
311     }
312 
populateListBox(SimplifiedList box, String staticDataKey)313     public static void populateListBox(SimplifiedList box, String staticDataKey) {
314         JSONArray options = staticData.getData(staticDataKey).isArray();
315         for (JSONString jsonOption : new JSONArrayList<JSONString>(options)) {
316             String option = Utils.jsonToString(jsonOption);
317             box.addItem(option, option);
318         }
319     }
320 
setSelectedItem(ListBox box, String item)321     public static void setSelectedItem(ListBox box, String item) {
322         box.setSelectedIndex(0);
323         for (int i = 0; i < box.getItemCount(); i++) {
324             if (box.getItemText(i).equals(item)) {
325                 box.setSelectedIndex(i);
326                 break;
327             }
328         }
329     }
330 
removeElement(String id)331     public static void removeElement(String id) {
332         Element element = DOM.getElementById(id);
333         element.getParentElement().removeChild(element);
334     }
335 
parsePositiveIntegerInput(String input, String fieldName)336     public static int parsePositiveIntegerInput(String input, String fieldName) {
337         final int parsedInt;
338         try {
339             if (input.equals("") ||
340                 (parsedInt = Integer.parseInt(input)) <= 0) {
341                     String error = "Please enter a positive " + fieldName;
342                     NotifyManager.getInstance().showError(error);
343                     throw new IllegalArgumentException();
344             }
345         } catch (NumberFormatException e) {
346             String error = "Invalid " + fieldName + ": \"" + input + "\"";
347             NotifyManager.getInstance().showError(error);
348             throw new IllegalArgumentException();
349         }
350         return parsedInt;
351     }
352 
removeSecondsFromDateField(JSONObject row, String sourceFieldName, String targetFieldName)353     public static void removeSecondsFromDateField(JSONObject row,
354                                                   String sourceFieldName,
355                                                   String targetFieldName) {
356         JSONValue dateValue = row.get(sourceFieldName);
357         String date = "";
358         if (dateValue.isNull() == null) {
359             date = dateValue.isString().stringValue();
360             date = date.substring(0, date.length() - 3);
361         }
362         row.put(targetFieldName, new JSONString(date));
363     }
364 
callGetJobHistory(JSONObject params, final SimpleCallback onSuccess, final boolean showMessage)365     public static void callGetJobHistory(JSONObject params,
366                                          final SimpleCallback onSuccess,
367                                          final boolean showMessage) {
368         JsonRpcProxy rpcProxy = JsonRpcProxy.getProxy();
369         rpcProxy.rpcCall("get_job_history", params, new JsonRpcCallback() {
370             @Override
371             public void onSuccess(JSONValue result) {
372                 if (showMessage) {
373                     NotifyManager.getInstance().showMessage("Get job history succeeded.");
374                 }
375                 if (onSuccess != null) {
376                     onSuccess.doCallback(result);
377                 }
378             }
379         });
380     }
381 
callGetSpongeUrl(JSONObject params, final SimpleCallback onSuccess)382     public static void callGetSpongeUrl(JSONObject params,
383                                         final SimpleCallback onSuccess) {
384         JsonRpcProxy rpcProxy = JsonRpcProxy.getProxy(JsonRpcProxy.TKO_BASE_URL);
385         rpcProxy.rpcCall("get_detailed_test_views", params, new JsonRpcCallback() {
386             @Override
387             public void onSuccess(JSONValue result) {
388                 if (onSuccess != null) {
389                     JSONArray testViews = (JSONArray)result;
390                     JSONValue keyVals = ((JSONObject)testViews.get(0)).get("job_keyvals");
391                     String spongeUrl = ((JSONObject)keyVals).get("sponge_url").isString().stringValue();
392                     onSuccess.doCallback(spongeUrl);
393                 }
394             }
395         });
396     }
397 }
398