blob: b588f488bff7f3c3781347c891a2ddf18545b532 [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
Thomas Vachuskafe8c98a2015-02-04 01:24:32 -080017package org.onosproject.ui.impl;
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> {
25 public static enum Direction { ASC, DESC }
26
27 public static final String DESC_STR = "desc";
28
29 private final String colId;
30 private final Direction dir;
31
Bri Prebilic Coledea09742015-02-12 15:33:50 -080032 /**
33 * Constructs a comparator for table rows that uses the given
34 * column ID and direction.
35 *
36 * @param colId the column to sort on
37 * @param dir the direction to sort in
38 */
Bri Prebilic Cole468bc1d2015-02-12 12:11:13 -080039 public RowComparator(String colId, Direction dir) {
40 if (colId == null || dir == null) {
41 throw new NullPointerException("Null parameters not allowed");
42 }
43 this.colId = colId;
44 this.dir = dir;
45 }
46
47 @Override
48 public int compare(TableRow a, TableRow b) {
49 String cellA = a.get(colId);
50 String cellB = b.get(colId);
51
52 if (dir.equals(Direction.ASC)) {
53 return cellA.compareTo(cellB);
54 }
55 return cellB.compareTo(cellA);
56 }
57
58 /**
59 * Returns the sort direction constant for the given string.
60 * The expected strings are "asc" and "desc"; defaults to "asc".
61 *
62 * @param s the direction as a string
63 * @return the constant
64 */
65 public static Direction direction(String s) {
66 return DESC_STR.equals(s) ? Direction.DESC : Direction.ASC;
67 }
68}