1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.primefaces.extensions.component.sheet;
23
24 import java.text.Collator;
25 import java.util.Comparator;
26 import java.util.Locale;
27
28 import javax.el.ValueExpression;
29 import javax.faces.FacesException;
30 import javax.faces.context.FacesContext;
31
32 import org.primefaces.model.SortMeta;
33
34
35
36
37 public class BeanPropertyComparator implements Comparator<Object> {
38
39 private String var;
40 private Locale locale;
41 private Collator collator;
42 private SortMeta sortMeta;
43
44 public BeanPropertyComparator(String var, SortMeta sortMeta, Locale locale) {
45 this.sortMeta = sortMeta;
46 this.var = var;
47 this.locale = locale;
48 collator = Collator.getInstance(locale);
49 }
50
51 @SuppressWarnings("java:S3776")
52 @Override
53 public int compare(Object obj1, Object obj2) {
54 FacesContext context = FacesContext.getCurrentInstance();
55 ValueExpression sortBy = sortMeta.getSortBy();
56
57 try {
58 context.getExternalContext().getRequestMap().put(var, obj1);
59 Object value1 = sortBy.getValue(context.getELContext());
60
61 context.getExternalContext().getRequestMap().put(var, obj2);
62 Object value2 = sortBy.getValue(context.getELContext());
63
64 int result;
65
66 if (sortMeta.getFunction() == null) {
67
68 if (value1 == null && value2 == null) {
69 return 0;
70 }
71 else if (value1 == null) {
72 result = sortMeta.getNullSortOrder();
73 }
74 else if (value2 == null) {
75 result = -1 * sortMeta.getNullSortOrder();
76 }
77 else if (value1 instanceof String && value2 instanceof String) {
78 if (sortMeta.isCaseSensitiveSort()) {
79 result = collator.compare(value1, value2);
80 }
81 else {
82 String str1 = (((String) value1).toLowerCase(locale));
83 String str2 = (((String) value2).toLowerCase(locale));
84
85 result = collator.compare(str1, str2);
86 }
87 }
88 else {
89 result = ((Comparable<Object>) value1).compareTo(value2);
90 }
91 }
92 else {
93 result = (Integer) sortMeta.getFunction().invoke(context.getELContext(), new Object[] {value1, value2});
94 }
95
96 return sortMeta.getOrder().isAscending() ? result : -1 * result;
97
98 }
99 catch (Exception e) {
100 throw new FacesException(e);
101 }
102 }
103 }