Solution to sort any column of a Table

Hi!

Here I post my solution to have sorted column any time on any type of Object even if it does not implement Comparable<?>. It is now possible to even sort Vaadin fields (CheckBox field for exemple).

In our application we use the BeanItemContainer<?> as the data source of the Vaadin Table. But in order to sort a column each entity had to implement the Comparable<?> interface that most of the time was as simple as this:

@Override
public int compareTo(MyEntity o) {
	if (o != null) {
		return this.toString().compareTo(o.toString());
	}
	return 0;
}

So I created theses classes in order to sort items by their toString() method if they do not implement Comparable<?> :

/**
 * @author "Léo Millon <leo.millon@declasin.com>"
 *
 */
public class CustomItemComparator extends DefaultPropertyValueComparator {

	@Override
	public int compare(Object o1, Object o2) {
		// if object are comparable, keep default behavior
		if (o1 instanceOf Comparable<?> && o2 instanceOf Comparable<?>) {
			return super.compare(o1, o2);
		}
		
		// else, compare toString()
		Object obj1 = o1 != null ? o1.toString() : null;
		Object obj2 = o2 != null ? o2.toString() : null;
		return super.compare(obj1, obj2);
	}

}
/**
 * @author "Léo Millon <leo.millon@declasin.com>"
 *
 */
public class CustomItemSorter extends DefaultItemSorter {

	/**
	 * 
	 */
	public CustomItemSorter() {
		super(new CustomItemComparator());
	}

	/**
	 * @param propertyValueComparator
	 */
	public CustomItemSorter(Comparator<Object> propertyValueComparator) {
		super(propertyValueComparator);
	}
	
}
/**
 * @author "Léo Millon <leo.millon@declasin.com>"
 *
 */
public class CustomBeanItemContainer<BEANTYPE> extends BeanItemContainer<BEANTYPE> {

	/**
	 * @see BeanItemContainer#BeanItemContainer(Class, Collection)
	 * @param type
	 * @param collection
	 * @throws IllegalArgumentException
	 */
	public CustomBeanItemContainer(Class<? super BEANTYPE> type,
			Collection<? extends BEANTYPE> collection)
			throws IllegalArgumentException {
		super(type, collection);
		init();
	}

	/**
	 * @see BeanItemContainer#BeanItemContainer(Class)
	 * @param type
	 * @throws IllegalArgumentException
	 */
	public CustomBeanItemContainer(Class<? super BEANTYPE> type)
			throws IllegalArgumentException {
		super(type);
		init();
	}
	
	/**
	 * Init method
	 */
	private final void init() {
		// replace the DefaultItemSorter
		setItemSorter(new CustomItemSorter());
	}

	@Override
	public Collection<?> getSortableContainerPropertyIds() {
		if (getItemSorter() instanceof CustomItemSorter) {
			return getContainerPropertyIds();
		}
		else {
			return super.getSortableContainerPropertyIds();
		}
	}
	
}

On the screen shot you can have an example of a table with a column of (default) field sorted

I think it should have been the default behavior of the Vaadin Table sort system…

I hope this solution will be useful for anybody!
13081.png