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

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