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.

DataCommunicator.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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.io.Serializable;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Comparator;
  21. import java.util.HashSet;
  22. import java.util.LinkedHashSet;
  23. import java.util.List;
  24. import java.util.Objects;
  25. import java.util.Set;
  26. import java.util.stream.Collectors;
  27. import java.util.stream.Stream;
  28. import com.vaadin.data.provider.DataChangeEvent.DataRefreshEvent;
  29. import com.vaadin.server.AbstractExtension;
  30. import com.vaadin.server.KeyMapper;
  31. import com.vaadin.server.SerializableConsumer;
  32. import com.vaadin.shared.Range;
  33. import com.vaadin.shared.Registration;
  34. import com.vaadin.shared.data.DataCommunicatorClientRpc;
  35. import com.vaadin.shared.data.DataCommunicatorConstants;
  36. import com.vaadin.shared.data.DataRequestRpc;
  37. import com.vaadin.shared.extension.datacommunicator.DataCommunicatorState;
  38. import elemental.json.Json;
  39. import elemental.json.JsonArray;
  40. import elemental.json.JsonObject;
  41. /**
  42. * DataProvider base class. This class is the base for all DataProvider
  43. * communication implementations. It uses {@link DataGenerator}s to write
  44. * {@link JsonObject}s representing each data object to be sent to the
  45. * client-side.
  46. *
  47. * @param <T>
  48. * the bean type
  49. *
  50. * @since 8.0
  51. */
  52. public class DataCommunicator<T> extends AbstractExtension {
  53. private Registration dataProviderUpdateRegistration;
  54. /**
  55. * Simple implementation of collection data provider communication. All data
  56. * is sent by server automatically and no data is requested by client.
  57. */
  58. protected class SimpleDataRequestRpc implements DataRequestRpc {
  59. @Override
  60. public void requestRows(int firstRowIndex, int numberOfRows,
  61. int firstCachedRowIndex, int cacheSize) {
  62. onRequestRows(firstRowIndex, numberOfRows, firstCachedRowIndex,
  63. cacheSize);
  64. }
  65. @Override
  66. public void dropRows(JsonArray keys) {
  67. onDropRows(keys);
  68. }
  69. }
  70. /**
  71. * A class for handling currently active data and dropping data that is no
  72. * longer needed. Data tracking is based on key string provided by
  73. * {@link DataKeyMapper}.
  74. * <p>
  75. * When the {@link DataCommunicator} is pushing new data to the client-side
  76. * via {@link DataCommunicator#pushData(int, Stream)},
  77. * {@link #addActiveData(Stream)} and {@link #cleanUp(Stream)} are called
  78. * with the same parameter. In the clean up method any dropped data objects
  79. * that are not in the given collection will be cleaned up and
  80. * {@link DataGenerator#destroyData(Object)} will be called for them.
  81. */
  82. protected class ActiveDataHandler
  83. implements Serializable, DataGenerator<T> {
  84. /**
  85. * Set of key strings for currently active data objects
  86. */
  87. private final Set<String> activeData = new HashSet<>();
  88. /**
  89. * Set of key strings for data objects dropped on the client. This set
  90. * is used to clean up old data when it's no longer needed.
  91. */
  92. private final Set<String> droppedData = new HashSet<>();
  93. /**
  94. * Adds given objects as currently active objects.
  95. *
  96. * @param dataObjects
  97. * collection of new active data objects
  98. */
  99. public void addActiveData(Stream<T> dataObjects) {
  100. dataObjects.map(getKeyMapper()::key)
  101. .filter(key -> !activeData.contains(key))
  102. .forEach(activeData::add);
  103. }
  104. /**
  105. * Executes the data destruction for dropped data that is not sent to
  106. * the client. This method takes most recently sent data objects in a
  107. * collection. Doing the clean up like this prevents the
  108. * {@link ActiveDataHandler} from creating new keys for rows that were
  109. * dropped but got re-requested by the client-side. In the case of
  110. * having all data at the client, the collection should be all the data
  111. * in the back end.
  112. *
  113. * @param dataObjects
  114. * collection of most recently sent data to the client
  115. */
  116. public void cleanUp(Stream<T> dataObjects) {
  117. Collection<String> keys = dataObjects.map(getKeyMapper()::key)
  118. .collect(Collectors.toSet());
  119. // Remove still active rows that were dropped by the client
  120. droppedData.removeAll(keys);
  121. // Do data clean up for object no longer needed.
  122. dropData(droppedData);
  123. droppedData.clear();
  124. }
  125. /**
  126. * Marks a data object identified by given key string to be dropped.
  127. *
  128. * @param key
  129. * key string
  130. */
  131. public void dropActiveData(String key) {
  132. if (activeData.contains(key)) {
  133. droppedData.add(key);
  134. }
  135. }
  136. /**
  137. * Returns the collection of all currently active data.
  138. *
  139. * @return collection of active data objects
  140. */
  141. public Collection<T> getActiveData() {
  142. HashSet<T> hashSet = new HashSet<>();
  143. for (String key : activeData) {
  144. hashSet.add(getKeyMapper().get(key));
  145. }
  146. return hashSet;
  147. }
  148. @Override
  149. public void generateData(T data, JsonObject jsonObject) {
  150. // Write the key string for given data object
  151. jsonObject.put(DataCommunicatorConstants.KEY,
  152. getKeyMapper().key(data));
  153. }
  154. @Override
  155. public void destroyData(T data) {
  156. // Remove from active data set
  157. activeData.remove(getKeyMapper().key(data));
  158. // Drop the registered key
  159. getKeyMapper().remove(data);
  160. }
  161. @Override
  162. public void destroyAllData() {
  163. activeData.clear();
  164. getKeyMapper().removeAll();
  165. }
  166. }
  167. private final Collection<DataGenerator<T>> generators = new LinkedHashSet<>();
  168. private final ActiveDataHandler handler = new ActiveDataHandler();
  169. /** Empty default data provider */
  170. protected DataProvider<T, ?> dataProvider = new CallbackDataProvider<>(
  171. q -> Stream.empty(), q -> 0);
  172. private final DataKeyMapper<T> keyMapper;
  173. protected boolean reset = false;
  174. private final Set<T> updatedData = new HashSet<>();
  175. private int minPushSize = 40;
  176. private Range pushRows = Range.withLength(0, minPushSize);
  177. private Object filter;
  178. private Comparator<T> inMemorySorting;
  179. private final List<QuerySortOrder> backEndSorting = new ArrayList<>();
  180. private final DataCommunicatorClientRpc rpc;
  181. public DataCommunicator() {
  182. addDataGenerator(handler);
  183. rpc = getRpcProxy(DataCommunicatorClientRpc.class);
  184. registerRpc(createRpc());
  185. keyMapper = createKeyMapper();
  186. }
  187. @Override
  188. public void attach() {
  189. super.attach();
  190. attachDataProviderListener();
  191. }
  192. @Override
  193. public void detach() {
  194. super.detach();
  195. detachDataProviderListener();
  196. }
  197. /**
  198. * Set the range of rows to push for next response.
  199. *
  200. * @param pushRows
  201. */
  202. protected void setPushRows(Range pushRows) {
  203. this.pushRows = pushRows;
  204. }
  205. /**
  206. * Get the current range of rows to push in the next response.
  207. *
  208. * @return the range of rows to push
  209. */
  210. protected Range getPushRows() {
  211. return pushRows;
  212. }
  213. /**
  214. * Get the object used for filtering in this data communicator.
  215. *
  216. * @return the filter object of this data communicator
  217. */
  218. protected Object getFilter() {
  219. return filter;
  220. }
  221. /**
  222. * Get the client rpc interface for this data communicator.
  223. *
  224. * @return the client rpc interface for this data communicator
  225. */
  226. protected DataCommunicatorClientRpc getClientRpc() {
  227. return rpc;
  228. }
  229. /**
  230. * Request the given rows to be available on the client side.
  231. *
  232. * @param firstRowIndex
  233. * the index of the first requested row
  234. * @param numberOfRows
  235. * the number of requested rows
  236. * @param firstCachedRowIndex
  237. * the index of the first cached row
  238. * @param cacheSize
  239. * the number of cached rows
  240. */
  241. protected void onRequestRows(int firstRowIndex, int numberOfRows,
  242. int firstCachedRowIndex, int cacheSize) {
  243. setPushRows(Range.withLength(firstRowIndex, numberOfRows));
  244. markAsDirty();
  245. }
  246. /**
  247. * Triggered when rows have been dropped from the client side cache.
  248. *
  249. * @param keys
  250. * the keys of the rows that have been dropped
  251. */
  252. protected void onDropRows(JsonArray keys) {
  253. for (int i = 0; i < keys.length(); ++i) {
  254. handler.dropActiveData(keys.getString(i));
  255. }
  256. }
  257. /**
  258. * Initially and in the case of a reset all data should be pushed to the
  259. * client.
  260. */
  261. @Override
  262. public void beforeClientResponse(boolean initial) {
  263. super.beforeClientResponse(initial);
  264. sendDataToClient(initial);
  265. }
  266. /**
  267. * Send the needed data and updates to the client side.
  268. *
  269. * @param initial
  270. * {@code true} if initial data load, {@code false} if not
  271. */
  272. protected void sendDataToClient(boolean initial) {
  273. if (getDataProvider() == null) {
  274. return;
  275. }
  276. if (initial || reset) {
  277. @SuppressWarnings({ "rawtypes", "unchecked" })
  278. int dataProviderSize = getDataProvider().size(new Query(filter));
  279. rpc.reset(dataProviderSize);
  280. }
  281. Range requestedRows = getPushRows();
  282. if (!requestedRows.isEmpty()) {
  283. int offset = requestedRows.getStart();
  284. int limit = requestedRows.length();
  285. @SuppressWarnings({ "rawtypes", "unchecked" })
  286. Stream<T> rowsToPush = getDataProvider().fetch(new Query(offset,
  287. limit, backEndSorting, inMemorySorting, filter));
  288. pushData(offset, rowsToPush);
  289. }
  290. if (!updatedData.isEmpty()) {
  291. JsonArray dataArray = Json.createArray();
  292. int i = 0;
  293. for (T data : updatedData) {
  294. dataArray.set(i++, getDataObject(data));
  295. }
  296. rpc.updateData(dataArray);
  297. }
  298. setPushRows(Range.withLength(0, 0));
  299. reset = false;
  300. updatedData.clear();
  301. }
  302. /**
  303. * Adds a data generator to this data communicator. Data generators can be
  304. * used to insert custom data to the rows sent to the client. If the data
  305. * generator is already added, does nothing.
  306. *
  307. * @param generator
  308. * the data generator to add, not null
  309. */
  310. public void addDataGenerator(DataGenerator<T> generator) {
  311. Objects.requireNonNull(generator, "generator cannot be null");
  312. generators.add(generator);
  313. }
  314. /**
  315. * Removes a data generator from this data communicator. If there is no such
  316. * data generator, does nothing.
  317. *
  318. * @param generator
  319. * the data generator to remove, not null
  320. */
  321. public void removeDataGenerator(DataGenerator<T> generator) {
  322. Objects.requireNonNull(generator, "generator cannot be null");
  323. generators.remove(generator);
  324. }
  325. /**
  326. * Gets the {@link DataKeyMapper} used by this {@link DataCommunicator}. Key
  327. * mapper can be used to map keys sent to the client-side back to their
  328. * respective data objects.
  329. *
  330. * @return key mapper
  331. */
  332. public DataKeyMapper<T> getKeyMapper() {
  333. return keyMapper;
  334. }
  335. /**
  336. * Sends given collection of data objects to the client-side.
  337. *
  338. * @param firstIndex
  339. * first index of pushed data
  340. * @param data
  341. * data objects to send as an iterable
  342. */
  343. protected void pushData(int firstIndex, Stream<T> data) {
  344. JsonArray dataArray = Json.createArray();
  345. int i = 0;
  346. List<T> collected = data.collect(Collectors.toList());
  347. for (T item : collected) {
  348. dataArray.set(i++, getDataObject(item));
  349. }
  350. rpc.setData(firstIndex, dataArray);
  351. handler.addActiveData(collected.stream());
  352. handler.cleanUp(collected.stream());
  353. }
  354. /**
  355. * Creates the JsonObject for given data object. This method calls all data
  356. * generators for it.
  357. *
  358. * @param data
  359. * data object to be made into a json object
  360. * @return json object representing the data object
  361. */
  362. protected JsonObject getDataObject(T data) {
  363. JsonObject dataObject = Json.createObject();
  364. for (DataGenerator<T> generator : generators) {
  365. generator.generateData(data, dataObject);
  366. }
  367. return dataObject;
  368. }
  369. /**
  370. * Returns the active data handler.
  371. *
  372. * @return the active data handler
  373. */
  374. protected ActiveDataHandler getActiveDataHandler() {
  375. return handler;
  376. }
  377. /**
  378. * Drops data objects identified by given keys from memory. This will invoke
  379. * {@link DataGenerator#destroyData} for each of those objects.
  380. *
  381. * @param droppedKeys
  382. * collection of dropped keys
  383. */
  384. private void dropData(Collection<String> droppedKeys) {
  385. for (String key : droppedKeys) {
  386. assert key != null : "Bookkeepping failure. Dropping a null key";
  387. T data = getKeyMapper().get(key);
  388. assert data != null : "Bookkeepping failure. No data object to match key";
  389. for (DataGenerator<T> g : generators) {
  390. g.destroyData(data);
  391. }
  392. }
  393. }
  394. private void dropAllData() {
  395. for (DataGenerator<T> g : generators) {
  396. g.destroyAllData();
  397. }
  398. handler.destroyAllData();
  399. }
  400. /**
  401. * Informs the DataProvider that the collection has changed.
  402. */
  403. public void reset() {
  404. if (reset) {
  405. return;
  406. }
  407. reset = true;
  408. markAsDirty();
  409. }
  410. /**
  411. * Informs the DataProvider that a data object has been updated.
  412. *
  413. * @param data
  414. * updated data object
  415. */
  416. public void refresh(T data) {
  417. if (!handler.getActiveData().contains(data)) {
  418. // Item is not currently available at the client-side
  419. return;
  420. }
  421. if (updatedData.isEmpty()) {
  422. markAsDirty();
  423. }
  424. updatedData.add(data);
  425. }
  426. /**
  427. * Returns the currently set updated data.
  428. *
  429. * @return the set of data that should be updated on the next response
  430. */
  431. protected Set<T> getUpdatedData() {
  432. return updatedData;
  433. }
  434. /**
  435. * Sets the {@link Comparator} to use with in-memory sorting.
  436. *
  437. * @param comparator
  438. * comparator used to sort data
  439. */
  440. public void setInMemorySorting(Comparator<T> comparator) {
  441. inMemorySorting = comparator;
  442. reset();
  443. }
  444. /**
  445. * Returns the {@link Comparator} to use with in-memory sorting.
  446. *
  447. * @return comparator used to sort data
  448. */
  449. public Comparator<T> getInMemorySorting() {
  450. return inMemorySorting;
  451. }
  452. /**
  453. * Sets the {@link QuerySortOrder}s to use with backend sorting.
  454. *
  455. * @param sortOrder
  456. * list of sort order information to pass to a query
  457. */
  458. public void setBackEndSorting(List<QuerySortOrder> sortOrder) {
  459. backEndSorting.clear();
  460. backEndSorting.addAll(sortOrder);
  461. reset();
  462. }
  463. /**
  464. * Returns the {@link QuerySortOrder} to use with backend sorting.
  465. *
  466. * @return list of sort order information to pass to a query
  467. */
  468. public List<QuerySortOrder> getBackEndSorting() {
  469. return backEndSorting;
  470. }
  471. /**
  472. * Creates a {@link DataKeyMapper} to use with this DataCommunicator.
  473. * <p>
  474. * This method is called from the constructor.
  475. *
  476. * @return key mapper
  477. */
  478. protected DataKeyMapper<T> createKeyMapper() {
  479. return new KeyMapper<>();
  480. }
  481. /**
  482. * Creates a {@link DataRequestRpc} used with this {@link DataCommunicator}.
  483. * <p>
  484. * This method is called from the constructor.
  485. *
  486. * @return data request rpc implementation
  487. */
  488. protected DataRequestRpc createRpc() {
  489. return new SimpleDataRequestRpc();
  490. }
  491. /**
  492. * Gets the current data provider from this DataCommunicator.
  493. *
  494. * @return the data provider
  495. */
  496. public DataProvider<T, ?> getDataProvider() {
  497. return dataProvider;
  498. }
  499. /**
  500. * Sets the current data provider for this DataCommunicator.
  501. * <p>
  502. * The returned consumer can be used to set some other filter value that
  503. * should be included in queries sent to the data provider. It is only valid
  504. * until another data provider is set.
  505. *
  506. * @param dataProvider
  507. * the data provider to set, not <code>null</code>
  508. * @param initialFilter
  509. * the initial filter value to use, or <code>null</code> to not
  510. * use any initial filter value
  511. *
  512. * @param <F>
  513. * the filter type
  514. *
  515. * @return a consumer that accepts a new filter value to use
  516. */
  517. public <F> SerializableConsumer<F> setDataProvider(
  518. DataProvider<T, F> dataProvider, F initialFilter) {
  519. Objects.requireNonNull(dataProvider, "data provider cannot be null");
  520. filter = initialFilter;
  521. detachDataProviderListener();
  522. dropAllData();
  523. this.dataProvider = dataProvider;
  524. /*
  525. * This introduces behavior which influence on the client-server
  526. * communication: now the very first response to the client will always
  527. * contain some data. If data provider has been set already then {@code
  528. * pushRows} is empty at this point. So without the next line the very
  529. * first response will be without data. And the client will request more
  530. * data in the next request after the response. The next line allows to
  531. * send some data (in the {@code pushRows} range) to the client even in
  532. * the very first response. This is necessary for disabled component
  533. * (and theoretically allows to the client doesn't request more data in
  534. * a happy path).
  535. */
  536. setPushRows(Range.between(0, getMinPushSize()));
  537. if (isAttached()) {
  538. attachDataProviderListener();
  539. }
  540. reset();
  541. return filter -> {
  542. if (this.dataProvider != dataProvider) {
  543. throw new IllegalStateException(
  544. "Filter slot is no longer valid after data provider has been changed");
  545. }
  546. if (!Objects.equals(this.filter, filter)) {
  547. this.filter = filter;
  548. reset();
  549. }
  550. };
  551. }
  552. /**
  553. * Set minimum size of data which will be sent to the client when data
  554. * source is set.
  555. * <p>
  556. * Server doesn't send all data from data source to the client. It sends
  557. * some initial chunk of data (whose size is determined as minimum between
  558. * {@code size} parameter of this method and data size). Client decides
  559. * whether it is able to show more data and request server to send more data
  560. * (next chunk).
  561. * <p>
  562. * When component is disabled then client cannot communicate to the server
  563. * side (by design, because of security reasons). It means that client will
  564. * get <b>only</b> initial chunk of data whose size is set here.
  565. *
  566. * @param size
  567. * the size of initial data to send to the client
  568. */
  569. public void setMinPushSize(int size) {
  570. if (size < 0) {
  571. throw new IllegalArgumentException("Value cannot be negative");
  572. }
  573. minPushSize = size;
  574. }
  575. /**
  576. * Get minimum size of data which will be sent to the client when data
  577. * source is set.
  578. *
  579. * @see #setMinPushSize(int)
  580. *
  581. * @return current minimum push size of initial data chunk which is sent to
  582. * the client when data source is set
  583. */
  584. public int getMinPushSize() {
  585. return minPushSize;
  586. }
  587. @Override
  588. protected DataCommunicatorState getState(boolean markAsDirty) {
  589. return (DataCommunicatorState) super.getState(markAsDirty);
  590. }
  591. @Override
  592. protected DataCommunicatorState getState() {
  593. return (DataCommunicatorState) super.getState();
  594. }
  595. private void attachDataProviderListener() {
  596. dataProviderUpdateRegistration = getDataProvider()
  597. .addDataProviderListener(event -> {
  598. getUI().access(() -> {
  599. if (event instanceof DataRefreshEvent) {
  600. T item = ((DataRefreshEvent<T>) event).getItem();
  601. generators.forEach(g -> g.refreshData(item));
  602. keyMapper.refresh(item, dataProvider::getId);
  603. refresh(item);
  604. } else {
  605. reset();
  606. }
  607. });
  608. });
  609. }
  610. private void detachDataProviderListener() {
  611. if (dataProviderUpdateRegistration != null) {
  612. dataProviderUpdateRegistration.remove();
  613. dataProviderUpdateRegistration = null;
  614. }
  615. }
  616. }