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; 021 022import gwt.material.design.client.data.loader.LoadCallback; 023import gwt.material.design.client.data.loader.LoadConfig; 024import gwt.material.design.client.data.loader.LoadResult; 025 026import java.util.ArrayList; 027import java.util.List; 028import java.util.logging.Level; 029import java.util.logging.Logger; 030 031/** 032 * @author Ben Dol 033 */ 034public class ListDataSource<T> implements DataSource<T> { 035 036 private Logger logger = Logger.getLogger(ListDataSource.class.getName()); 037 038 private List<T> data; 039 040 public ListDataSource() { 041 data = new ArrayList<>(); 042 } 043 044 public ListDataSource(List<T> data) { 045 this.data = data; 046 } 047 048 @Override 049 public void load(LoadConfig<T> loadConfig, LoadCallback<T> callback) { 050 try { 051 int size = loadConfig.getOffset() + loadConfig.getLimit(); 052 if(size > data.size()){ 053 size = data.size(); 054 } 055 final List<T> subList = size == 0 ? new ArrayList<>() : data.subList(loadConfig.getOffset(), size); 056 callback.onSuccess(new LoadResult<>(subList, loadConfig.getOffset(), data.size(), cacheData())); 057 } catch (IndexOutOfBoundsException ex) { 058 // Silently ignore index out of bounds exceptions 059 logger.log(Level.FINE, "ListDataSource threw index out of bounds.", ex); 060 callback.onFailure(ex); 061 } 062 } 063 064 public void add(int startIndex, List<T> list) { 065 data.addAll(startIndex, list); 066 } 067 068 public void remove(List<T> list) { 069 data.removeAll(list); 070 } 071 072 public boolean cacheData() { 073 return true; 074 } 075 076 @Override 077 public boolean useRemoteSort() { 078 return false; 079 } 080}