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.

HierarchicalDataCommunicator.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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.data.provider;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.HashSet;
  20. import java.util.List;
  21. import java.util.Objects;
  22. import java.util.Optional;
  23. import java.util.Set;
  24. import java.util.concurrent.atomic.AtomicInteger;
  25. import java.util.function.BiConsumer;
  26. import java.util.logging.Logger;
  27. import java.util.stream.Collectors;
  28. import java.util.stream.Stream;
  29. import com.vaadin.data.HierarchyData;
  30. import com.vaadin.data.provider.HierarchyMapper.TreeLevelQuery;
  31. import com.vaadin.data.provider.HierarchyMapper.TreeNode;
  32. import com.vaadin.server.SerializableConsumer;
  33. import com.vaadin.server.SerializablePredicate;
  34. import com.vaadin.shared.Range;
  35. import com.vaadin.shared.extension.datacommunicator.HierarchicalDataCommunicatorState;
  36. import com.vaadin.shared.ui.treegrid.TreeGridCommunicationConstants;
  37. import elemental.json.Json;
  38. import elemental.json.JsonArray;
  39. import elemental.json.JsonObject;
  40. /**
  41. * Data communicator that handles requesting hierarchical data from
  42. * {@link HierarchicalDataProvider} and sending it to client side.
  43. *
  44. * @param <T>
  45. * the bean type
  46. * @author Vaadin Ltd
  47. * @since 8.1
  48. */
  49. public class HierarchicalDataCommunicator<T> extends DataCommunicator<T> {
  50. private static final Logger LOGGER = Logger
  51. .getLogger(HierarchicalDataCommunicator.class.getName());
  52. /**
  53. * The amount of root level nodes to fetch and push to the client.
  54. */
  55. private static final int INITIAL_FETCH_SIZE = 100;
  56. private HierarchyMapper mapper = new HierarchyMapper();
  57. private Set<String> rowKeysPendingExpand = new HashSet<>();
  58. /**
  59. * Collapse allowed provider used to allow/disallow collapsing nodes.
  60. */
  61. private SerializablePredicate<T> itemCollapseAllowedProvider = t -> true;
  62. /**
  63. * The captured client side cache size.
  64. */
  65. private int latestCacheSize = INITIAL_FETCH_SIZE;
  66. /**
  67. * Construct a new hierarchical data communicator backed by a
  68. * {@link InMemoryHierarchicalDataProvider}.
  69. */
  70. public HierarchicalDataCommunicator() {
  71. super();
  72. dataProvider = new InMemoryHierarchicalDataProvider<>(
  73. new HierarchyData<>());
  74. }
  75. @Override
  76. protected HierarchicalDataCommunicatorState getState() {
  77. return (HierarchicalDataCommunicatorState) super.getState();
  78. }
  79. @Override
  80. protected HierarchicalDataCommunicatorState getState(boolean markAsDirty) {
  81. return (HierarchicalDataCommunicatorState) super.getState(markAsDirty);
  82. }
  83. @Override
  84. protected void sendDataToClient(boolean initial) {
  85. // on purpose do not call super
  86. if (getDataProvider() == null) {
  87. return;
  88. }
  89. if (initial || reset) {
  90. loadInitialData();
  91. } else {
  92. loadRequestedRows();
  93. }
  94. if (!getUpdatedData().isEmpty()) {
  95. JsonArray dataArray = Json.createArray();
  96. int i = 0;
  97. for (T data : getUpdatedData()) {
  98. dataArray.set(i++, createDataObject(data, -1));
  99. }
  100. getClientRpc().updateData(dataArray);
  101. getUpdatedData().clear();
  102. }
  103. }
  104. private void loadInitialData() {
  105. int rootSize = doSizeQuery(null);
  106. mapper.reset(rootSize);
  107. if (rootSize != 0) {
  108. Range initialRange = getInitialRowsToPush(rootSize);
  109. assert !initialRange
  110. .isEmpty() : "Initial range should never be empty.";
  111. Stream<T> rootItems = doFetchQuery(initialRange.getStart(),
  112. initialRange.length(), null);
  113. // for now just fetching data for the root level as everything is
  114. // collapsed by default
  115. List<T> items = rootItems.collect(Collectors.toList());
  116. List<JsonObject> dataObjects = items.stream()
  117. .map(item -> createDataObject(item, 0))
  118. .collect(Collectors.toList());
  119. getClientRpc().reset(rootSize);
  120. sendData(0, dataObjects);
  121. getActiveDataHandler().addActiveData(items.stream());
  122. getActiveDataHandler().cleanUp(items.stream());
  123. } else {
  124. getClientRpc().reset(0);
  125. }
  126. setPushRows(Range.withLength(0, 0));
  127. // any updated data is ignored at this point
  128. getUpdatedData().clear();
  129. reset = false;
  130. }
  131. private void loadRequestedRows() {
  132. final Range requestedRows = getPushRows();
  133. if (!requestedRows.isEmpty()) {
  134. doPushRows(requestedRows);
  135. }
  136. setPushRows(Range.withLength(0, 0));
  137. }
  138. private void doPushRows(final Range requestedRows) {
  139. Stream<TreeLevelQuery> levelQueries = mapper.splitRangeToLevelQueries(
  140. requestedRows.getStart(), requestedRows.getEnd() - 1);
  141. JsonObject[] dataObjects = new JsonObject[requestedRows.length()];
  142. BiConsumer<JsonObject, Integer> rowDataMapper = (object,
  143. index) -> dataObjects[index
  144. - requestedRows.getStart()] = object;
  145. List<T> fetchedItems = new ArrayList<>(dataObjects.length);
  146. levelQueries.forEach(query -> {
  147. List<T> results = doFetchQuery(query.startIndex, query.size,
  148. getKeyMapper().get(query.node.getParentKey()))
  149. .collect(Collectors.toList());
  150. // TODO if the size differers from expected, all goes to hell
  151. fetchedItems.addAll(results);
  152. List<JsonObject> rowData = results.stream()
  153. .map(item -> createDataObject(item, query.depth))
  154. .collect(Collectors.toList());
  155. mapper.reorderLevelQueryResultsToFlatOrdering(rowDataMapper, query,
  156. rowData);
  157. });
  158. verifyNoNullItems(dataObjects, requestedRows);
  159. sendData(requestedRows.getStart(), Arrays.asList(dataObjects));
  160. getActiveDataHandler().addActiveData(fetchedItems.stream());
  161. getActiveDataHandler().cleanUp(fetchedItems.stream());
  162. }
  163. /*
  164. * Verify that there are no null objects in the array, to fail eagerly and
  165. * not just on the client side.
  166. */
  167. private void verifyNoNullItems(JsonObject[] dataObjects,
  168. Range requestedRange) {
  169. List<Integer> nullItems = new ArrayList<>(0);
  170. AtomicInteger indexCounter = new AtomicInteger();
  171. Stream.of(dataObjects).forEach(object -> {
  172. int index = indexCounter.getAndIncrement();
  173. if (object == null) {
  174. nullItems.add(index);
  175. }
  176. });
  177. if (!nullItems.isEmpty()) {
  178. throw new IllegalStateException("For requested rows "
  179. + requestedRange + ", there was null items for indexes "
  180. + nullItems.stream().map(Object::toString)
  181. .collect(Collectors.joining(", ")));
  182. }
  183. }
  184. private JsonObject createDataObject(T item, int depth) {
  185. JsonObject dataObject = getDataObject(item);
  186. JsonObject hierarchyData = Json.createObject();
  187. if (depth != -1) {
  188. hierarchyData.put(TreeGridCommunicationConstants.ROW_DEPTH, depth);
  189. }
  190. boolean isLeaf = !getDataProvider().hasChildren(item);
  191. if (isLeaf) {
  192. hierarchyData.put(TreeGridCommunicationConstants.ROW_LEAF, true);
  193. } else {
  194. String key = getKeyMapper().key(item);
  195. hierarchyData.put(TreeGridCommunicationConstants.ROW_COLLAPSED,
  196. mapper.isCollapsed(key));
  197. hierarchyData.put(TreeGridCommunicationConstants.ROW_LEAF, false);
  198. hierarchyData.put(
  199. TreeGridCommunicationConstants.ROW_COLLAPSE_ALLOWED,
  200. itemCollapseAllowedProvider.test(item));
  201. }
  202. // add hierarchy information to row as metadata
  203. dataObject.put(TreeGridCommunicationConstants.ROW_HIERARCHY_DESCRIPTION,
  204. hierarchyData);
  205. return dataObject;
  206. }
  207. private void sendData(int startIndex, List<JsonObject> dataObjects) {
  208. JsonArray dataArray = Json.createArray();
  209. int i = 0;
  210. for (JsonObject dataObject : dataObjects) {
  211. dataArray.set(i++, dataObject);
  212. }
  213. getClientRpc().setData(startIndex, dataArray);
  214. }
  215. /**
  216. * Returns the range of rows to push on initial response.
  217. *
  218. * @param rootLevelSize
  219. * the amount of rows on the root level
  220. * @return the range of rows to push initially
  221. */
  222. private Range getInitialRowsToPush(int rootLevelSize) {
  223. // TODO optimize initial level to avoid unnecessary requests
  224. return Range.between(0, Math.min(rootLevelSize, latestCacheSize));
  225. }
  226. @SuppressWarnings({ "rawtypes", "unchecked" })
  227. private Stream<T> doFetchQuery(int start, int length, T parentItem) {
  228. return getDataProvider()
  229. .fetch(new HierarchicalQuery(start, length, getBackEndSorting(),
  230. getInMemorySorting(), getFilter(), parentItem));
  231. }
  232. @SuppressWarnings({ "unchecked", "rawtypes" })
  233. private int doSizeQuery(T parentItem) {
  234. return getDataProvider()
  235. .getChildCount(new HierarchicalQuery(getFilter(), parentItem));
  236. }
  237. @Override
  238. protected void onRequestRows(int firstRowIndex, int numberOfRows,
  239. int firstCachedRowIndex, int cacheSize) {
  240. super.onRequestRows(firstRowIndex, numberOfRows, firstCachedRowIndex,
  241. cacheSize);
  242. }
  243. @Override
  244. protected void onDropRows(JsonArray keys) {
  245. for (int i = 0; i < keys.length(); i++) {
  246. // cannot drop expanded rows since the parent item is needed always
  247. // when fetching more rows
  248. String itemKey = keys.getString(i);
  249. if (mapper.isCollapsed(itemKey) && !rowKeysPendingExpand.contains(itemKey)) {
  250. getActiveDataHandler().dropActiveData(itemKey);
  251. }
  252. }
  253. }
  254. @Override
  255. protected void dropAllData() {
  256. super.dropAllData();
  257. rowKeysPendingExpand.clear();
  258. }
  259. @Override
  260. public HierarchicalDataProvider<T, ?> getDataProvider() {
  261. return (HierarchicalDataProvider<T, ?>) super.getDataProvider();
  262. }
  263. /**
  264. * Set the current hierarchical data provider for this communicator.
  265. *
  266. * @param dataProvider
  267. * the data provider to set, not <code>null</code>
  268. * @param initialFilter
  269. * the initial filter value to use, or <code>null</code> to not
  270. * use any initial filter value
  271. *
  272. * @param <F>
  273. * the filter type
  274. *
  275. * @return a consumer that accepts a new filter value to use
  276. */
  277. public <F> SerializableConsumer<F> setDataProvider(
  278. HierarchicalDataProvider<T, F> dataProvider, F initialFilter) {
  279. return super.setDataProvider(dataProvider, initialFilter);
  280. }
  281. /**
  282. * Set the current hierarchical data provider for this communicator.
  283. *
  284. * @param dataProvider
  285. * the data provider to set, must extend
  286. * {@link HierarchicalDataProvider}, not <code>null</code>
  287. * @param initialFilter
  288. * the initial filter value to use, or <code>null</code> to not
  289. * use any initial filter value
  290. *
  291. * @param <F>
  292. * the filter type
  293. *
  294. * @return a consumer that accepts a new filter value to use
  295. */
  296. @Override
  297. public <F> SerializableConsumer<F> setDataProvider(
  298. DataProvider<T, F> dataProvider, F initialFilter) {
  299. if (dataProvider instanceof HierarchicalDataProvider) {
  300. return super.setDataProvider(dataProvider, initialFilter);
  301. }
  302. throw new IllegalArgumentException(
  303. "Only " + HierarchicalDataProvider.class.getName()
  304. + " and subtypes supported.");
  305. }
  306. /**
  307. * Collapses given row, removing all its subtrees. Calling this method will
  308. * have no effect if the row is already collapsed.
  309. *
  310. * @param collapsedRowKey
  311. * the key of the row, not {@code null}
  312. * @param collapsedRowIndex
  313. * the index of row to collapse
  314. * @return {@code true} if the row was collapsed, {@code false} otherwise
  315. */
  316. public boolean doCollapse(String collapsedRowKey, int collapsedRowIndex) {
  317. if (collapsedRowIndex < 0 | collapsedRowIndex >= mapper.getTreeSize()) {
  318. throw new IllegalArgumentException("Invalid row index "
  319. + collapsedRowIndex + " when tree grid size of "
  320. + mapper.getTreeSize());
  321. }
  322. Objects.requireNonNull(collapsedRowKey, "Row key cannot be null");
  323. T collapsedItem = getKeyMapper().get(collapsedRowKey);
  324. Objects.requireNonNull(collapsedItem,
  325. "Cannot find item for given key " + collapsedItem);
  326. if (mapper.isCollapsed(collapsedRowKey)) {
  327. return false;
  328. }
  329. int collapsedSubTreeSize = mapper.collapse(collapsedRowKey,
  330. collapsedRowIndex);
  331. getClientRpc().removeRows(collapsedRowIndex + 1,
  332. collapsedSubTreeSize);
  333. // FIXME seems like a slight overkill to do this just for refreshing
  334. // expanded status
  335. refresh(collapsedItem);
  336. return true;
  337. }
  338. /**
  339. * Expands the given row. Calling this method will have no effect if the row
  340. * is already expanded.
  341. *
  342. * @param expandedRowKey
  343. * the key of the row, not {@code null}
  344. * @param expandedRowIndex
  345. * the index of the row to expand
  346. * @return {@code true} if the row was expanded, {@code false} otherwise
  347. */
  348. public boolean doExpand(String expandedRowKey, final int expandedRowIndex) {
  349. if (expandedRowIndex < 0 | expandedRowIndex >= mapper.getTreeSize()) {
  350. throw new IllegalArgumentException("Invalid row index "
  351. + expandedRowIndex + " when tree grid size of "
  352. + mapper.getTreeSize());
  353. }
  354. Objects.requireNonNull(expandedRowKey, "Row key cannot be null");
  355. final T expandedItem = getKeyMapper().get(expandedRowKey);
  356. Objects.requireNonNull(expandedItem,
  357. "Cannot find item for given key " + expandedRowKey);
  358. final int expandedNodeSize = doSizeQuery(expandedItem);
  359. if (expandedNodeSize == 0) {
  360. // TODO handle 0 size -> not expandable
  361. throw new IllegalStateException("Row with index " + expandedRowIndex
  362. + " returned no child nodes.");
  363. }
  364. if (!mapper.isCollapsed(expandedRowKey)) {
  365. return false;
  366. }
  367. mapper.expand(expandedRowKey, expandedRowIndex, expandedNodeSize);
  368. rowKeysPendingExpand.remove(expandedRowKey);
  369. getClientRpc().insertRows(expandedRowIndex + 1, expandedNodeSize);
  370. // TODO optimize by sending "just enough" of the expanded items
  371. // directly
  372. doPushRows(
  373. Range.withLength(expandedRowIndex + 1, expandedNodeSize));
  374. // expanded node needs to be updated to be marked as expanded
  375. // FIXME seems like a slight overkill to do this just for refreshing
  376. // expanded status
  377. refresh(expandedItem);
  378. return true;
  379. }
  380. /**
  381. * Set an item as pending expansion.
  382. * <p>
  383. * Calling this method reserves a communication key for the item that is
  384. * guaranteed to not be invalidated until the item is expanded. Has no
  385. * effect and returns an empty optional if the given item is already
  386. * expanded or has no children.
  387. *
  388. * @param item
  389. * the item to set as pending expansion
  390. * @return an optional of the communication key used for the item, empty if
  391. * the item cannot be expanded
  392. */
  393. public Optional<String> setPendingExpand(T item) {
  394. Objects.requireNonNull(item, "Item cannot be null");
  395. if (getKeyMapper().has(item)
  396. && !mapper.isCollapsed(getKeyMapper().key(item))) {
  397. // item is already expanded
  398. return Optional.empty();
  399. }
  400. if (!getDataProvider().hasChildren(item)) {
  401. // ignore item with no children
  402. return Optional.empty();
  403. }
  404. String key = getKeyMapper().key(item);
  405. rowKeysPendingExpand.add(key);
  406. return Optional.of(key);
  407. }
  408. /**
  409. * Collapse an item.
  410. * <p>
  411. * This method will either collapse an item directly, or remove its pending
  412. * expand status. If the item is not expanded or pending expansion, calling
  413. * this method has no effect.
  414. *
  415. * @param item
  416. * the item to collapse
  417. * @return an optional of the communication key used for the item, empty if
  418. * the item cannot be collapsed
  419. */
  420. public Optional<String> collapseItem(T item) {
  421. Objects.requireNonNull(item, "Item cannot be null");
  422. if (!getKeyMapper().has(item)) {
  423. // keymapper should always have items that are expanded or pending
  424. // expand
  425. return Optional.empty();
  426. }
  427. String nodeKey = getKeyMapper().key(item);
  428. Optional<TreeNode> node = mapper.getNodeForKey(nodeKey);
  429. if (node.isPresent()) {
  430. rowKeysPendingExpand.remove(nodeKey);
  431. doCollapse(nodeKey, node.get().getStartIndex() - 1);
  432. return Optional.of(nodeKey);
  433. }
  434. if (rowKeysPendingExpand.contains(nodeKey)) {
  435. rowKeysPendingExpand.remove(nodeKey);
  436. return Optional.of(nodeKey);
  437. }
  438. return Optional.empty();
  439. }
  440. /**
  441. * Sets the item collapse allowed provider for this
  442. * HierarchicalDataCommunicator. The provider should return {@code true} for
  443. * any item that the user can collapse.
  444. * <p>
  445. * <strong>Note:</strong> This callback will be accessed often when sending
  446. * data to the client. The callback should not do any costly operations.
  447. *
  448. * @param provider
  449. * the item collapse allowed provider, not {@code null}
  450. */
  451. public void setItemCollapseAllowedProvider(
  452. SerializablePredicate<T> provider) {
  453. Objects.requireNonNull(provider, "Provider can't be null");
  454. itemCollapseAllowedProvider = provider;
  455. getActiveDataHandler().getActiveData().forEach(this::refresh);
  456. }
  457. /**
  458. * Returns parent index for the row or {@code null}
  459. *
  460. * @param rowIndex the row index
  461. * @return the parent index or {@code null} for top-level items
  462. */
  463. public Integer getParentIndex(int rowIndex) {
  464. return mapper.getParentIndex(rowIndex);
  465. }
  466. }