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

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