選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

AbstractRemoteDataSource.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. Range maxCacheRange = getMaxCacheRange();
  250. if (!maxCacheRange.isEmpty()) {
  251. handleMissingRows(maxCacheRange);
  252. } else {
  253. // There is nothing to fetch. We're done here.
  254. getHandlers().forEach(dch -> dch
  255. .dataAvailable(cached.getStart(), cached.length()));
  256. }
  257. } else {
  258. discardStaleCacheEntries();
  259. // Might need more rows -> request them
  260. if (!minCacheRange.isSubsetOf(cached)) {
  261. Range[] missingCachePartition = getMaxCacheRange()
  262. .partitionWith(cached);
  263. handleMissingRows(missingCachePartition[0]);
  264. handleMissingRows(missingCachePartition[2]);
  265. } else {
  266. getHandlers().forEach(dch -> dch
  267. .dataAvailable(cached.getStart(), cached.length()));
  268. }
  269. }
  270. Profiler.leave("AbstractRemoteDataSource.checkCacheCoverage");
  271. }
  272. /**
  273. * Checks whether this data source is currently waiting for more rows to
  274. * become available.
  275. *
  276. * @return <code>true</code> if waiting for data; otherwise
  277. * <code>false</code>
  278. */
  279. public boolean isWaitingForData() {
  280. return currentRequestCallback != null;
  281. }
  282. private void discardStaleCacheEntries() {
  283. Range[] cacheParition = cached.partitionWith(getMaxCacheRange());
  284. dropFromCache(cacheParition[0]);
  285. cached = cacheParition[1];
  286. dropFromCache(cacheParition[2]);
  287. }
  288. private void dropFromCache(Range range) {
  289. for (int i = range.getStart(); i < range.getEnd(); i++) {
  290. // Called after dropping from cache. Dropped row is passed as a
  291. // parameter, but is no longer present in the DataSource
  292. T removed = indexToRowMap.remove(Integer.valueOf(i));
  293. if (removed != null) {
  294. onDropFromCache(i, removed);
  295. keyToIndexMap.remove(getRowKey(removed));
  296. }
  297. }
  298. }
  299. /**
  300. * A hook that can be overridden to do something whenever a row has been
  301. * dropped from the cache. DataSource no longer has anything in the given
  302. * index.
  303. * <p>
  304. * NOTE: This method has been replaced. Override
  305. * {@link #onDropFromCache(int, Object)} instead of this method.
  306. *
  307. * @since 7.5.0
  308. * @param rowIndex
  309. * the index of the dropped row
  310. * @deprecated replaced by {@link #onDropFromCache(int, Object)}
  311. */
  312. @Deprecated
  313. protected void onDropFromCache(int rowIndex) {
  314. // noop
  315. }
  316. /**
  317. * A hook that can be overridden to do something whenever a row has been
  318. * dropped from the cache. DataSource no longer has anything in the given
  319. * index.
  320. *
  321. * @since 7.6
  322. * @param rowIndex
  323. * the index of the dropped row
  324. * @param removed
  325. * the removed row object
  326. */
  327. protected void onDropFromCache(int rowIndex, T removed) {
  328. // Call old version as a fallback (someone might have used it)
  329. onDropFromCache(rowIndex);
  330. }
  331. private void handleMissingRows(Range range) {
  332. if (range.isEmpty() || !canFetchData()) {
  333. return;
  334. }
  335. currentRequestCallback = new RequestRowsCallback<>(this, range);
  336. requestRows(range.getStart(), range.length(), currentRequestCallback);
  337. }
  338. /**
  339. * Triggers fetching rows from the remote data source. The provided callback
  340. * should be informed when the requested rows have been received.
  341. *
  342. * @param firstRowIndex
  343. * the index of the first row to fetch
  344. * @param numberOfRows
  345. * the number of rows to fetch
  346. * @param callback
  347. * callback to inform when the requested rows are available
  348. */
  349. protected abstract void requestRows(int firstRowIndex, int numberOfRows,
  350. RequestRowsCallback<T> callback);
  351. @Override
  352. public T getRow(int rowIndex) {
  353. return indexToRowMap.get(Integer.valueOf(rowIndex));
  354. }
  355. /**
  356. * Retrieves the index for given row object.
  357. * <p>
  358. * <em>Note:</em> This method does not verify that the given row object
  359. * exists at all in this DataSource.
  360. *
  361. * @param row
  362. * the row object
  363. * @return index of the row; or <code>-1</code> if row is not available
  364. */
  365. public int indexOf(T row) {
  366. Object key = getRowKey(row);
  367. if (keyToIndexMap.containsKey(key)) {
  368. return keyToIndexMap.get(key);
  369. }
  370. return -1;
  371. }
  372. @Override
  373. public Registration addDataChangeHandler(
  374. final DataChangeHandler dataChangeHandler) {
  375. Objects.requireNonNull(dataChangeHandler,
  376. "DataChangeHandler can't be null");
  377. dataChangeHandlers.add(dataChangeHandler);
  378. if (!cached.isEmpty()) {
  379. // Push currently cached data to the implementation
  380. dataChangeHandler.dataUpdated(cached.getStart(), cached.length());
  381. dataChangeHandler.dataAvailable(cached.getStart(), cached.length());
  382. }
  383. return () -> dataChangeHandlers.remove(dataChangeHandler);
  384. }
  385. /**
  386. * Informs this data source that updated data has been sent from the server.
  387. *
  388. * @param firstRowIndex
  389. * the index of the first received row
  390. * @param rowData
  391. * a list of rows, starting from <code>firstRowIndex</code>
  392. */
  393. protected void setRowData(int firstRowIndex, List<T> rowData) {
  394. assert firstRowIndex + rowData.size() <= size();
  395. Profiler.enter("AbstractRemoteDataSource.setRowData");
  396. Range received = Range.withLength(firstRowIndex, rowData.size());
  397. if (isWaitingForData()) {
  398. cacheStrategy.onDataArrive(
  399. Duration.currentTimeMillis()
  400. - currentRequestCallback.requestStart,
  401. received.length());
  402. currentRequestCallback = null;
  403. }
  404. Range maxCacheRange = getMaxCacheRange();
  405. Range[] partition = received.partitionWith(maxCacheRange);
  406. Range newUsefulData = partition[1];
  407. if (!newUsefulData.isEmpty()) {
  408. // Update the parts that are actually inside
  409. int start = newUsefulData.getStart();
  410. for (int i = start; i < newUsefulData.getEnd(); i++) {
  411. final T row = rowData.get(i - firstRowIndex);
  412. indexToRowMap.put(Integer.valueOf(i), row);
  413. keyToIndexMap.put(getRowKey(row), Integer.valueOf(i));
  414. }
  415. Profiler.enter(
  416. "AbstractRemoteDataSource.setRowData notify dataChangeHandler");
  417. int length = newUsefulData.length();
  418. getHandlers().forEach(dch -> dch.dataUpdated(start, length));
  419. Profiler.leave(
  420. "AbstractRemoteDataSource.setRowData notify dataChangeHandler");
  421. // Potentially extend the range
  422. if (cached.isEmpty()) {
  423. cached = newUsefulData;
  424. } else {
  425. discardStaleCacheEntries();
  426. /*
  427. * everything might've become stale so we need to re-check for
  428. * emptiness.
  429. */
  430. if (!cached.isEmpty()) {
  431. cached = cached.combineWith(newUsefulData);
  432. } else {
  433. cached = newUsefulData;
  434. }
  435. }
  436. getHandlers().forEach(dch -> dch.dataAvailable(cached.getStart(),
  437. cached.length()));
  438. updatePinnedRows(rowData);
  439. }
  440. if (!partition[0].isEmpty() || !partition[2].isEmpty()) {
  441. /*
  442. * FIXME
  443. *
  444. * Got data that we might need in a moment if the container is
  445. * updated before the widget settings. Support for this will be
  446. * implemented later on.
  447. */
  448. // Run a dummy drop from cache for unused rows.
  449. for (int i = 0; i < partition[0].length(); ++i) {
  450. onDropFromCache(i + partition[0].getStart(), rowData.get(i));
  451. }
  452. for (int i = 0; i < partition[2].length(); ++i) {
  453. onDropFromCache(i + partition[2].getStart(), rowData.get(i));
  454. }
  455. }
  456. // Eventually check whether all needed rows are now available
  457. ensureCoverageCheck();
  458. Profiler.leave("AbstractRemoteDataSource.setRowData");
  459. }
  460. private Stream<DataChangeHandler> getHandlers() {
  461. Set<DataChangeHandler> copy = new LinkedHashSet<>(dataChangeHandlers);
  462. return copy.stream();
  463. }
  464. private void updatePinnedRows(final List<T> rowData) {
  465. for (final T row : rowData) {
  466. final Object key = getRowKey(row);
  467. final RowHandleImpl handle = pinnedRows.get(key);
  468. if (handle != null) {
  469. handle.setRow(row);
  470. }
  471. }
  472. }
  473. /**
  474. * Informs this data source that the server has removed data.
  475. *
  476. * @param firstRowIndex
  477. * the index of the first removed row
  478. * @param count
  479. * the number of removed rows, starting from
  480. * <code>firstRowIndex</code>
  481. */
  482. protected void removeRowData(int firstRowIndex, int count) {
  483. Profiler.enter("AbstractRemoteDataSource.removeRowData");
  484. size -= count;
  485. Range removedRange = Range.withLength(firstRowIndex, count);
  486. dropFromCache(removedRange);
  487. // shift indices to fill the cache correctly
  488. int firstMoved = Math.max(firstRowIndex + count, cached.getStart());
  489. for (int i = firstMoved; i < cached.getEnd(); i++) {
  490. moveRowFromIndexToIndex(i, i - count);
  491. }
  492. if (cached.isSubsetOf(removedRange)) {
  493. // Whole cache is part of the removal. Empty cache
  494. cached = Range.withLength(0, 0);
  495. } else if (removedRange.intersects(cached)) {
  496. // Removal and cache share some indices. fix accordingly.
  497. Range[] partitions = cached.partitionWith(removedRange);
  498. Range remainsBefore = partitions[0];
  499. Range transposedRemainsAfter = partitions[2]
  500. .offsetBy(-removedRange.length());
  501. cached = remainsBefore.combineWith(transposedRemainsAfter);
  502. } else if (removedRange.getEnd() <= cached.getStart()) {
  503. // Removal was before the cache. offset the cache.
  504. cached = cached.offsetBy(-removedRange.length());
  505. }
  506. getHandlers().forEach(dch -> dch.dataRemoved(firstRowIndex, count));
  507. ensureCoverageCheck();
  508. Profiler.leave("AbstractRemoteDataSource.removeRowData");
  509. }
  510. /**
  511. * Informs this data source that new data has been inserted from the server.
  512. *
  513. * @param firstRowIndex
  514. * the destination index of the new row data
  515. * @param count
  516. * the number of rows inserted
  517. */
  518. protected void insertRowData(int firstRowIndex, int count) {
  519. Profiler.enter("AbstractRemoteDataSource.insertRowData");
  520. size += count;
  521. if (firstRowIndex <= cached.getStart()) {
  522. Range oldCached = cached;
  523. cached = cached.offsetBy(count);
  524. for (int i = 1; i <= cached.length(); i++) {
  525. int oldIndex = oldCached.getEnd() - i;
  526. int newIndex = cached.getEnd() - i;
  527. moveRowFromIndexToIndex(oldIndex, newIndex);
  528. }
  529. } else if (cached.contains(firstRowIndex)) {
  530. int oldCacheEnd = cached.getEnd();
  531. /*
  532. * We need to invalidate the cache from the inserted row onwards,
  533. * since the cache wants to be a contiguous range. It doesn't
  534. * support holes.
  535. *
  536. * If holes were supported, we could shift the higher part of
  537. * "cached" and leave a hole the size of "count" in the middle.
  538. */
  539. cached = cached.splitAt(firstRowIndex)[0];
  540. for (int i = firstRowIndex; i < oldCacheEnd; i++) {
  541. T row = indexToRowMap.remove(Integer.valueOf(i));
  542. keyToIndexMap.remove(getRowKey(row));
  543. }
  544. }
  545. getHandlers().forEach(dch -> dch.dataAdded(firstRowIndex, count));
  546. ensureCoverageCheck();
  547. Profiler.leave("AbstractRemoteDataSource.insertRowData");
  548. }
  549. @SuppressWarnings("boxing")
  550. private void moveRowFromIndexToIndex(int oldIndex, int newIndex) {
  551. T row = indexToRowMap.remove(oldIndex);
  552. if (indexToRowMap.containsKey(newIndex)) {
  553. // Old row is about to be overwritten. Remove it from keyCache.
  554. T row2 = indexToRowMap.remove(newIndex);
  555. if (row2 != null) {
  556. keyToIndexMap.remove(getRowKey(row2));
  557. }
  558. }
  559. indexToRowMap.put(newIndex, row);
  560. if (row != null) {
  561. keyToIndexMap.put(getRowKey(row), newIndex);
  562. }
  563. }
  564. /**
  565. * Gets the current range of cached rows
  566. *
  567. * @return the range of currently cached rows
  568. */
  569. public Range getCachedRange() {
  570. return cached;
  571. }
  572. /**
  573. * Sets the cache strategy that is used to determine how much data is
  574. * fetched and cached.
  575. * <p>
  576. * The new strategy is immediately used to evaluate whether currently cached
  577. * rows should be discarded or new rows should be fetched.
  578. *
  579. * @param cacheStrategy
  580. * a cache strategy implementation, not <code>null</code>
  581. */
  582. public void setCacheStrategy(CacheStrategy cacheStrategy) {
  583. if (cacheStrategy == null) {
  584. throw new IllegalArgumentException();
  585. }
  586. if (this.cacheStrategy != cacheStrategy) {
  587. this.cacheStrategy = cacheStrategy;
  588. checkCacheCoverage();
  589. }
  590. }
  591. private Range getMinCacheRange() {
  592. Range availableDataRange = getAvailableRangeForCache();
  593. Range minCacheRange = cacheStrategy.getMinCacheRange(
  594. requestedAvailability, cached, availableDataRange);
  595. assert minCacheRange.isSubsetOf(availableDataRange);
  596. return minCacheRange;
  597. }
  598. private Range getMaxCacheRange() {
  599. Range availableDataRange = getAvailableRangeForCache();
  600. Range maxCacheRange = cacheStrategy.getMaxCacheRange(
  601. requestedAvailability, cached, availableDataRange);
  602. assert maxCacheRange.isSubsetOf(availableDataRange);
  603. return maxCacheRange;
  604. }
  605. private Range getAvailableRangeForCache() {
  606. int upperBound = size();
  607. if (upperBound == -1) {
  608. upperBound = requestedAvailability.length();
  609. }
  610. return Range.withLength(0, upperBound);
  611. }
  612. @Override
  613. public RowHandle<T> getHandle(T row) throws IllegalStateException {
  614. Object key = getRowKey(row);
  615. if (key == null) {
  616. throw new NullPointerException(
  617. "key may not be null (row: " + row + ")");
  618. }
  619. if (pinnedRows.containsKey(key)) {
  620. return pinnedRows.get(key);
  621. } else if (keyToIndexMap.containsKey(key)) {
  622. return new RowHandleImpl(row, key);
  623. } else {
  624. throw new IllegalStateException("The cache of this DataSource "
  625. + "does not currently contain the row " + row);
  626. }
  627. }
  628. /**
  629. * Gets a stable key for the row object.
  630. * <p>
  631. * This method is a workaround for the fact that there is no means to force
  632. * proper implementations for {@link #hashCode()} and
  633. * {@link #equals(Object)} methods.
  634. * <p>
  635. * Since the same row object will be created several times for the same
  636. * logical data, the DataSource needs a mechanism to be able to compare two
  637. * objects, and figure out whether or not they represent the same data. Even
  638. * if all the fields of an entity would be changed, it still could represent
  639. * the very same thing (say, a person changes all of her names.)
  640. * <p>
  641. * A very usual and simple example what this could be, is an unique ID for
  642. * this object that would also be stored in a database.
  643. *
  644. * @param row
  645. * the row object for which to get the key
  646. * @return a non-null object that uniquely and consistently represents the
  647. * row object
  648. */
  649. abstract public Object getRowKey(T row);
  650. @Override
  651. public int size() {
  652. return size;
  653. }
  654. /**
  655. * Updates the size, discarding all cached data. This method is used when
  656. * the size of the container is changed without any information about the
  657. * structure of the change. In this case, all cached data is discarded to
  658. * avoid cache offset issues.
  659. * <p>
  660. * If you have information about the structure of the change, use
  661. * {@link #insertRowData(int, int)} or {@link #removeRowData(int, int)} to
  662. * indicate where the inserted or removed rows are located.
  663. *
  664. * @param newSize
  665. * the new size of the container
  666. */
  667. protected void resetDataAndSize(int newSize) {
  668. size = newSize;
  669. dropFromCache(getCachedRange());
  670. cached = Range.withLength(0, 0);
  671. getHandlers().forEach(dch -> dch.resetDataAndSize(newSize));
  672. }
  673. protected int indexOfKey(Object rowKey) {
  674. if (!keyToIndexMap.containsKey(rowKey)) {
  675. return -1;
  676. } else {
  677. return keyToIndexMap.get(rowKey);
  678. }
  679. }
  680. protected boolean isPinned(T row) {
  681. return pinnedRows.containsKey(getRowKey(row));
  682. }
  683. /**
  684. * Checks if it is possible to currently fetch data from the remote data
  685. * source.
  686. *
  687. * @return <code>true</code> if it is ok to try to fetch data,
  688. * <code>false</code> if it is known that fetching data will fail
  689. * and should not be tried right now.
  690. * @since 7.7.2
  691. */
  692. protected boolean canFetchData() {
  693. return true;
  694. }
  695. }