use of org.forgerock.json.resource.SortKey in project OpenAM by OpenRock.
the class QueryResponsePresentation method sortItems.
private static List<ResourceResponse> sortItems(final QueryRequest request, List<ResourceResponse> items) {
Comparator<ResourceResponse> comparator = new Comparator<ResourceResponse>() {
final List<SortKey> sortKeys = request.getSortKeys();
@Override
public int compare(ResourceResponse o1, ResourceResponse o2) {
int compare = 0;
for (SortKey key : sortKeys) {
Comparable<Object> v1 = getField(o1, key.getField());
Comparable<Object> v2 = getField(o2, key.getField());
compare = compare(v1, v2, key.isAscendingOrder());
if (compare != 0) {
break;
}
}
return compare;
}
private int compare(Comparable<Object> first, Comparable<Object> second, boolean ascending) {
int result;
if (first == null && second == null) {
result = 0;
} else if (first == null) {
result = -1;
} else if (second == null) {
result = 1;
} else {
result = first.compareTo(second);
}
if (!ascending) {
result = -result;
}
return result;
}
/**
* Gets the comparable field value from a resource.
*
* @param resource The resource.
* @param field The field.
* @return The comparable field value or {@code null} if the field is empty or the
* field value is not comparable.
*/
private Comparable<Object> getField(ResourceResponse resource, JsonPointer field) {
JsonValue value = resource.getContent();
if (value.get(field).isNull()) {
return null;
}
Object object = value.get(field).getObject();
if (isComparable(object)) {
return asComparable(object);
} else {
return null;
}
}
private boolean isComparable(Object o) {
return o instanceof Comparable;
}
@SuppressWarnings("unchecked")
private Comparable<Object> asComparable(Object o) {
return (Comparable<Object>) o;
}
};
try {
Collections.sort(items, comparator);
} catch (NullPointerException e) {
// No-op, sorting failed.
}
return Collections.unmodifiableList(items);
}
Aggregations