1 /*******************************************************************************
2 * Copyright (c) 2010, 2011 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.browsing.ui.model.sorters;
14 import java.util.Arrays;
15 import java.util.Comparator;
16 import java.util.List;
18 import org.simantics.browsing.ui.NodeContext;
19 import org.simantics.browsing.ui.model.browsecontexts.BrowseContext;
20 import org.simantics.db.ReadGraph;
21 import org.simantics.db.exception.DatabaseException;
23 public abstract class AbstractSorter<T> implements Sorter {
25 public abstract T getSortingCriterion(ReadGraph graph, BrowseContext context, NodeContext node) throws DatabaseException;
26 public abstract int compare(T a, T b);
28 static class OrderNodeContext<T> {
29 public final NodeContext node;
30 public final T criterion;
32 public OrderNodeContext(NodeContext node, T criterion) {
34 this.criterion = criterion;
38 Comparator<OrderNodeContext<T>> comparator = new Comparator<OrderNodeContext<T>>() {
40 public int compare(OrderNodeContext<T> o1, OrderNodeContext<T> o2) {
41 return AbstractSorter.this.compare(o1.criterion, o2.criterion);
46 public void sort(ReadGraph graph, BrowseContext context, List<NodeContext> nodes) throws DatabaseException {
47 @SuppressWarnings("unchecked")
48 OrderNodeContext<T>[] orderNodes = new OrderNodeContext[nodes.size()];
49 for (int i = 0; i < orderNodes.length; i++) {
50 NodeContext node = nodes.get(i);
51 orderNodes[i] = new OrderNodeContext<T>(node, getSortingCriterion(graph, context, node));
53 Arrays.sort(orderNodes, comparator);
54 for (int i = 0; i < orderNodes.length; i++)
55 nodes.set(i, orderNodes[i].node);