dk.apaq.crud.core.CollectionCrud Maven / Gradle / Ivy
package dk.apaq.crud.core;
import dk.apaq.filter.Filter;
import dk.apaq.filter.FiltrationItem;
import dk.apaq.filter.core.BeanFiltrationItem;
import dk.apaq.filter.limit.Limit;
import dk.apaq.filter.sort.Sorter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.WeakHashMap;
/**
*
*/
public class CollectionCrud extends BaseFilterableCrud {
private final List beans;
private final IdResolver idResolver;
private static class DefaultIdResolver implements IdResolver {
private final WeakHashMap idmap = new WeakHashMap();
public String getIdForBean(BEANTYPE bean) {
String id = idmap.get(bean);
if (id == null) {
id = UUID.randomUUID().toString();
idmap.put(bean, id);
}
return id;
}
}
public interface IdResolver {
String getIdForBean(BEANTYPE bean);
}
public CollectionCrud(List beans) {
this(beans, new DefaultIdResolver());
}
public CollectionCrud(List beans, IdResolver idResolver) {
this.beans = beans;
this.idResolver = idResolver;
}
public BEANTYPE read(String id) {
fireOnBeforeRead(id);
for (BEANTYPE current : beans) {
String currentId = idResolver.getIdForBean(current);
if (id.equals(currentId)) {
fireOnRead(id, current);
return current;
}
}
return null;
}
public List listIds(Filter filter, Sorter sorter, Limit limit) {
List list = new ArrayList(beans);
list = filter == null ? list : filterList(list, filter);
list = sorter == null ? list : sortList(list, sorter);
List idlist = new ArrayList();
int count = 0;
for (BEANTYPE e : list) {
if (limit == null | (limit != null && count >= limit.getOffset() && count < (limit.getOffset() + limit.getCount()))) {
String id = idResolver.getIdForBean(e);
idlist.add(id);
}
count++;
}
return idlist;
}
public List list(Filter filter, Sorter sorter, Limit limit) {
List idlist = listIds(filter, sorter, limit);
List beanlist = new ArrayList();
for(String id : idlist) {
beanlist.add(read(id));
}
return beanlist;
}
private List filterList(List list, Filter filter) {
List filtered = new ArrayList();
for (BEANTYPE e : list) {
FiltrationItem fi = new BeanFiltrationItem(e);
if (filter.passesFilter(fi)) {
filtered.add(e);
}
}
return filtered;
}
private List sortList(List list, final Sorter sorter) {
List> sortList = new ArrayList>();
List sorted = new ArrayList();
for (BEANTYPE current : list) {
sortList.add(new BeanFiltrationItem(current));
}
Collections.sort(sortList, new Comparator() {
@Override
public int compare(BeanFiltrationItem o1, BeanFiltrationItem o2) {
if (sorter == null) {
return 0;
}
switch (sorter.compare(o1, o2)) {
case GreaterThan:
return 1;
case LessThan:
return -1;
default:
return 0;
}
}
});
for (BeanFiltrationItem current : sortList) {
sorted.add(current.getBean());
}
return sorted;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy