package be.selckin.swu.repeater; import com.google.common.base.Preconditions; import org.apache.wicket.Component; import org.apache.wicket.markup.repeater.AbstractRepeater; import org.apache.wicket.model.IModel; import java.util.Collections; import java.util.Iterator; import java.util.List; public abstract class SimpleListView<T> extends AbstractRepeater { private boolean reuseItems; protected SimpleListView(String id, IModel<? extends List<T>> model) { super(id, Preconditions.checkNotNull(model)); } @Override protected void onConfigure() { super.onConfigure(); setVisible(!getList().isEmpty()); } @SuppressWarnings("unchecked") public final List<T> getList() { List<T> list = (List<T>) getDefaultModelObject(); return list == null ? Collections.<T>emptyList() : list; } public boolean isReuseItems() { return reuseItems; } public SimpleListView<T> setReuseItems(boolean reuseItems) { this.reuseItems = reuseItems; return this; } @SuppressWarnings("unchecked") @Override protected final void onPopulate() { if (!getList().isEmpty()) { if (!reuseItems) removeAll(); boolean hasChildren = size() != 0; for (int index = 0; index < getList().size(); index++) { String id = Integer.toString(index); Component item = null; if (hasChildren) item = get(id); if (item == null) add(create(id, new SimpleListViewItemModel<T>(this, index))); } } else { removeAll(); } } protected abstract Component create(String id, IModel<T> model); @Override protected Iterator<Component> renderIterator() { return iterator(); } @SuppressWarnings("unchecked") public final IModel<? extends List<T>> getModel() { return (IModel<? extends List<T>>) getDefaultModel(); } public final void setModel(IModel<? extends List<T>> model) { setDefaultModel(model); } @SuppressWarnings("unchecked") public final List<T> getModelObject() { return (List<T>) getDefaultModelObject(); } public static class SimpleListViewItemModel<T> implements IModel<T> { private final SimpleListView<T> listView; private final int index; public SimpleListViewItemModel(SimpleListView<T> listView, int index) { this.listView = listView; this.index = index; } @Override public T getObject() { return listView.getModelObject().get(index); } @Override public void setObject(T object) { listView.getModelObject().set(index, object); } @Override public void detach() { } } }