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 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. /*
  2. * Copyright 2000-2021 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.Collection;
  19. import java.util.Collections;
  20. import java.util.Comparator;
  21. import java.util.HashSet;
  22. import java.util.LinkedHashSet;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.Objects;
  26. import java.util.Set;
  27. import java.util.function.Function;
  28. import java.util.stream.Collectors;
  29. import java.util.stream.Stream;
  30. import com.vaadin.data.ValueProvider;
  31. import com.vaadin.data.provider.DataChangeEvent.DataRefreshEvent;
  32. import com.vaadin.server.AbstractExtension;
  33. import com.vaadin.server.KeyMapper;
  34. import com.vaadin.server.SerializableConsumer;
  35. import com.vaadin.shared.Range;
  36. import com.vaadin.shared.Registration;
  37. import com.vaadin.shared.data.DataCommunicatorClientRpc;
  38. import com.vaadin.shared.data.DataCommunicatorConstants;
  39. import com.vaadin.shared.data.DataRequestRpc;
  40. import com.vaadin.shared.extension.datacommunicator.DataCommunicatorState;
  41. import com.vaadin.ui.ComboBox;
  42. import elemental.json.Json;
  43. import elemental.json.JsonArray;
  44. import elemental.json.JsonObject;
  45. /**
  46. * DataProvider base class. This class is the base for all DataProvider
  47. * communication implementations. It uses {@link DataGenerator}s to write
  48. * {@link JsonObject}s representing each data object to be sent to the
  49. * client-side.
  50. *
  51. * @param <T>
  52. * the bean type
  53. *
  54. * @since 8.0
  55. */
  56. public class DataCommunicator<T> extends AbstractExtension {
  57. private Registration dataProviderUpdateRegistration;
  58. private static final int MAXIMUM_ALLOWED_ROWS = 500;
  59. /**
  60. * Simple implementation of collection data provider communication. All data
  61. * is sent by server automatically and no data is requested by client.
  62. */
  63. protected class SimpleDataRequestRpc implements DataRequestRpc {
  64. @Override
  65. public void requestRows(int firstRowIndex, int numberOfRows,
  66. int firstCachedRowIndex, int cacheSize) {
  67. onRequestRows(firstRowIndex, numberOfRows, firstCachedRowIndex,
  68. cacheSize);
  69. }
  70. @Override
  71. public void dropRows(JsonArray keys) {
  72. onDropRows(keys);
  73. }
  74. }
  75. /**
  76. * A class for handling currently active data and dropping data that is no
  77. * longer needed. Data tracking is based on key string provided by
  78. * {@link DataKeyMapper}.
  79. * <p>
  80. * When the {@link DataCommunicator} is pushing new data to the client-side
  81. * via {@link DataCommunicator#pushData(int, List)},
  82. * {@link #addActiveData(Stream)} and {@link #cleanUp(Stream)} are called
  83. * with the same parameter. In the clean up method any dropped data objects
  84. * that are not in the given collection will be cleaned up and
  85. * {@link DataGenerator#destroyData(Object)} will be called for them.
  86. */
  87. protected class ActiveDataHandler implements DataGenerator<T> {
  88. /**
  89. * Set of key strings for currently active data objects
  90. */
  91. private final Set<String> activeData = new HashSet<>();
  92. /**
  93. * Set of key strings for data objects dropped on the client. This set
  94. * is used to clean up old data when it's no longer needed.
  95. */
  96. private final Set<String> droppedData = new HashSet<>();
  97. /**
  98. * Adds given objects as currently active objects.
  99. *
  100. * @param dataObjects
  101. * collection of new active data objects
  102. */
  103. public void addActiveData(Stream<T> dataObjects) {
  104. dataObjects.map(getKeyMapper()::key)
  105. .filter(key -> !activeData.contains(key))
  106. .forEach(activeData::add);
  107. }
  108. /**
  109. * Executes the data destruction for dropped data that is not sent to
  110. * the client. This method takes most recently sent data objects in a
  111. * collection. Doing the clean up like this prevents the
  112. * {@link ActiveDataHandler} from creating new keys for rows that were
  113. * dropped but got re-requested by the client-side. In the case of
  114. * having all data at the client, the collection should be all the data
  115. * in the back end.
  116. *
  117. * @param dataObjects
  118. * collection of most recently sent data to the client
  119. */
  120. public void cleanUp(Stream<T> dataObjects) {
  121. Collection<String> keys = dataObjects.map(getKeyMapper()::key)
  122. .collect(Collectors.toSet());
  123. // Remove still active rows that were dropped by the client
  124. droppedData.removeAll(keys);
  125. // Do data clean up for object no longer needed.
  126. dropData(droppedData);
  127. droppedData.clear();
  128. }
  129. /**
  130. * Marks all currently active data objects to be dropped.
  131. *
  132. * @since 8.6.0
  133. */
  134. public void dropAllActiveData() {
  135. activeData.forEach(this::dropActiveData);
  136. }
  137. /**
  138. * Marks a data object identified by given key string to be dropped.
  139. *
  140. * @param key
  141. * key string
  142. */
  143. public void dropActiveData(String key) {
  144. if (activeData.contains(key)) {
  145. droppedData.add(key);
  146. }
  147. }
  148. /**
  149. * Returns all dropped data mapped by their id from DataProvider.
  150. *
  151. * @return map of ids to dropped data objects
  152. *
  153. * @since 8.6.0
  154. */
  155. protected Map<Object, T> getDroppedData() {
  156. Function<T, Object> getId = getDataProvider()::getId;
  157. return droppedData.stream().map(getKeyMapper()::get)
  158. .collect(Collectors.toMap(getId, i -> i));
  159. }
  160. /**
  161. * Returns all currently active data mapped by their id from
  162. * DataProvider.
  163. *
  164. * @return map of ids to active data objects
  165. */
  166. public Map<Object, T> getActiveData() {
  167. Function<T, Object> getId = getDataProvider()::getId;
  168. return activeData.stream().map(getKeyMapper()::get)
  169. .collect(Collectors.toMap(getId, i -> i));
  170. }
  171. @Override
  172. public void generateData(T data, JsonObject jsonObject) {
  173. // Make sure KeyMapper is up to date
  174. getKeyMapper().refresh(data);
  175. // Write the key string for given data object
  176. jsonObject.put(DataCommunicatorConstants.KEY,
  177. getKeyMapper().key(data));
  178. }
  179. @Override
  180. public void destroyData(T data) {
  181. // Remove from active data set
  182. activeData.remove(getKeyMapper().key(data));
  183. // Drop the registered key
  184. getKeyMapper().remove(data);
  185. }
  186. @Override
  187. public void destroyAllData() {
  188. droppedData.clear();
  189. activeData.clear();
  190. updatedData.clear();
  191. getKeyMapper().removeAll();
  192. }
  193. }
  194. private final Collection<DataGenerator<T>> generators = new LinkedHashSet<>();
  195. private final ActiveDataHandler handler = new ActiveDataHandler();
  196. /** Empty default data provider. */
  197. private DataProvider<T, ?> dataProvider = new CallbackDataProvider<>(
  198. q -> Stream.empty(), q -> 0);
  199. private final DataKeyMapper<T> keyMapper;
  200. /** Boolean for pending hard reset. */
  201. protected boolean reset = true;
  202. private final Set<T> updatedData = new HashSet<>();
  203. private int minPushSize = 40;
  204. private Range pushRows = Range.withLength(0, minPushSize);
  205. private Object filter;
  206. private Comparator<T> inMemorySorting;
  207. private final List<QuerySortOrder> backEndSorting = new ArrayList<>();
  208. private final DataCommunicatorClientRpc rpc;
  209. public DataCommunicator() {
  210. addDataGenerator(handler);
  211. rpc = getRpcProxy(DataCommunicatorClientRpc.class);
  212. registerRpc(createRpc());
  213. keyMapper = createKeyMapper(dataProvider::getId);
  214. }
  215. @Override
  216. public void attach() {
  217. super.attach();
  218. attachDataProviderListener();
  219. }
  220. @Override
  221. public void detach() {
  222. super.detach();
  223. detachDataProviderListener();
  224. }
  225. /**
  226. * Set the range of rows to push for next response.
  227. *
  228. * @param pushRows
  229. * @since 8.0.6
  230. */
  231. protected void setPushRows(Range pushRows) {
  232. this.pushRows = pushRows;
  233. }
  234. /**
  235. * Get the current range of rows to push in the next response.
  236. *
  237. * @return the range of rows to push
  238. * @since 8.0.6
  239. */
  240. protected Range getPushRows() {
  241. return pushRows;
  242. }
  243. /**
  244. * Get the object used for filtering in this data communicator.
  245. *
  246. * @return the filter object of this data communicator
  247. * @since 8.0.6
  248. */
  249. protected Object getFilter() {
  250. return filter;
  251. }
  252. /**
  253. * Get the client rpc interface for this data communicator.
  254. *
  255. * @return the client rpc interface for this data communicator
  256. * @since 8.0.6
  257. */
  258. protected DataCommunicatorClientRpc getClientRpc() {
  259. return rpc;
  260. }
  261. /**
  262. * Request the given rows to be available on the client side.
  263. *
  264. * @param firstRowIndex
  265. * the index of the first requested row
  266. * @param numberOfRows
  267. * the number of requested rows
  268. * @param firstCachedRowIndex
  269. * the index of the first cached row
  270. * @param cacheSize
  271. * the number of cached rows
  272. * @since 8.0.6
  273. */
  274. protected void onRequestRows(int firstRowIndex, int numberOfRows,
  275. int firstCachedRowIndex, int cacheSize) {
  276. if (numberOfRows > getMaximumAllowedRows()) {
  277. throw new IllegalStateException(
  278. "Client tried fetch more rows than allowed. This is denied to prevent denial of service.");
  279. }
  280. setPushRows(Range.withLength(firstRowIndex, numberOfRows));
  281. markAsDirty();
  282. }
  283. /**
  284. * Set the maximum allowed rows to be fetched in one query.
  285. *
  286. * @return Maximum allowed rows for one query.
  287. * @since 8.14.1
  288. */
  289. protected int getMaximumAllowedRows() {
  290. return MAXIMUM_ALLOWED_ROWS;
  291. }
  292. /**
  293. * Triggered when rows have been dropped from the client side cache.
  294. *
  295. * @param keys
  296. * the keys of the rows that have been dropped
  297. * @since 8.0.6
  298. */
  299. protected void onDropRows(JsonArray keys) {
  300. for (int i = 0; i < keys.length(); ++i) {
  301. handler.dropActiveData(keys.getString(i));
  302. }
  303. }
  304. /**
  305. * Initially and in the case of a reset all data should be pushed to the
  306. * client.
  307. */
  308. @Override
  309. public void beforeClientResponse(boolean initial) {
  310. super.beforeClientResponse(initial);
  311. if (initial && getPushRows().isEmpty()) {
  312. // Make sure rows are pushed when component is attached.
  313. setPushRows(Range.withLength(0, getMinPushSize()));
  314. }
  315. sendDataToClient(initial);
  316. }
  317. /**
  318. * Send the needed data and updates to the client side.
  319. *
  320. * @param initial
  321. * {@code true} if initial data load, {@code false} if not
  322. * @since 8.0.6
  323. */
  324. protected void sendDataToClient(boolean initial) {
  325. if (getDataProvider() == null) {
  326. return;
  327. }
  328. if (initial || reset) {
  329. if (reset) {
  330. handler.dropAllActiveData();
  331. }
  332. rpc.reset(getDataProviderSize());
  333. }
  334. if (!updatedData.isEmpty()) {
  335. JsonArray dataArray = Json.createArray();
  336. int i = 0;
  337. for (T data : updatedData) {
  338. dataArray.set(i++, getDataObject(data));
  339. }
  340. rpc.updateData(dataArray);
  341. }
  342. Range requestedRows = getPushRows();
  343. boolean triggerReset = false;
  344. if (!requestedRows.isEmpty()) {
  345. int offset = requestedRows.getStart();
  346. int limit = requestedRows.length();
  347. List<T> rowsToPush = fetchItemsWithRange(offset, limit);
  348. if (!initial && !reset && rowsToPush.isEmpty()) {
  349. triggerReset = true;
  350. }
  351. pushData(offset, rowsToPush);
  352. }
  353. setPushRows(Range.withLength(0, 0));
  354. reset = triggerReset;
  355. updatedData.clear();
  356. }
  357. /**
  358. * Fetches a list of items from the DataProvider.
  359. *
  360. * @param offset
  361. * the starting index of the range
  362. * @param limit
  363. * the max number of results
  364. * @return the list of items in given range
  365. *
  366. * @since 8.1
  367. */
  368. @SuppressWarnings({ "rawtypes", "unchecked" })
  369. public List<T> fetchItemsWithRange(int offset, int limit) {
  370. return (List<T>) getDataProvider().fetch(new Query(offset, limit,
  371. backEndSorting, inMemorySorting, filter))
  372. .collect(Collectors.toList());
  373. }
  374. /**
  375. * Adds a data generator to this data communicator. Data generators can be
  376. * used to insert custom data to the rows sent to the client. If the data
  377. * generator is already added, does nothing.
  378. *
  379. * @param generator
  380. * the data generator to add, not null
  381. */
  382. public void addDataGenerator(DataGenerator<T> generator) {
  383. Objects.requireNonNull(generator, "generator cannot be null");
  384. generators.add(generator);
  385. // Make sure data gets generated when adding data generators.
  386. reset();
  387. }
  388. /**
  389. * Removes a data generator from this data communicator. If there is no such
  390. * data generator, does nothing.
  391. *
  392. * @param generator
  393. * the data generator to remove, not null
  394. */
  395. public void removeDataGenerator(DataGenerator<T> generator) {
  396. Objects.requireNonNull(generator, "generator cannot be null");
  397. generators.remove(generator);
  398. }
  399. /**
  400. * Gets the {@link DataKeyMapper} used by this {@link DataCommunicator}. Key
  401. * mapper can be used to map keys sent to the client-side back to their
  402. * respective data objects.
  403. *
  404. * @return key mapper
  405. */
  406. public DataKeyMapper<T> getKeyMapper() {
  407. return keyMapper;
  408. }
  409. /**
  410. * Sends given collection of data objects to the client-side.
  411. *
  412. * @param firstIndex
  413. * first index of pushed data
  414. * @param data
  415. * data objects to send as an iterable
  416. */
  417. protected void pushData(int firstIndex, List<T> data) {
  418. JsonArray dataArray = Json.createArray();
  419. int i = 0;
  420. for (T item : data) {
  421. dataArray.set(i++, getDataObject(item));
  422. }
  423. rpc.setData(firstIndex, dataArray);
  424. handler.addActiveData(data.stream());
  425. handler.cleanUp(data.stream());
  426. }
  427. /**
  428. * Creates the JsonObject for given data object. This method calls all data
  429. * generators for it.
  430. *
  431. * @param data
  432. * data object to be made into a json object
  433. * @return json object representing the data object
  434. */
  435. protected JsonObject getDataObject(T data) {
  436. JsonObject dataObject = Json.createObject();
  437. for (DataGenerator<T> generator : generators) {
  438. generator.generateData(data, dataObject);
  439. }
  440. return dataObject;
  441. }
  442. /**
  443. * Returns the active data handler.
  444. *
  445. * @return the active data handler
  446. * @since 8.0.6
  447. */
  448. protected ActiveDataHandler getActiveDataHandler() {
  449. return handler;
  450. }
  451. /**
  452. * Drops data objects identified by given keys from memory. This will invoke
  453. * {@link DataGenerator#destroyData} for each of those objects.
  454. *
  455. * @param droppedKeys
  456. * collection of dropped keys
  457. */
  458. private void dropData(Collection<String> droppedKeys) {
  459. for (String key : droppedKeys) {
  460. assert key != null : "Bookkeepping failure. Dropping a null key";
  461. T data = getKeyMapper().get(key);
  462. assert data != null : "Bookkeepping failure. No data object to match key";
  463. for (DataGenerator<T> g : generators) {
  464. g.destroyData(data);
  465. }
  466. }
  467. }
  468. /**
  469. * Drops all data associated with this data communicator.
  470. */
  471. protected void dropAllData() {
  472. for (DataGenerator<T> g : generators) {
  473. g.destroyAllData();
  474. }
  475. handler.destroyAllData();
  476. }
  477. /**
  478. * Method for internal reset from a change in the component, requiring a
  479. * full data update.
  480. */
  481. public void reset() {
  482. // Only needed if a full reset is not pending.
  483. if (!reset) {
  484. if (getParent() instanceof ComboBox) {
  485. beforeClientResponse(true);
  486. }
  487. // Soft reset through client-side re-request.
  488. getClientRpc().reset(getDataProviderSize());
  489. }
  490. }
  491. /**
  492. * Informs the DataProvider that a data object has been updated.
  493. *
  494. * @param data
  495. * updated data object; not {@code null}
  496. */
  497. public void refresh(T data) {
  498. Objects.requireNonNull(data,
  499. "DataCommunicator can not refresh null object");
  500. Object id = getDataProvider().getId(data);
  501. // ActiveDataHandler has always the latest data through KeyMapper.
  502. Map<Object, T> activeData = getActiveDataHandler().getActiveData();
  503. if (activeData.containsKey(id)) {
  504. // Item is currently available at the client-side
  505. if (updatedData.isEmpty()) {
  506. markAsDirty();
  507. }
  508. updatedData.add(activeData.get(id));
  509. }
  510. }
  511. /**
  512. * Returns the currently set updated data.
  513. *
  514. * @return the set of data that should be updated on the next response
  515. * @since 8.0.6
  516. */
  517. protected Set<T> getUpdatedData() {
  518. return updatedData;
  519. }
  520. /**
  521. * Sets the {@link Comparator} to use with in-memory sorting.
  522. *
  523. * @param comparator
  524. * comparator used to sort data
  525. * @param immediateReset
  526. * {@code true} if an internal reset should be performed
  527. * immediately after updating the comparator (unless full reset
  528. * is already pending), {@code false} if you are going to trigger
  529. * reset separately later
  530. */
  531. public void setInMemorySorting(Comparator<T> comparator,
  532. boolean immediateReset) {
  533. inMemorySorting = comparator;
  534. if (immediateReset) {
  535. reset();
  536. }
  537. }
  538. /**
  539. * Sets the {@link Comparator} to use with in-memory sorting.
  540. *
  541. * @param comparator
  542. * comparator used to sort data
  543. */
  544. public void setInMemorySorting(Comparator<T> comparator) {
  545. setInMemorySorting(comparator, true);
  546. }
  547. /**
  548. * Returns the {@link Comparator} to use with in-memory sorting.
  549. *
  550. * @return comparator used to sort data
  551. * @since 8.0.6
  552. */
  553. public Comparator<T> getInMemorySorting() {
  554. return inMemorySorting;
  555. }
  556. /**
  557. * Sets the {@link QuerySortOrder}s to use with backend sorting.
  558. *
  559. * @param sortOrder
  560. * list of sort order information to pass to a query
  561. * @param immediateReset
  562. * {@code true} if an internal reset should be performed
  563. * immediately after updating the comparator (unless full reset
  564. * is already pending), {@code false} if you are going to trigger
  565. * reset separately later
  566. */
  567. public void setBackEndSorting(List<QuerySortOrder> sortOrder,
  568. boolean immediateReset) {
  569. backEndSorting.clear();
  570. backEndSorting.addAll(sortOrder);
  571. if (immediateReset) {
  572. reset();
  573. }
  574. }
  575. /**
  576. * Sets the {@link QuerySortOrder}s to use with backend sorting.
  577. *
  578. * @param sortOrder
  579. * list of sort order information to pass to a query
  580. */
  581. public void setBackEndSorting(List<QuerySortOrder> sortOrder) {
  582. setBackEndSorting(sortOrder, true);
  583. }
  584. /**
  585. * Returns the {@link QuerySortOrder} to use with backend sorting.
  586. *
  587. * @return an unmodifiable list of sort order information to pass to a query
  588. * @since 8.0.6
  589. */
  590. public List<QuerySortOrder> getBackEndSorting() {
  591. return Collections.unmodifiableList(backEndSorting);
  592. }
  593. /**
  594. * Creates a {@link DataKeyMapper} to use with this DataCommunicator.
  595. * <p>
  596. * This method is called from the constructor.
  597. *
  598. * @param identifierGetter
  599. * has to return a unique key for every bean, and the returned
  600. * key has to follow general {@code hashCode()} and
  601. * {@code equals()} contract, see {@link Object#hashCode()} for
  602. * details.
  603. * @return key mapper
  604. *
  605. * @since 8.1
  606. *
  607. */
  608. protected DataKeyMapper<T> createKeyMapper(
  609. ValueProvider<T, Object> identifierGetter) {
  610. return new KeyMapper<T>(identifierGetter);
  611. }
  612. /**
  613. * Creates a {@link DataRequestRpc} used with this {@link DataCommunicator}.
  614. * <p>
  615. * This method is called from the constructor.
  616. *
  617. * @return data request rpc implementation
  618. */
  619. protected DataRequestRpc createRpc() {
  620. return new SimpleDataRequestRpc();
  621. }
  622. /**
  623. * Gets the current data provider from this DataCommunicator.
  624. *
  625. * @return the data provider
  626. */
  627. public DataProvider<T, ?> getDataProvider() {
  628. return dataProvider;
  629. }
  630. /**
  631. * Sets the current data provider for this DataCommunicator.
  632. * <p>
  633. * The returned consumer can be used to set some other filter value that
  634. * should be included in queries sent to the data provider. It is only valid
  635. * until another data provider is set.
  636. *
  637. * @param dataProvider
  638. * the data provider to set, not <code>null</code>
  639. * @param initialFilter
  640. * the initial filter value to use, or <code>null</code> to not
  641. * use any initial filter value
  642. *
  643. * @param <F>
  644. * the filter type
  645. *
  646. * @return a consumer that accepts a new filter value to use
  647. */
  648. public <F> SerializableConsumer<F> setDataProvider(
  649. DataProvider<T, F> dataProvider, F initialFilter) {
  650. Objects.requireNonNull(dataProvider, "data provider cannot be null");
  651. filter = initialFilter;
  652. setDataProvider(dataProvider);
  653. /*
  654. * This introduces behavior which influence on the client-server
  655. * communication: now the very first response to the client will always
  656. * contain some data. If data provider has been set already then {@code
  657. * pushRows} is empty at this point. So without the next line the very
  658. * first response will be without data. And the client will request more
  659. * data in the next request after the response. The next line allows to
  660. * send some data (in the {@code pushRows} range) to the client even in
  661. * the very first response. This is necessary for disabled component
  662. * (and theoretically allows to the client doesn't request more data in
  663. * a happy path).
  664. */
  665. setPushRows(Range.between(0, getMinPushSize()));
  666. if (isAttached()) {
  667. attachDataProviderListener();
  668. }
  669. reset = true;
  670. markAsDirty();
  671. return filter -> {
  672. if (this.dataProvider != dataProvider) {
  673. throw new IllegalStateException(
  674. "Filter slot is no longer valid after data provider has been changed");
  675. }
  676. if (!Objects.equals(this.filter, filter)) {
  677. setFilter(filter);
  678. reset();
  679. // Make sure filter change causes data to be sent again.
  680. markAsDirty();
  681. }
  682. };
  683. }
  684. /**
  685. * Sets the filter for this DataCommunicator. This method is used by user
  686. * through the consumer method from {@link #setDataProvider} and should not
  687. * be called elsewhere.
  688. *
  689. * @param filter
  690. * the filter
  691. *
  692. * @param <F>
  693. * the filter type
  694. *
  695. * @since 8.1
  696. */
  697. protected <F> void setFilter(F filter) {
  698. this.filter = filter;
  699. }
  700. /**
  701. * Set minimum size of data which will be sent to the client when data
  702. * source is set.
  703. * <p>
  704. * Server doesn't send all data from data source to the client. It sends
  705. * some initial chunk of data (whose size is determined as minimum between
  706. * {@code size} parameter of this method and data size). Client decides
  707. * whether it is able to show more data and request server to send more data
  708. * (next chunk).
  709. * <p>
  710. * When component is disabled then client cannot communicate to the server
  711. * side (by design, because of security reasons). It means that client will
  712. * get <b>only</b> initial chunk of data whose size is set here.
  713. *
  714. * @param size
  715. * the size of initial data to send to the client
  716. */
  717. public void setMinPushSize(int size) {
  718. if (size < 0) {
  719. throw new IllegalArgumentException("Value cannot be negative");
  720. }
  721. minPushSize = size;
  722. }
  723. /**
  724. * Get minimum size of data which will be sent to the client when data
  725. * source is set.
  726. *
  727. * @see #setMinPushSize(int)
  728. *
  729. * @return current minimum push size of initial data chunk which is sent to
  730. * the client when data source is set
  731. */
  732. public int getMinPushSize() {
  733. return minPushSize;
  734. }
  735. /**
  736. * Getter method for finding the size of DataProvider. Can be overridden by
  737. * a subclass that uses a specific type of DataProvider and/or query.
  738. *
  739. * @return the size of data provider with current filter
  740. */
  741. @SuppressWarnings({ "unchecked", "rawtypes" })
  742. public int getDataProviderSize() {
  743. return getDataProvider().size(new Query(getFilter()));
  744. }
  745. @Override
  746. protected DataCommunicatorState getState(boolean markAsDirty) {
  747. return (DataCommunicatorState) super.getState(markAsDirty);
  748. }
  749. @Override
  750. protected DataCommunicatorState getState() {
  751. return (DataCommunicatorState) super.getState();
  752. }
  753. private void attachDataProviderListener() {
  754. dataProviderUpdateRegistration = getDataProvider()
  755. .addDataProviderListener(event -> {
  756. if (event instanceof DataRefreshEvent) {
  757. T item = ((DataRefreshEvent<T>) event).getItem();
  758. getKeyMapper().refresh(item);
  759. generators.forEach(g -> g.refreshData(item));
  760. getUI().access(() -> refresh(item));
  761. } else {
  762. reset = true;
  763. getUI().access(() -> markAsDirty());
  764. }
  765. });
  766. }
  767. private void detachDataProviderListener() {
  768. if (dataProviderUpdateRegistration != null) {
  769. dataProviderUpdateRegistration.remove();
  770. dataProviderUpdateRegistration = null;
  771. }
  772. }
  773. /**
  774. * Sets a new {@code DataProvider} and refreshes all the internal
  775. * structures.
  776. *
  777. * @param dataProvider
  778. * @since 8.1
  779. */
  780. protected void setDataProvider(DataProvider<T, ?> dataProvider) {
  781. detachDataProviderListener();
  782. dropAllData();
  783. this.dataProvider = dataProvider;
  784. getKeyMapper().setIdentifierGetter(dataProvider::getId);
  785. }
  786. }