Skip to content

Instantly share code, notes, and snippets.

@mvysny
Created June 21, 2017 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvysny/4307b4b76c13bc159c4dae77cff9549f to your computer and use it in GitHub Desktop.
Save mvysny/4307b4b76c13bc159c4dae77cff9549f to your computer and use it in GitHub Desktop.
/**
* Extends HierarchicalContainer which provides proper support for sorting and filtering, and add bean capabilities to it.
*/
public class HierarchicalBeanContainer<IDTYPE, BEANTYPE> extends HierarchicalContainer {
private final BeanContainer<IDTYPE, BEANTYPE> properties;
public HierarchicalBeanContainer(Class<BEANTYPE> itemClass) {
properties = new BeanContainer<>(itemClass);
properties.getContainerPropertyIds().forEach(prop -> addContainerProperty(prop, properties.getType(prop), null));
}
private String propertyId = null;
/**
* Sets the bean id resolver to use a property of the beans as the
* identifier.
*
* @param propertyId
* the identifier of the property to use to find item identifiers
*/
public void setBeanIdProperty(String propertyId) {
if (!properties.getContainerPropertyIds().contains(propertyId)) {
throw new IllegalArgumentException("propertyId: unknown property " + propertyId + "; supported properties: " + properties.getContainerPropertyIds());
}
this.propertyId = propertyId;
}
/**
* Adds a bean to the container using the bean item id resolver to find its
* identifier.
*
* A bean id resolver must be set before calling this method.
*
* @param bean
* the bean to add
* @return Item<BEANTYPE> item added or null
* @throws IllegalStateException
* if no bean identifier resolver has been set
* @throws IllegalArgumentException
* if an identifier cannot be resolved for the bean
*/
public Item addBean(BEANTYPE bean)
throws IllegalStateException, IllegalArgumentException {
if (bean == null) {
return null;
}
if (propertyId == null) {
throw new IllegalStateException("propertyId is not set");
}
final BeanItem<BEANTYPE> beanItem = new BeanItem<>(bean);
final IDTYPE itemId = (IDTYPE) beanItem.getItemProperty(propertyId).getValue();
if (itemId == null) {
throw new IllegalArgumentException(
"Resolved identifier for a bean must not be null");
}
final Item item = addItem(itemId);
properties.getContainerPropertyIds().forEach(prop -> item.getItemProperty(prop).setValue(beanItem.getItemProperty(prop).getValue()));
return item;
}
public void addAll(Collection<? extends BEANTYPE> beans) {
beans.forEach(this::addBean);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment