blob: 9859a6518ff131275507b4d40404828493827d2d [file] [log] [blame]
Bri Prebilic Cole468bc1d2015-02-12 12:11:13 -08001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Simon Hunt44aa2f82015-04-30 15:01:35 -070017package org.onosproject.ui.table;
Bri Prebilic Cole468bc1d2015-02-12 12:11:13 -080018
19import java.util.Comparator;
20
21/**
22 * Comparator for {@link TableRow}.
23 */
24public class RowComparator implements Comparator<TableRow> {
Simon Hunt44aa2f82015-04-30 15:01:35 -070025 /** Designates the sort direction. */
26 public enum Direction {
27 /** Sort Ascending. */
28 ASC,
29 /** Sort Descending. */
30 DESC
31 }
Bri Prebilic Cole468bc1d2015-02-12 12:11:13 -080032
33 public static final String DESC_STR = "desc";
34
35 private final String colId;
36 private final Direction dir;
37
Bri Prebilic Coledea09742015-02-12 15:33:50 -080038 /**
39 * Constructs a comparator for table rows that uses the given
40 * column ID and direction.
41 *
42 * @param colId the column to sort on
43 * @param dir the direction to sort in
44 */
Bri Prebilic Cole468bc1d2015-02-12 12:11:13 -080045 public RowComparator(String colId, Direction dir) {
46 if (colId == null || dir == null) {
47 throw new NullPointerException("Null parameters not allowed");
48 }
49 this.colId = colId;
50 this.dir = dir;
51 }
52
53 @Override
54 public int compare(TableRow a, TableRow b) {
55 String cellA = a.get(colId);
56 String cellB = b.get(colId);
57
58 if (dir.equals(Direction.ASC)) {
59 return cellA.compareTo(cellB);
60 }
61 return cellB.compareTo(cellA);
62 }
63
64 /**
65 * Returns the sort direction constant for the given string.
66 * The expected strings are "asc" and "desc"; defaults to "asc".
67 *
68 * @param s the direction as a string
69 * @return the constant
70 */
71 public static Direction direction(String s) {
72 return DESC_STR.equals(s) ? Direction.DESC : Direction.ASC;
73 }
74}