Object value = data.getValue();
if (value instanceof DataModel) {
value = ((DataModel) value).getWrappedData();
}
FacesContext facesContext = FacesContext.getCurrentInstance();
SheetState sheetState = data.getSheetState(facesContext);
Comparator actualComparator = null;
if (value instanceof List || value instanceof Object[]) {
String sortProperty;
try {
UIComponent child = getFirstSortableChild(column.getChildren());
if (child != null) {
String attributeName = child instanceof AbstractUICommand ? Attributes.LABEL:Attributes.VALUE;
if (FacesUtils.hasValueBindingOrValueExpression(child, attributeName)) {
String var = data.getVar();
String expressionString = FacesUtils.getExpressionString(child, attributeName);
if (isSimpleProperty(expressionString)) {
if (expressionString.startsWith("#{")
&& expressionString.endsWith("}")) {
expressionString =
expressionString.substring(2,
expressionString.length() - 1);
}
sortProperty = expressionString.substring(var.length() + 1);
actualComparator = new BeanComparator(
sortProperty, comparator, !sheetState.isAscending());
if (LOG.isDebugEnabled()) {
LOG.debug("Sort property is {}", sortProperty);
}
} else {
boolean descending = !sheetState.isAscending();
actualComparator =
FacesUtils.getBindingOrExpressionComparator(facesContext, child, var, descending, comparator);
}
}
} else {
LOG.error("No sorting performed. Value is not instanceof List or Object[]!");
unsetSortableAttribute(column);
return;
}
} catch (Exception e) {
LOG.error("Error while extracting sortMethod :" + e.getMessage(), e);
if (column != null) {
unsetSortableAttribute(column);
}
return;
}
// TODO: locale / comparator parameter?
// don't compare numbers with Collator.getInstance() comparator
// Comparator comparator = Collator.getInstance();
// comparator = new RowComparator(ascending, method);
// memorize selected rows
List<Object> selectedDataRows = null;
if (sheetState.getSelectedRows().size() > 0) {
selectedDataRows = new ArrayList<Object>(sheetState.getSelectedRows().size());
Object dataRow;
for (Integer index : sheetState.getSelectedRows()) {
if (value instanceof List) {
dataRow = ((List) value).get(index);
} else {
dataRow = ((Object[]) value)[index];
}
selectedDataRows.add(dataRow);
}
}
// do sorting
if (value instanceof List) {
Collections.sort((List) value, actualComparator);
} else { // value is instanceof Object[]
Arrays.sort((Object[]) value, actualComparator);
}
// restore selected rows
if (selectedDataRows != null) {
sheetState.getSelectedRows().clear();
for (Object dataRow : selectedDataRows) {
int index = -1;
if (value instanceof List) {
for (int i = 0; i < ((List) value).size() && index < 0; i++) {
if (dataRow == ((List) value).get(i)) {
index = i;
}
}
} else {
for (int i = 0; i < ((Object[]) value).length && index < 0; i++) {
if (dataRow == ((Object[]) value)[i]) {
index = i;
}
}
}
if (index >= 0) {
sheetState.getSelectedRows().add(index);
}
}
}
} else { // DataModel?, ResultSet, Result or Object