1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.myfaces.tobago.example.demo;
21
22 import org.apache.myfaces.tobago.component.UISheet;
23 import org.apache.myfaces.tobago.event.SortActionEvent;
24 import org.apache.myfaces.tobago.model.SheetState;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 import javax.annotation.PostConstruct;
29 import javax.enterprise.context.SessionScoped;
30 import javax.faces.context.FacesContext;
31 import javax.faces.event.ActionEvent;
32 import javax.inject.Inject;
33 import javax.inject.Named;
34 import java.io.Serializable;
35 import java.lang.invoke.MethodHandles;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.List;
39 import java.util.stream.Collectors;
40
41 @SessionScoped
42 @Named
43 public class SheetSortingController implements Serializable {
44
45 private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
46
47 @Inject
48 private AstroData astroData;
49
50 private List<SolarObject> solarList1;
51 private List<SolarObject> solarList2;
52
53 @PostConstruct
54 private void init() {
55 solarList1 = astroData.findAll().collect(Collectors.toList());
56 solarList2 = astroData.findAll().collect(Collectors.toList());
57 }
58
59 public void sheetSorter(final ActionEvent event) {
60 if (event instanceof SortActionEvent) {
61 final SortActionEvent sortEvent = (SortActionEvent) event;
62 final UISheet sheet = (UISheet) sortEvent.getComponent();
63 final SheetState sheetState = sheet.getSheetState(FacesContext.getCurrentInstance());
64 final List<SolarObject> list = (List<SolarObject>) sheet.getValue();
65 sheetSorter(sheetState, list);
66 }
67 }
68
69 private void sheetSorter(final SheetState sheetState, final List<SolarObject> list) {
70 final String columnId = sheetState.getSortedColumnId();
71
72 LOG.info("Sorting column '{}'", columnId);
73
74 if ("customColumnName".equals(columnId)) {
75 list.sort(Comparator.comparing(SolarObject::getName, String.CASE_INSENSITIVE_ORDER));
76 } else if ("customColumnPeriod".equals(columnId)) {
77 list.sort(Comparator.comparing(d -> Math.abs(d.getPeriod())));
78 } else if ("customColumnYear".equals(columnId)) {
79 list.sort(Comparator.comparing(d -> d.getDiscoverYear() != null ? d.getDiscoverYear() : 0));
80 }
81
82 if (!sheetState.isAscending()) {
83 Collections.reverse(list);
84 }
85 }
86
87 public List<SolarObject> getSolarList1() {
88 return solarList1;
89 }
90
91 public void setSolarList1(List<SolarObject> solarList1) {
92 this.solarList1 = solarList1;
93 }
94
95 public List<SolarObject> getSolarList2() {
96 return solarList2;
97 }
98
99 public void setSolarList2(List<SolarObject> solarList2) {
100 this.solarList2 = solarList2;
101 }
102 }