You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ListDataSource.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.v7.client.widget.grid.datasources;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Comparator;
  22. import java.util.Iterator;
  23. import java.util.LinkedHashSet;
  24. import java.util.List;
  25. import java.util.ListIterator;
  26. import java.util.Objects;
  27. import java.util.Set;
  28. import java.util.stream.Stream;
  29. import com.vaadin.client.data.DataChangeHandler;
  30. import com.vaadin.client.data.DataSource;
  31. import com.vaadin.shared.Registration;
  32. import com.vaadin.shared.util.SharedUtil;
  33. import com.vaadin.v7.client.widget.grid.events.SelectAllEvent;
  34. import com.vaadin.v7.client.widget.grid.events.SelectAllHandler;
  35. /**
  36. * A simple list based on an in-memory data source for simply adding a list of
  37. * row pojos to the grid. Based on a wrapped list instance which supports adding
  38. * and removing of items.
  39. *
  40. * <p>
  41. * Usage:
  42. *
  43. * <pre>
  44. * ListDataSource&lt;Integer&gt; ds = new ListDataSource&lt;Integer&gt;(1, 2, 3, 4);
  45. *
  46. * // Add item to the data source
  47. * ds.asList().add(5);
  48. *
  49. * // Remove item from the data source
  50. * ds.asList().remove(3);
  51. *
  52. * // Add multiple items
  53. * ds.asList().addAll(Arrays.asList(5, 6, 7));
  54. * </pre>
  55. *
  56. * @since 7.4
  57. * @author Vaadin Ltd
  58. */
  59. public class ListDataSource<T> implements DataSource<T> {
  60. private class RowHandleImpl extends RowHandle<T> {
  61. private final T row;
  62. public RowHandleImpl(T row) {
  63. this.row = row;
  64. }
  65. @Override
  66. public T getRow() {
  67. /*
  68. * We'll cheat here and don't throw an IllegalStateException even if
  69. * this isn't pinned, because we know that the reference never gets
  70. * stale.
  71. */
  72. return row;
  73. }
  74. @Override
  75. public void pin() {
  76. // NOOP, really
  77. }
  78. @Override
  79. public void unpin() throws IllegalStateException {
  80. /*
  81. * Just to make things easier for everyone, we won't throw the
  82. * exception, even in illegal situations.
  83. */
  84. }
  85. @Override
  86. protected boolean equalsExplicit(Object obj) {
  87. if (obj instanceof ListDataSource.RowHandleImpl) {
  88. /*
  89. * Java prefers AbstractRemoteDataSource<?>.RowHandleImpl. I
  90. * like the @SuppressWarnings more (keeps the line length in
  91. * check.)
  92. */
  93. @SuppressWarnings("unchecked")
  94. RowHandleImpl rhi = (RowHandleImpl) obj;
  95. return SharedUtil.equals(row, rhi.row);
  96. } else {
  97. return false;
  98. }
  99. }
  100. @Override
  101. protected int hashCodeExplicit() {
  102. return row.hashCode();
  103. }
  104. @Override
  105. public void updateRow() {
  106. getHandlers()
  107. .forEach(dch -> dch.dataUpdated(ds.indexOf(getRow()), 1));
  108. }
  109. }
  110. /**
  111. * Wraps the datasource list and notifies the change handler of changing to
  112. * the list
  113. */
  114. private class ListWrapper implements List<T> {
  115. @Override
  116. public int size() {
  117. return ds.size();
  118. }
  119. @Override
  120. public boolean isEmpty() {
  121. return ds.isEmpty();
  122. }
  123. @Override
  124. public boolean contains(Object o) {
  125. return ds.contains(o);
  126. }
  127. @Override
  128. public Iterator<T> iterator() {
  129. return new ListWrapperIterator(ds.iterator());
  130. }
  131. @Override
  132. public Object[] toArray() {
  133. return ds.toArray();
  134. }
  135. @Override
  136. @SuppressWarnings("hiding")
  137. public <T> T[] toArray(T[] a) {
  138. return ds.toArray(a);
  139. }
  140. @Override
  141. public boolean add(T e) {
  142. if (ds.add(e)) {
  143. getHandlers().forEach(dch -> dch.dataAdded(ds.size() - 1, 1));
  144. return true;
  145. }
  146. return false;
  147. }
  148. @Override
  149. public boolean remove(Object o) {
  150. int index = ds.indexOf(o);
  151. if (ds.remove(o)) {
  152. getHandlers().forEach(dch -> dch.dataRemoved(index, 1));
  153. return true;
  154. }
  155. return false;
  156. }
  157. @Override
  158. public boolean containsAll(Collection<?> c) {
  159. return ds.containsAll(c);
  160. }
  161. @Override
  162. public boolean addAll(Collection<? extends T> c) {
  163. int idx = ds.size();
  164. if (ds.addAll(c)) {
  165. getHandlers().forEach(dch -> dch.dataAdded(idx, c.size()));
  166. return true;
  167. }
  168. return false;
  169. }
  170. @Override
  171. public boolean addAll(int index, Collection<? extends T> c) {
  172. if (ds.addAll(index, c)) {
  173. getHandlers().forEach(dch -> dch.dataAdded(index, c.size()));
  174. return true;
  175. }
  176. return false;
  177. }
  178. @Override
  179. public boolean removeAll(Collection<?> c) {
  180. if (ds.removeAll(c)) {
  181. getHandlers().forEach(dch -> dch.dataUpdated(0, ds.size()));
  182. getHandlers().forEach(dch -> dch.dataAvailable(0, ds.size()));
  183. return true;
  184. }
  185. return false;
  186. }
  187. @Override
  188. public boolean retainAll(Collection<?> c) {
  189. if (ds.retainAll(c)) {
  190. getHandlers().forEach(dch -> dch.dataUpdated(0, ds.size()));
  191. getHandlers().forEach(dch -> dch.dataAvailable(0, ds.size()));
  192. return true;
  193. }
  194. return false;
  195. }
  196. @Override
  197. public void clear() {
  198. int size = ds.size();
  199. ds.clear();
  200. getHandlers().forEach(dch -> dch.dataRemoved(0, size));
  201. }
  202. @Override
  203. public T get(int index) {
  204. return ds.get(index);
  205. }
  206. @Override
  207. public T set(int index, T element) {
  208. T prev = ds.set(index, element);
  209. getHandlers().forEach(dch -> dch.dataUpdated(index, 1));
  210. return prev;
  211. }
  212. @Override
  213. public void add(int index, T element) {
  214. ds.add(index, element);
  215. getHandlers().forEach(dch -> dch.dataAdded(index, 1));
  216. }
  217. @Override
  218. public T remove(int index) {
  219. T removed = ds.remove(index);
  220. getHandlers().forEach(dch -> dch.dataRemoved(index, 1));
  221. return removed;
  222. }
  223. @Override
  224. public int indexOf(Object o) {
  225. return ds.indexOf(o);
  226. }
  227. @Override
  228. public int lastIndexOf(Object o) {
  229. return ds.lastIndexOf(o);
  230. }
  231. @Override
  232. public ListIterator<T> listIterator() {
  233. // TODO could be implemented by a custom iterator.
  234. throw new UnsupportedOperationException(
  235. "List iterators not supported at this time.");
  236. }
  237. @Override
  238. public ListIterator<T> listIterator(int index) {
  239. // TODO could be implemented by a custom iterator.
  240. throw new UnsupportedOperationException(
  241. "List iterators not supported at this time.");
  242. }
  243. @Override
  244. public List<T> subList(int fromIndex, int toIndex) {
  245. throw new UnsupportedOperationException("Sub lists not supported.");
  246. }
  247. }
  248. /**
  249. * Iterator returned by {@link ListWrapper}
  250. */
  251. private class ListWrapperIterator implements Iterator<T> {
  252. private final Iterator<T> iterator;
  253. /**
  254. * Constructs a new iterator
  255. */
  256. public ListWrapperIterator(Iterator<T> iterator) {
  257. this.iterator = iterator;
  258. }
  259. @Override
  260. public boolean hasNext() {
  261. return iterator.hasNext();
  262. }
  263. @Override
  264. public T next() {
  265. return iterator.next();
  266. }
  267. @Override
  268. public void remove() {
  269. throw new UnsupportedOperationException(
  270. "Iterator.remove() is not supported by this iterator.");
  271. }
  272. }
  273. /**
  274. * Datasource for providing row pojo's
  275. */
  276. private final List<T> ds;
  277. /**
  278. * Wrapper that wraps the data source
  279. */
  280. private final ListWrapper wrapper;
  281. /**
  282. * Handler for listening to changes in the underlying list.
  283. */
  284. private Set<DataChangeHandler> changeHandlers = new LinkedHashSet<>();
  285. /**
  286. * Constructs a new list data source.
  287. * <p>
  288. * Note: Modifications to the original list will not be reflected in the
  289. * data source after the data source has been constructed. To add or remove
  290. * items to the data source after it has been constructed use
  291. * {@link ListDataSource#asList()}.
  292. *
  293. *
  294. * @param datasource
  295. * The list to use for providing the data to the grid
  296. */
  297. public ListDataSource(List<T> datasource) {
  298. if (datasource == null) {
  299. throw new IllegalArgumentException("datasource cannot be null");
  300. }
  301. ds = new ArrayList<T>(datasource);
  302. wrapper = new ListWrapper();
  303. }
  304. /**
  305. * Constructs a data source with a set of rows. You can dynamically add and
  306. * remove rows from the data source via the list you get from
  307. * {@link ListDataSource#asList()}
  308. *
  309. * @param rows
  310. * The rows to initially add to the data source
  311. */
  312. public ListDataSource(T... rows) {
  313. if (rows == null) {
  314. ds = new ArrayList<T>();
  315. } else {
  316. ds = new ArrayList<T>(Arrays.asList(rows));
  317. }
  318. wrapper = new ListWrapper();
  319. }
  320. @Override
  321. public void ensureAvailability(int firstRowIndex, int numberOfRows) {
  322. if (firstRowIndex >= ds.size()) {
  323. throw new IllegalStateException(
  324. "Trying to fetch rows outside of array");
  325. }
  326. getHandlers()
  327. .forEach(dch -> dch.dataAvailable(firstRowIndex, numberOfRows));
  328. }
  329. @Override
  330. public T getRow(int rowIndex) {
  331. return ds.get(rowIndex);
  332. }
  333. @Override
  334. public int size() {
  335. return ds.size();
  336. }
  337. @Override
  338. public Registration addDataChangeHandler(
  339. DataChangeHandler dataChangeHandler) {
  340. Objects.requireNonNull(dataChangeHandler,
  341. "DataChangeHandler can't be null");
  342. changeHandlers.add(dataChangeHandler);
  343. return () -> changeHandlers.remove(dataChangeHandler);
  344. }
  345. /**
  346. * Gets the list that backs this datasource. Any changes made to this list
  347. * will be reflected in the datasource.
  348. * <p>
  349. * Note: The list is not the same list as passed into the data source via
  350. * the constructor.
  351. *
  352. * @return Returns a list implementation that wraps the real list that backs
  353. * the data source and provides events for the data source
  354. * listeners.
  355. */
  356. public List<T> asList() {
  357. return wrapper;
  358. }
  359. @Override
  360. public RowHandle<T> getHandle(T row) throws IllegalStateException {
  361. assert ds.contains(row) : "This data source doesn't contain the row "
  362. + row;
  363. return new RowHandleImpl(row);
  364. }
  365. /**
  366. * Sort entire container according to a {@link Comparator}.
  367. *
  368. * @param comparator
  369. * a comparator object, which compares two data source entries
  370. * (beans/pojos)
  371. */
  372. public void sort(Comparator<T> comparator) {
  373. Collections.sort(ds, comparator);
  374. getHandlers().forEach(dch -> dch.dataUpdated(0, ds.size()));
  375. }
  376. /**
  377. * Retrieves the index for given row object.
  378. * <p>
  379. * <em>Note:</em> This method does not verify that the given row object
  380. * exists at all in this DataSource.
  381. *
  382. * @param row
  383. * the row object
  384. * @return index of the row; or <code>-1</code> if row is not available
  385. */
  386. public int indexOf(T row) {
  387. return ds.indexOf(row);
  388. }
  389. /**
  390. * Returns a {@link SelectAllHandler} for this ListDataSource.
  391. *
  392. * @return select all handler
  393. */
  394. public SelectAllHandler<T> getSelectAllHandler() {
  395. return new SelectAllHandler<T>() {
  396. @Override
  397. public void onSelectAll(SelectAllEvent<T> event) {
  398. event.getSelectionModel().select(asList());
  399. }
  400. };
  401. }
  402. private Stream<DataChangeHandler> getHandlers() {
  403. Set<DataChangeHandler> copy = new LinkedHashSet<>(changeHandlers);
  404. return copy.stream();
  405. }
  406. }