]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.browsing.ui.model/src/org/simantics/browsing/ui/model/sorters/AbstractSorter.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.browsing.ui.model / src / org / simantics / browsing / ui / model / sorters / AbstractSorter.java
1 /*******************************************************************************
2  * Copyright (c) 2010, 2011 Association for Decentralized Information Management in
3  * Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.browsing.ui.model.sorters;
13
14 import java.util.Arrays;
15 import java.util.Comparator;
16 import java.util.List;
17
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;
22
23 public abstract class AbstractSorter<T> implements Sorter {
24
25     public abstract T getSortingCriterion(ReadGraph graph, BrowseContext context, NodeContext node) throws DatabaseException;
26     public abstract int compare(T a, T b);
27     
28     static class OrderNodeContext<T> {
29         public final NodeContext node;
30         public final T criterion;
31         
32         public OrderNodeContext(NodeContext node, T criterion) {        
33             this.node = node;
34             this.criterion = criterion;
35         }
36     }
37     
38     Comparator<OrderNodeContext<T>> comparator = new Comparator<OrderNodeContext<T>>() {
39         @Override
40         public int compare(OrderNodeContext<T> o1, OrderNodeContext<T> o2) {
41             return AbstractSorter.this.compare(o1.criterion, o2.criterion);
42         }        
43     };
44     
45     @Override
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));
52         }
53         Arrays.sort(orderNodes, comparator);
54         for (int i = 0; i < orderNodes.length; i++)
55             nodes.set(i, orderNodes[i].node);
56     }
57
58 }