RpcDataSource.java revision 6bc47015cce0ebc2fc255d3950bfeaf4851f36fd
1package autotest.common.table; 2 3import autotest.common.JsonRpcCallback; 4import autotest.common.JsonRpcProxy; 5import autotest.common.Utils; 6 7import com.google.gwt.json.client.JSONArray; 8import com.google.gwt.json.client.JSONNumber; 9import com.google.gwt.json.client.JSONObject; 10import com.google.gwt.json.client.JSONString; 11import com.google.gwt.json.client.JSONValue; 12 13/** 14 * Data source that retrieves results via RPC requests to the server. 15 */ 16public class RpcDataSource implements DataSource { 17 protected String getDataMethod, getCountMethod; 18 protected JSONObject filterParams; 19 protected Integer numResults = null; 20 21 public RpcDataSource(String getDataMethod, String getCountMethod) { 22 this.getDataMethod = getDataMethod; 23 this.getCountMethod = getCountMethod; 24 } 25 26 /** 27 * Process the JSON result returned by the server into an array of result 28 * objects. This default implementation assumes the result itself is an array. 29 * Subclasses may override this to construct an array from the JSON result. 30 */ 31 protected JSONArray handleJsonResult(JSONValue result) { 32 return result.isArray(); 33 } 34 35 public void updateData(JSONObject params, final DataCallback callback) { 36 filterParams = params; 37 JsonRpcProxy.getProxy().rpcCall(getCountMethod, params, 38 new JsonRpcCallback() { 39 @Override 40 public void onSuccess(JSONValue result) { 41 int count = (int) result.isNumber().doubleValue(); 42 numResults = Integer.valueOf(count); 43 callback.onGotData(count); 44 } 45 }); 46 } 47 48 public void getPage(Integer start, Integer maxCount, 49 String sortOn, Integer sortDirection, 50 final DataCallback callback) { 51 JSONObject params; 52 if (filterParams == null) 53 params = new JSONObject(); 54 else 55 params = Utils.copyJSONObject(filterParams); 56 if (start != null) 57 params.put("query_start", new JSONNumber(start.intValue())); 58 if (maxCount != null) 59 params.put("query_limit", new JSONNumber(maxCount.intValue())); 60 if (sortOn != null) { 61 if (sortDirection.intValue() == DataSource.DESCENDING) 62 sortOn = "-" + sortOn; 63 JSONArray sortList = new JSONArray(); 64 sortList.set(0, new JSONString(sortOn)); 65 params.put("sort_by", sortList); 66 } 67 68 JsonRpcProxy.getProxy().rpcCall(getDataMethod, params, 69 new JsonRpcCallback() { 70 @Override 71 public void onSuccess(JSONValue result) { 72 JSONArray resultData = handleJsonResult(result); 73 callback.handlePage(resultData); 74 } 75 }); 76 } 77 78 public int getNumResults() { 79 assert numResults != null; 80 return numResults.intValue(); 81 } 82} 83