001
014
015 package com.liferay.portal.kernel.search;
016
017 import java.util.ArrayList;
018 import java.util.Comparator;
019 import java.util.List;
020
021
024 public class DocumentComparator implements Comparator<Document> {
025
026 public DocumentComparator() {
027 this(true, false);
028 }
029
030 public DocumentComparator(boolean ascending, boolean caseSensitive) {
031 _ascending = ascending;
032 _caseSensitive = caseSensitive;
033 }
034
035 public void addOrderBy(String name) {
036 addOrderBy(name, _ascending, _caseSensitive);
037 }
038
039 public void addOrderBy(String name, boolean ascending) {
040 addOrderBy(name, ascending, _caseSensitive);
041 }
042
043 public void addOrderBy(
044 String name, boolean ascending, boolean caseSensitive) {
045
046 DocumentComparatorOrderBy orderBy = new DocumentComparatorOrderBy(
047 name, ascending, caseSensitive);
048
049 _columns.add(orderBy);
050 }
051
052 public int compare(Document doc1, Document doc2) {
053 for (DocumentComparatorOrderBy orderBy : _columns) {
054 String value1 = doc1.get(orderBy.getName());
055 String value2 = doc2.get(orderBy.getName());
056
057 if (!orderBy.isAsc()) {
058 String temp = value1;
059
060 value1 = value2;
061 value2 = temp;
062 }
063
064 int result = 0;
065
066 if ((value1 != null) && (value2 != null)) {
067 if (orderBy.isCaseSensitive()) {
068 result = value1.compareTo(value2);
069 }
070 else {
071 result = value1.compareToIgnoreCase(value2);
072 }
073 }
074
075 if (result != 0) {
076 return result;
077 }
078 }
079
080 return 0;
081 }
082
083 private boolean _ascending;
084 private boolean _caseSensitive;
085 private List<DocumentComparatorOrderBy> _columns =
086 new ArrayList<DocumentComparatorOrderBy>();
087
088 }