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.

AbstractRemoteDataSource.java 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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.client.data;
  17. import java.util.HashMap;
  18. import java.util.LinkedHashSet;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.Objects;
  22. import java.util.Set;
  23. import java.util.stream.Stream;
  24. import com.google.gwt.core.client.Duration;
  25. import com.google.gwt.core.client.Scheduler;
  26. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  27. import com.vaadin.client.Profiler;
  28. import com.vaadin.shared.Range;
  29. import com.vaadin.shared.Registration;
  30. /**
  31. * Base implementation for data sources that fetch data from a remote system.
  32. * This class takes care of caching data and communicating with the data source
  33. * user. An implementation of this class should override
  34. * {@link #requestRows(int, int, RequestRowsCallback)} to trigger asynchronously
  35. * loading of data and then pass the loaded data into the provided callback.
  36. *
  37. * @since 7.4
  38. * @author Vaadin Ltd
  39. * @param <T>
  40. * the row type
  41. */
  42. public abstract class AbstractRemoteDataSource<T> implements DataSource<T> {
  43. /**
  44. * Callback used by
  45. * {@link AbstractRemoteDataSource#requestRows(int, int, RequestRowsCallback)}
  46. * to pass data to the underlying implementation when data has been fetched.
  47. */
  48. public static class RequestRowsCallback<T> {
  49. private final Range requestedRange;
  50. private final double requestStart;
  51. private final AbstractRemoteDataSource<T> source;
  52. /**
  53. * Creates a new callback
  54. *
  55. * @param source
  56. * the data source for which the request is made
  57. * @param requestedRange
  58. * the requested row range
  59. */
  60. protected RequestRowsCallback(AbstractRemoteDataSource<T> source,
  61. Range requestedRange) {
  62. this.source = source;
  63. this.requestedRange = requestedRange;
  64. requestStart = Duration.currentTimeMillis();
  65. }
  66. /**
  67. * Called by the
  68. * {@link AbstractRemoteDataSource#requestRows(int, int, RequestRowsCallback)}
  69. * implementation when data has been received.
  70. *
  71. * @param rowData
  72. * a list of row objects starting at the requested offset
  73. * @param totalSize
  74. * the total number of rows available at the remote end
  75. */
  76. public void onResponse(List<T> rowData, int totalSize) {
  77. if (source.size != totalSize) {
  78. source.resetDataAndSize(totalSize);
  79. }
  80. source.setRowData(requestedRange.getStart(), rowData);
  81. }
  82. /**
  83. * Gets the range of rows that was requested.
  84. *
  85. * @return the requsted row range
  86. */
  87. public Range getRequestedRange() {
  88. return requestedRange;
  89. }
  90. }
  91. protected class RowHandleImpl extends RowHandle<T> {
  92. private T row;
  93. private final Object key;
  94. public RowHandleImpl(final T row, final Object key) {
  95. this.row = row;
  96. this.key = key;
  97. }
  98. /**
  99. * A method for the data source to update the row data.
  100. *
  101. * @param row
  102. * the updated row object
  103. */
  104. public void setRow(final T row) {
  105. this.row = row;
  106. assert getRowKey(row).equals(key) : "The old key does not "
  107. + "equal the new key for the given row (old: " + key
  108. + ", new :" + getRowKey(row) + ")";
  109. }
  110. @Override
  111. public T getRow() throws IllegalStateException {
  112. return row;
  113. }
  114. public boolean isPinned() {
  115. return pinnedRows.containsKey(key);
  116. }
  117. @Override
  118. public void pin() {
  119. pinHandle(this);
  120. }
  121. @Override
  122. public void unpin() throws IllegalStateException {
  123. unpinHandle(this);
  124. }
  125. @Override
  126. protected boolean equalsExplicit(final Object obj) {
  127. if (obj instanceof AbstractRemoteDataSource.RowHandleImpl) {
  128. /*
  129. * Java prefers AbstractRemoteDataSource<?>.RowHandleImpl. I
  130. * like the @SuppressWarnings more (keeps the line length in
  131. * check.)
  132. */
  133. @SuppressWarnings("unchecked")
  134. final RowHandleImpl rhi = (RowHandleImpl) obj;
  135. return key.equals(rhi.key);
  136. } else {
  137. return false;
  138. }
  139. }
  140. @Override
  141. protected int hashCodeExplicit() {
  142. return key.hashCode();
  143. }
  144. @Override
  145. public void updateRow() {
  146. int index = indexOf(row);
  147. if (index >= 0) {
  148. getHandlers().forEach(dch -> dch.dataUpdated(index, 1));
  149. }
  150. }
  151. }
  152. private RequestRowsCallback<T> currentRequestCallback;
  153. private boolean coverageCheckPending = false;
  154. private Range requestedAvailability = Range.between(0, 0);
  155. private Range cached = Range.between(0, 0);
  156. private final HashMap<Integer, T> indexToRowMap = new HashMap<>();
  157. private final HashMap<Object, Integer> keyToIndexMap = new HashMap<>();
  158. private Set<DataChangeHandler> dataChangeHandlers = new LinkedHashSet<>();
  159. private CacheStrategy cacheStrategy = new CacheStrategy.DefaultCacheStrategy();
  160. private final ScheduledCommand coverageChecker = new ScheduledCommand() {
  161. @Override
  162. public void execute() {
  163. coverageCheckPending = false;
  164. checkCacheCoverage();
  165. }
  166. };
  167. private Map<Object, Integer> pinnedCounts = new HashMap<>();
  168. private Map<Object, RowHandleImpl> pinnedRows = new HashMap<>();
  169. // Size not yet known
  170. private int size = -1;
  171. private void ensureCoverageCheck() {
  172. if (!coverageCheckPending) {
  173. coverageCheckPending = true;
  174. Scheduler.get().scheduleDeferred(coverageChecker);
  175. }
  176. }
  177. /**
  178. * Pins a row with given handle. This function can be overridden to do
  179. * specific logic related to pinning rows.
  180. *
  181. * @param handle
  182. * row handle to pin
  183. */
  184. protected void pinHandle(RowHandleImpl handle) {
  185. Object key = handle.key;
  186. Integer count = pinnedCounts.get(key);
  187. if (count == null) {
  188. count = Integer.valueOf(0);
  189. pinnedRows.put(key, handle);
  190. }
  191. pinnedCounts.put(key, Integer.valueOf(count.intValue() + 1));
  192. }
  193. /**
  194. * Unpins a previously pinned row with given handle. This function can be
  195. * overridden to do specific logic related to unpinning rows.
  196. *
  197. * @param handle
  198. * row handle to unpin
  199. *
  200. * @throws IllegalStateException
  201. * if given row handle has not been pinned before
  202. */
  203. protected void unpinHandle(RowHandleImpl handle)
  204. throws IllegalStateException {
  205. Object key = handle.key;
  206. final Integer count = pinnedCounts.get(key);
  207. if (count == null) {
  208. throw new IllegalStateException("Row " + handle.getRow()
  209. + " with key " + key + " was not pinned to begin with");
  210. } else if (count.equals(Integer.valueOf(1))) {
  211. pinnedRows.remove(key);
  212. pinnedCounts.remove(key);
  213. } else {
  214. pinnedCounts.put(key, Integer.valueOf(count.intValue() - 1));
  215. }
  216. }
  217. @Override
  218. public void ensureAvailability(int firstRowIndex, int numberOfRows) {
  219. requestedAvailability = Range.withLength(firstRowIndex, numberOfRows);
  220. /*
  221. * Don't request any data right away since the data might be included in
  222. * a message that has been received but not yet fully processed.
  223. */
  224. ensureCoverageCheck();
  225. }
  226. /**
  227. * Gets the row index range that was requested by the previous call to
  228. * {@link #ensureAvailability(int, int)}.
  229. *
  230. * @return the requested availability range
  231. */
  232. public Range getRequestedAvailability() {
  233. return requestedAvailability;
  234. }
  235. private void checkCacheCoverage() {
  236. if (isWaitingForData()) {
  237. // Anyone clearing the waiting status should run this method again
  238. return;
  239. }
  240. Profiler.enter("AbstractRemoteDataSource.checkCacheCoverage");
  241. Range minCacheRange = getMinCacheRange();
  242. if (!minCacheRange.intersects(cached) || cached.isEmpty()) {
  243. /*
  244. * Simple case: no overlap between cached data and needed data.
  245. * Clear the cache and request new data
  246. */
  247. dropFromCache(cached);
  248. cached = Range.between(0, 0);
  249. handleMissingRows(getMaxCacheRange());
  250. } else {
  251. discardStaleCacheEntries();
  252. // Might need more rows -> request them
  253. if (!minCacheRange.isSubsetOf(cached)) {
  254. Range[] missingCachePartition = getMaxCacheRange()
  255. .partitionWith(cached);
  256. handleMissingRows(missingCachePartition[0]);
  257. handleMissingRows(missingCachePartition[2]);
  258. } else {
  259. getHandlers().forEach(dch -> dch
  260. .dataAvailable(cached.getStart(), cached.length()));
  261. }
  262. }
  263. Profiler.leave("AbstractRemoteDataSource.checkCacheCoverage");
  264. }
  265. /**
  266. * Checks whether this data source is currently waiting for more rows to
  267. * become available.
  268. *
  269. * @return <code>true</code> if waiting for data; otherwise
  270. * <code>false</code>
  271. */
  272. public boolean isWaitingForData() {
  273. return currentRequestCallback != null;
  274. }
  275. private void discardStaleCacheEntries() {
  276. Range[] cacheParition = cached.partitionWith(getMaxCacheRange());
  277. dropFromCache(cacheParition[0]);
  278. cached = cacheParition[1];
  279. dropFromCache(cacheParition[2]);
  280. }
  281. private void dropFromCache(Range range) {
  282. for (int i = range.getStart(); i < range.getEnd(); i++) {
  283. // Called after dropping from cache. Dropped row is passed as a
  284. // parameter, but is no longer present in the DataSource
  285. T removed = indexToRowMap.remove(Integer.valueOf(i));
  286. if (removed != null) {
  287. onDropFromCache(i, removed);
  288. keyToIndexMap.remove(getRowKey(removed));
  289. }
  290. }
  291. }
  292. /**
  293. * A hook that can be overridden to do something whenever a row has been
  294. * dropped from the cache. DataSource no longer has anything in the given
  295. * index.
  296. * <p>
  297. * NOTE: This method has been replaced. Override
  298. * {@link #onDropFromCache(int, Object)} instead of this method.
  299. *
  300. * @since 7.5.0
  301. * @param rowIndex
  302. * the index of the dropped row
  303. * @deprecated replaced by {@link #onDropFromCache(int, Object)}
  304. */
  305. @Deprecated
  306. protected void onDropFromCache(int rowIndex) {
  307. // noop
  308. }
  309. /**
  310. * A hook that can be overridden to do something whenever a row has been
  311. * dropped from the cache. DataSource no longer has anything in the given
  312. * index.
  313. *
  314. * @since 7.6
  315. * @param rowIndex
  316. * the index of the dropped row
  317. * @param removed
  318. * the removed row object
  319. */
  320. protected void onDropFromCache(int rowIndex, T removed) {
  321. // Call old version as a fallback (someone might have used it)
  322. onDropFromCache(rowIndex);
  323. }
  324. private void handleMissingRows(Range range) {
  325. if (range.isEmpty()) {
  326. return;
  327. }
  328. currentRequestCallback = new RequestRowsCallback<>(this, range);
  329. requestRows(range.getStart(), range.length(), currentRequestCallback);
  330. }
  331. /**
  332. * Triggers fetching rows from the remote data source. The provided callback
  333. * should be informed when the requested rows have been received.
  334. *
  335. * @param firstRowIndex
  336. * the index of the first row to fetch
  337. * @param numberOfRows
  338. * the number of rows to fetch
  339. * @param callback
  340. * callback to inform when the requested rows are available
  341. */
  342. protected abstract void requestRows(int firstRowIndex, int numberOfRows,
  343. RequestRowsCallback<T> callback);
  344. @Override
  345. public T getRow(int rowIndex) {
  346. return indexToRowMap.get(Integer.valueOf(rowIndex));
  347. }
  348. /**
  349. * Retrieves the index for given row object.
  350. * <p>
  351. * <em>Note:</em> This method does not verify that the given row object
  352. * exists at all in this DataSource.
  353. *
  354. * @param row
  355. * the row object
  356. * @return index of the row; or <code>-1</code> if row is not available
  357. */
  358. public int indexOf(T row) {
  359. Object key = getRowKey(row);
  360. if (keyToIndexMap.containsKey(key)) {
  361. return keyToIndexMap.get(key);
  362. }
  363. return -1;
  364. }
  365. @Override
  366. public Registration addDataChangeHandler(
  367. final DataChangeHandler dataChangeHandler) {
  368. Objects.requireNonNull(dataChangeHandler,
  369. "DataChangeHandler can't be null");
  370. dataChangeHandlers.add(dataChangeHandler);
  371. if (!cached.isEmpty()) {
  372. // Push currently cached data to the implementation
  373. dataChangeHandler.dataUpdated(cached.getStart(), cached.length());
  374. dataChangeHandler.dataAvailable(cached.getStart(), cached.length());
  375. }
  376. return () -> dataChangeHandlers.remove(dataChangeHandler);
  377. }
  378. /**
  379. * Informs this data source that updated data has been sent from the server.
  380. *
  381. * @param firstRowIndex
  382. * the index of the first received row
  383. * @param rowData
  384. * a list of rows, starting from <code>firstRowIndex</code>
  385. */
  386. protected void setRowData(int firstRowIndex, List<T> rowData) {
  387. assert firstRowIndex + rowData.size() <= size();
  388. Profiler.enter("AbstractRemoteDataSource.setRowData");
  389. Range received = Range.withLength(firstRowIndex, rowData.size());
  390. if (isWaitingForData()) {
  391. cacheStrategy.onDataArrive(
  392. Duration.currentTimeMillis()
  393. - currentRequestCallback.requestStart,
  394. received.length());
  395. currentRequestCallback = null;
  396. }
  397. Range maxCacheRange = getMaxCacheRange();
  398. Range[] partition = received.partitionWith(maxCacheRange);
  399. Range newUsefulData = partition[1];
  400. if (!newUsefulData.isEmpty()) {
  401. // Update the parts that are actually inside
  402. int start = newUsefulData.getStart();
  403. for (int i = start; i < newUsefulData.getEnd(); i++) {
  404. final T row = rowData.get(i - firstRowIndex);
  405. indexToRowMap.put(Integer.valueOf(i), row);
  406. keyToIndexMap.put(getRowKey(row), Integer.valueOf(i));
  407. }
  408. Profiler.enter(
  409. "AbstractRemoteDataSource.setRowData notify dataChangeHandler");
  410. int length = newUsefulData.length();
  411. getHandlers().forEach(dch -> dch.dataUpdated(start, length));
  412. Profiler.leave(
  413. "AbstractRemoteDataSource.setRowData notify dataChangeHandler");
  414. // Potentially extend the range
  415. if (cached.isEmpty()) {
  416. cached = newUsefulData;
  417. } else {
  418. discardStaleCacheEntries();
  419. /*
  420. * everything might've become stale so we need to re-check for
  421. * emptiness.
  422. */
  423. if (!cached.isEmpty()) {
  424. cached = cached.combineWith(newUsefulData);
  425. } else {
  426. cached = newUsefulData;
  427. }
  428. }
  429. getHandlers().forEach(dch -> dch.dataAvailable(cached.getStart(),
  430. cached.length()));
  431. updatePinnedRows(rowData);
  432. }
  433. if (!partition[0].isEmpty() || !partition[2].isEmpty()) {
  434. /*
  435. * FIXME
  436. *
  437. * Got data that we might need in a moment if the container is
  438. * updated before the widget settings. Support for this will be
  439. * implemented later on.
  440. */
  441. // Run a dummy drop from cache for unused rows.
  442. for (int i = 0; i < partition[0].length(); ++i) {
  443. onDropFromCache(i + partition[0].getStart(), rowData.get(i));
  444. }
  445. for (int i = 0; i < partition[2].length(); ++i) {
  446. onDropFromCache(i + partition[2].getStart(), rowData.get(i));
  447. }
  448. }
  449. // Eventually check whether all needed rows are now available
  450. ensureCoverageCheck();
  451. Profiler.leave("AbstractRemoteDataSource.setRowData");
  452. }
  453. private Stream<DataChangeHandler> getHandlers() {
  454. Set<DataChangeHandler> copy = new LinkedHashSet<>(dataChangeHandlers);
  455. return copy.stream();
  456. }
  457. private void updatePinnedRows(final List<T> rowData) {
  458. for (final T row : rowData) {
  459. final Object key = getRowKey(row);
  460. final RowHandleImpl handle = pinnedRows.get(key);
  461. if (handle != null) {
  462. handle.setRow(row);
  463. }
  464. }
  465. }
  466. /**
  467. * Informs this data source that the server has removed data.
  468. *
  469. * @param firstRowIndex
  470. * the index of the first removed row
  471. * @param count
  472. * the number of removed rows, starting from
  473. * <code>firstRowIndex</code>
  474. */
  475. protected void removeRowData(int firstRowIndex, int count) {
  476. Profiler.enter("AbstractRemoteDataSource.removeRowData");
  477. size -= count;
  478. Range removedRange = Range.withLength(firstRowIndex, count);
  479. dropFromCache(removedRange);
  480. // shift indices to fill the cache correctly
  481. int firstMoved = Math.max(firstRowIndex + count, cached.getStart());
  482. for (int i = firstMoved; i < cached.getEnd(); i++) {
  483. moveRowFromIndexToIndex(i, i - count);
  484. }
  485. if (cached.isSubsetOf(removedRange)) {
  486. // Whole cache is part of the removal. Empty cache
  487. cached = Range.withLength(0, 0);
  488. } else if (removedRange.intersects(cached)) {
  489. // Removal and cache share some indices. fix accordingly.
  490. Range[] partitions = cached.partitionWith(removedRange);
  491. Range remainsBefore = partitions[0];
  492. Range transposedRemainsAfter = partitions[2]
  493. .offsetBy(-removedRange.length());
  494. cached = remainsBefore.combineWith(transposedRemainsAfter);
  495. } else if (removedRange.getEnd() <= cached.getStart()) {
  496. // Removal was before the cache. offset the cache.
  497. cached = cached.offsetBy(-removedRange.length());
  498. }
  499. getHandlers().forEach(dch -> dch.dataRemoved(firstRowIndex, count));
  500. ensureCoverageCheck();
  501. Profiler.leave("AbstractRemoteDataSource.removeRowData");
  502. }
  503. /**
  504. * Informs this data source that new data has been inserted from the server.
  505. *
  506. * @param firstRowIndex
  507. * the destination index of the new row data
  508. * @param count
  509. * the number of rows inserted
  510. */
  511. protected void insertRowData(int firstRowIndex, int count) {
  512. Profiler.enter("AbstractRemoteDataSource.insertRowData");
  513. size += count;
  514. if (firstRowIndex <= cached.getStart()) {
  515. Range oldCached = cached;
  516. cached = cached.offsetBy(count);
  517. for (int i = 1; i <= cached.length(); i++) {
  518. int oldIndex = oldCached.getEnd() - i;
  519. int newIndex = cached.getEnd() - i;
  520. moveRowFromIndexToIndex(oldIndex, newIndex);
  521. }
  522. } else if (cached.contains(firstRowIndex)) {
  523. int oldCacheEnd = cached.getEnd();
  524. /*
  525. * We need to invalidate the cache from the inserted row onwards,
  526. * since the cache wants to be a contiguous range. It doesn't
  527. * support holes.
  528. *
  529. * If holes were supported, we could shift the higher part of
  530. * "cached" and leave a hole the size of "count" in the middle.
  531. */
  532. cached = cached.splitAt(firstRowIndex)[0];
  533. for (int i = firstRowIndex; i < oldCacheEnd; i++) {
  534. T row = indexToRowMap.remove(Integer.valueOf(i));
  535. keyToIndexMap.remove(getRowKey(row));
  536. }
  537. }
  538. getHandlers().forEach(dch -> dch.dataAdded(firstRowIndex, count));
  539. ensureCoverageCheck();
  540. Profiler.leave("AbstractRemoteDataSource.insertRowData");
  541. }
  542. @SuppressWarnings("boxing")
  543. private void moveRowFromIndexToIndex(int oldIndex, int newIndex) {
  544. T row = indexToRowMap.remove(oldIndex);
  545. if (indexToRowMap.containsKey(newIndex)) {
  546. // Old row is about to be overwritten. Remove it from keyCache.
  547. T row2 = indexToRowMap.remove(newIndex);
  548. if (row2 != null) {
  549. keyToIndexMap.remove(getRowKey(row2));
  550. }
  551. }
  552. indexToRowMap.put(newIndex, row);
  553. if (row != null) {
  554. keyToIndexMap.put(getRowKey(row), newIndex);
  555. }
  556. }
  557. /**
  558. * Gets the current range of cached rows
  559. *
  560. * @return the range of currently cached rows
  561. */
  562. public Range getCachedRange() {
  563. return cached;
  564. }
  565. /**
  566. * Sets the cache strategy that is used to determine how much data is
  567. * fetched and cached.
  568. * <p>
  569. * The new strategy is immediately used to evaluate whether currently cached
  570. * rows should be discarded or new rows should be fetched.
  571. *
  572. * @param cacheStrategy
  573. * a cache strategy implementation, not <code>null</code>
  574. */
  575. public void setCacheStrategy(CacheStrategy cacheStrategy) {
  576. if (cacheStrategy == null) {
  577. throw new IllegalArgumentException();
  578. }
  579. if (this.cacheStrategy != cacheStrategy) {
  580. this.cacheStrategy = cacheStrategy;
  581. checkCacheCoverage();
  582. }
  583. }
  584. private Range getMinCacheRange() {
  585. Range availableDataRange = getAvailableRangeForCache();
  586. Range minCacheRange = cacheStrategy.getMinCacheRange(
  587. requestedAvailability, cached, availableDataRange);
  588. assert minCacheRange.isSubsetOf(availableDataRange);
  589. return minCacheRange;
  590. }
  591. private Range getMaxCacheRange() {
  592. Range availableDataRange = getAvailableRangeForCache();
  593. Range maxCacheRange = cacheStrategy.getMaxCacheRange(
  594. requestedAvailability, cached, availableDataRange);
  595. assert maxCacheRange.isSubsetOf(availableDataRange);
  596. return maxCacheRange;
  597. }
  598. private Range getAvailableRangeForCache() {
  599. int upperBound = size();
  600. if (upperBound == -1) {
  601. upperBound = requestedAvailability.length();
  602. }
  603. return Range.withLength(0, upperBound);
  604. }
  605. @Override
  606. public RowHandle<T> getHandle(T row) throws IllegalStateException {
  607. Object key = getRowKey(row);
  608. if (key == null) {
  609. throw new NullPointerException(
  610. "key may not be null (row: " + row + ")");
  611. }
  612. if (pinnedRows.containsKey(key)) {
  613. return pinnedRows.get(key);
  614. } else if (keyToIndexMap.containsKey(key)) {
  615. return new RowHandleImpl(row, key);
  616. } else {
  617. throw new IllegalStateException("The cache of this DataSource "
  618. + "does not currently contain the row " + row);
  619. }
  620. }
  621. /**
  622. * Gets a stable key for the row object.
  623. * <p>
  624. * This method is a workaround for the fact that there is no means to force
  625. * proper implementations for {@link #hashCode()} and
  626. * {@link #equals(Object)} methods.
  627. * <p>
  628. * Since the same row object will be created several times for the same
  629. * logical data, the DataSource needs a mechanism to be able to compare two
  630. * objects, and figure out whether or not they represent the same data. Even
  631. * if all the fields of an entity would be changed, it still could represent
  632. * the very same thing (say, a person changes all of her names.)
  633. * <p>
  634. * A very usual and simple example what this could be, is an unique ID for
  635. * this object that would also be stored in a database.
  636. *
  637. * @param row
  638. * the row object for which to get the key
  639. * @return a non-null object that uniquely and consistently represents the
  640. * row object
  641. */
  642. abstract public Object getRowKey(T row);
  643. @Override
  644. public int size() {
  645. return size;
  646. }
  647. /**
  648. * Updates the size, discarding all cached data. This method is used when
  649. * the size of the container is changed without any information about the
  650. * structure of the change. In this case, all cached data is discarded to
  651. * avoid cache offset issues.
  652. * <p>
  653. * If you have information about the structure of the change, use
  654. * {@link #insertRowData(int, int)} or {@link #removeRowData(int, int)} to
  655. * indicate where the inserted or removed rows are located.
  656. *
  657. * @param newSize
  658. * the new size of the container
  659. */
  660. protected void resetDataAndSize(int newSize) {
  661. size = newSize;
  662. dropFromCache(getCachedRange());
  663. cached = Range.withLength(0, 0);
  664. getHandlers().forEach(dch -> dch.resetDataAndSize(newSize));
  665. }
  666. protected int indexOfKey(Object rowKey) {
  667. if (!keyToIndexMap.containsKey(rowKey)) {
  668. return -1;
  669. } else {
  670. return keyToIndexMap.get(rowKey);
  671. }
  672. }
  673. protected boolean isPinned(T row) {
  674. return pinnedRows.containsKey(getRowKey(row));
  675. }
  676. }