001/* 002 * #%L 003 * GwtMaterial 004 * %% 005 * Copyright (C) 2015 - 2017 GwtMaterialDesign 006 * %% 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 * #L% 019 */ 020package gwt.material.design.client.data.infinite; 021 022import java.util.ArrayList; 023import java.util.List; 024 025/** 026 * A Data Source for the {@link InfiniteDataView}, supports asynchronous calls 027 * expecting that {@link InfiniteDataView#loaded(int, List, int, boolean)} is called when ready. 028 * <br><br> 029 * <b>Note</b> that if {@link InfiniteDataView#loaded(int, List, int, boolean)} is not called 030 * the data will not be populated. 031 * 032 * @author Ben Dol 033 */ 034public class InfiniteDataCache<T> extends ArrayList<T> { 035 036 public List<T> getCache(int startIndex, int viewSize) { 037 int size = size(); 038 int end = (startIndex + viewSize); 039 040 List<T> cache = new ArrayList<>(); 041 if(startIndex < size && end <= size) { 042 for(int i = startIndex; i < end; i++) { 043 T data = get(i); 044 if(data != null) { 045 cache.add(data); 046 } else { 047 // If any data record is null we 048 // need to invoke a full data request 049 cache.clear(); 050 break; 051 } 052 } 053 } 054 return cache; 055 } 056 057 public void addCache(int startIndex, List<T> data) { 058 // Create placeholders up to the specified index. 059 int cacheOffset = Math.max(0, startIndex - size()); 060 for (int i = 0; i < cacheOffset; i++) { 061 add(null); 062 } 063 064 // Insert the new values into the data array. 065 for (int i = startIndex; i < startIndex + data.size(); i++) { 066 T value = data.get(i - startIndex); 067 if (i < size()) { 068 set(i, value); 069 } else { 070 add(value); 071 } 072 } 073 } 074}