View Javadoc
1   /*
2    * Copyright (C) 2013 4th Line GmbH, Switzerland
3    *
4    * The contents of this file are subject to the terms of either the GNU
5    * Lesser General Public License Version 2 or later ("LGPL") or the
6    * Common Development and Distribution License Version 1 or later
7    * ("CDDL") (collectively, the "License"). You may not use this file
8    * except in compliance with the License. See LICENSE.txt for more
9    * information.
10   *
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14   */
15  
16  package org.fourthline.cling.support.model;
17  
18  import java.util.ArrayList;
19  import java.util.List;
20  
21  /**
22   * @author Christian Bauer
23   */
24  public class SortCriterion {
25  
26      final protected boolean ascending;
27      final protected String propertyName;
28  
29      public SortCriterion(boolean ascending, String propertyName) {
30          this.ascending = ascending;
31          this.propertyName = propertyName;
32      }
33  
34      public SortCriterion(String criterion) {
35          this(criterion.startsWith("+"), criterion.substring(1));
36          if (!(criterion.startsWith("-") || criterion.startsWith("+")))
37              throw new IllegalArgumentException("Missing sort prefix +/- on criterion: " + criterion);
38      }
39  
40      public boolean isAscending() {
41          return ascending;
42      }
43  
44      public String getPropertyName() {
45          return propertyName;
46      }
47  
48      public static SortCriterion[] valueOf(String s) {
49          if (s == null || s.length() == 0) return new SortCriterion[0];
50          List<SortCriterion> list = new ArrayList<>();
51          String[] criteria = s.split(",");
52          for (String criterion : criteria) {
53              list.add(new SortCriterion(criterion.trim()));
54          }
55          return list.toArray(new SortCriterion[list.size()]);
56      }
57  
58      public static String toString(SortCriterion[] criteria) {
59          if (criteria == null) return "";
60          StringBuilder sb = new StringBuilder();
61          for (SortCriterion sortCriterion : criteria) {
62              sb.append(sortCriterion.toString()).append(",");
63          }
64          if (sb.toString().endsWith(",")) sb.deleteCharAt(sb.length()-1);
65          return sb.toString();
66      }
67  
68      @Override
69      public String toString() {
70          StringBuilder sb = new StringBuilder();
71          sb.append(ascending ? "+" : "-");
72          sb.append(propertyName);
73          return sb.toString();
74      }
75  }