1 package autotest.common.table; 2 3 import autotest.common.UnmodifiableSublistView; 4 5 import com.google.gwt.json.client.JSONObject; 6 7 import java.util.ArrayList; 8 import java.util.Collection; 9 import java.util.Collections; 10 import java.util.List; 11 import java.util.SortedSet; 12 import java.util.TreeSet; 13 14 /** 15 * Data source that operates from a local array. Does not support any 16 * filtering. 17 */ 18 public class ArrayDataSource<T extends JSONObject> implements DataSource { 19 private class ArrayQuery extends DefaultQuery { 20 public ArrayQuery() { 21 super(null); 22 } 23 24 @Override 25 public void getPage(Integer start, Integer maxCount, SortSpec[] sortOn, 26 DataCallback callback) { 27 List<JSONObject> sortedData = new ArrayList<JSONObject>(data); 28 if (sortOn != null) { 29 Collections.sort(sortedData, new JSONObjectComparator(sortOn)); 30 } 31 int startInt = start != null ? start.intValue() : 0; 32 int maxCountInt = maxCount != null ? maxCount.intValue() : data.size(); 33 int size = Math.min(maxCountInt, data.size() - startInt); 34 List<JSONObject> subList = 35 new UnmodifiableSublistView<JSONObject>(sortedData, startInt, size); 36 callback.handlePage(subList); 37 } 38 39 @Override 40 public void getTotalResultCount(DataCallback callback) { 41 callback.handleTotalResultCount(data.size()); 42 } 43 } 44 45 private SortedSet<T> data; 46 private Query theQuery = new ArrayQuery(); // only need one for each instance 47 48 /** 49 * @param sortKeys keys that will be used to keep items sorted internally. We 50 * do this to ensure we can find and remove items quickly. 51 */ 52 public ArrayDataSource(String[] sortKeys) { 53 SortSpec[] sortSpecs = new SortSpec[sortKeys.length]; 54 for (int i = 0; i < sortKeys.length; i++) { 55 sortSpecs[i] = new SortSpec(sortKeys[i]); 56 } 57 data = new TreeSet<T>(new JSONObjectComparator(sortSpecs)); 58 } 59 60 public void addItem(T item) { 61 data.add(item); 62 } 63 64 public void removeItem(T item) { 65 boolean wasPresent = data.remove(item); 66 assert wasPresent; 67 } 68 69 public void clear() { 70 data.clear(); 71 } 72 73 public Collection<T> getItems() { 74 return Collections.unmodifiableCollection(data); 75 } 76 77 @Override 78 public void query(JSONObject params, DataCallback callback) { 79 // ignore params since we don't support filtering 80 callback.onQueryReady(theQuery); 81 } 82 } 83