Created
March 9, 2015 22:53
-
-
Save zkendall/a27ee497fed5d6db8ea9 to your computer and use it in GitHub Desktop.
Vaddin Container - Custom sorting by converted property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Comparator; | |
import com.vaadin.data.Container.Sortable; | |
import com.vaadin.data.Item; | |
import com.vaadin.data.Property; | |
import com.vaadin.data.util.DefaultItemSorter; | |
/** | |
* The original need for this class is to provide a way of sorting by converted values instead of only the underlying | |
* property values. Sometimes a property is converted to be entirely different than the underlying property, and the | |
* user should see sorting based on what is visible. For example, a location ID property that is converted to a name | |
* label name needs this, but likely date/time does not need this. | |
*/ | |
public abstract class CustomItemSorter extends DefaultItemSorter { | |
private static final long serialVersionUID = 1L; | |
protected Comparator<Object> propertyValueComparator = new DefaultPropertyValueComparator(); | |
@Override | |
final public void setSortProperties(Sortable container, Object[] propertyId, boolean[] ascending) { | |
super.setSortProperties(container, propertyId, ascending); | |
customSetup(container, propertyId, ascending); | |
} | |
/** | |
* Called just before sorting takes place. | |
*/ | |
protected abstract void customSetup(Sortable container, Object[] propertyId, boolean[] ascending); | |
/** | |
* Taken from super. | |
*/ | |
@Override | |
final protected int compareProperty(Object propertyId, boolean sortDirection, Item item1, Item item2) { | |
// Get the properties to compare | |
final Property<?> property1 = item1.getItemProperty(propertyId); | |
final Property<?> property2 = item2.getItemProperty(propertyId); | |
// Get the values to compare | |
Object value1 = (property1 == null) ? null : property1.getValue(); | |
Object value2 = (property2 == null) ? null : property2.getValue(); | |
// START CUSTOMIZATION | |
value1 = handleProperty(propertyId, value1); | |
value2 = handleProperty(propertyId, value2); | |
// END CUSTOMIZATION | |
// Result of the comparison | |
int r = 0; | |
if (sortDirection) { | |
r = propertyValueComparator.compare(value1, value2); | |
} else { | |
r = propertyValueComparator.compare(value2, value1); | |
} | |
return r; | |
} | |
/** | |
* This will be called against both compared properties. Return the value that you want used in compare. | |
*/ | |
protected abstract Object handleProperty(Object propertyId, Object value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment