1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.kernel.search;
16  
17  import java.util.ArrayList;
18  import java.util.Comparator;
19  import java.util.List;
20  
21  /**
22   * <a href="DocumentComparator.java.html"><b><i>View Source</i></b></a>
23   *
24   * @author Brian Wing Shun Chan
25   */
26  public class DocumentComparator implements Comparator<Document> {
27  
28      public DocumentComparator() {
29          this(true, false);
30      }
31  
32      public DocumentComparator(boolean asc, boolean caseSensitive) {
33          _asc = asc;
34          _caseSensitive = caseSensitive;
35      }
36  
37      public void addOrderBy(String name) {
38          addOrderBy(name, _asc, _caseSensitive);
39      }
40  
41      public void addOrderBy(String name, boolean asc, boolean caseSensitive) {
42          DocumentComparatorOrderBy orderBy = new DocumentComparatorOrderBy(
43              name, asc, caseSensitive);
44  
45          _columns.add(orderBy);
46      }
47  
48      public int compare(Document doc1, Document doc2) {
49          for (DocumentComparatorOrderBy orderBy : _columns) {
50              String value1 = doc1.get(orderBy.getName());
51              String value2 = doc2.get(orderBy.getName());
52  
53              if (!orderBy.isAsc()) {
54                  String temp = value1;
55  
56                  value1 = value2;
57                  value2 = temp;
58              }
59  
60              int result = 0;
61  
62              if ((value1 != null) && (value2 != null)) {
63                  if (orderBy.isCaseSensitive()) {
64                      result = value1.compareTo(value2);
65                  }
66                  else {
67                      result = value1.compareToIgnoreCase(value2);
68                  }
69              }
70  
71              if (result != 0) {
72                  return result;
73              }
74          }
75  
76          return 0;
77      }
78  
79      private boolean _asc;
80      private boolean _caseSensitive;
81      private List<DocumentComparatorOrderBy> _columns =
82          new ArrayList<DocumentComparatorOrderBy>();
83  
84  }