1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.bremersee.apiclient.webflux.contract.spring;
18
19 import static org.springframework.util.ObjectUtils.isEmpty;
20
21 import java.util.function.Predicate;
22 import java.util.stream.Collectors;
23 import org.bremersee.apiclient.webflux.Invocation;
24 import org.bremersee.apiclient.webflux.InvocationParameter;
25 import org.springframework.data.domain.Sort;
26 import org.springframework.data.domain.Sort.Order;
27 import org.springframework.util.LinkedMultiValueMap;
28 import org.springframework.util.MultiValueMap;
29
30
31
32
33
34
35 public class SortRequestParameterResolver implements
36 QueryParametersResolver,
37 Predicate<InvocationParameter> {
38
39 private String requestParamName = "sort";
40
41 private String separatorValue = ",";
42
43 private String descValue = "desc";
44
45
46
47
48
49
50
51 public SortRequestParameterResolver withRequestParamName(String requestParamName) {
52 if (!isEmpty(requestParamName)) {
53 this.requestParamName = requestParamName;
54 }
55 return this;
56 }
57
58
59
60
61
62
63
64 public SortRequestParameterResolver withSeparatorValue(String separatorValue) {
65 if (!isEmpty(separatorValue)) {
66 this.separatorValue = separatorValue;
67 }
68 return this;
69 }
70
71
72
73
74
75
76
77 public SortRequestParameterResolver withDescValue(String descValue) {
78 if (!isEmpty(descValue)) {
79 this.descValue = descValue;
80 }
81 return this;
82 }
83
84 @Override
85 public MultiValueMap<String, Object> apply(Invocation invocation) {
86 return invocation.toMethodParameterStream()
87 .filter(this)
88 .map(InvocationParameter::getValue)
89 .map(value -> getRequestParameters((Sort) value))
90 .collect(
91 LinkedMultiValueMap::new,
92 LinkedMultiValueMap::putAll,
93 LinkedMultiValueMap::putAll);
94 }
95
96 @Override
97 public boolean test(InvocationParameter invocationParameter) {
98 return invocationParameter.getValue() instanceof Sort && invocationParameter
99 .hasNoneParameterAnnotation(Extensions.ILLEGAL_EXTENSIONS_ANNOTATIONS);
100 }
101
102
103
104
105
106
107
108 protected MultiValueMap<String, Object> getRequestParameters(Sort sort) {
109 MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
110 if (sort.isSorted()) {
111 map.put(
112 requestParamName,
113 sort.stream().map(this::getRequestParamValue).collect(Collectors.toList()));
114 }
115 return map;
116 }
117
118
119
120
121
122
123
124 protected String getRequestParamValue(Order order) {
125 StringBuilder sb = new StringBuilder(order.getProperty());
126 if (order.isDescending()) {
127 sb.append(separatorValue).append(descValue);
128 }
129 return sb.toString();
130 }
131
132 }