-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathHierarchyHandler.java
More file actions
313 lines (266 loc) · 11.9 KB
/
Copy pathHierarchyHandler.java
File metadata and controls
313 lines (266 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package my.bookshop.handlers;
import java.util.ArrayDeque;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import com.sap.cds.Row;
import com.sap.cds.ql.CQL;
import com.sap.cds.ql.Select;
import com.sap.cds.ql.cqn.CqnElementRef;
import com.sap.cds.ql.cqn.CqnPredicate;
import com.sap.cds.ql.cqn.CqnSelect;
import com.sap.cds.ql.cqn.CqnValue;
import com.sap.cds.ql.cqn.Modifier;
import com.sap.cds.ql.cqn.transformation.CqnTopLevelsTransformation;
import com.sap.cds.ql.cqn.transformation.CqnAncestorsTransformation;
import com.sap.cds.ql.cqn.transformation.CqnDescendantsTransformation;
import com.sap.cds.ql.cqn.transformation.CqnFilterTransformation;
import com.sap.cds.ql.cqn.transformation.CqnSearchTransformation;
import com.sap.cds.ql.cqn.transformation.CqnOrderByTransformation;
import com.sap.cds.ql.cqn.transformation.CqnTransformation;
import com.sap.cds.services.cds.CdsReadEventContext;
import com.sap.cds.services.cds.CqnService;
import com.sap.cds.services.handler.EventHandler;
import com.sap.cds.services.handler.annotations.Before;
import com.sap.cds.services.handler.annotations.ServiceName;
import com.sap.cds.services.persistence.PersistenceService;
import cds.gen.catalogservice.CatalogService_;
import cds.gen.catalogservice.GenreHierarchy;
import cds.gen.catalogservice.GenreHierarchy_;
import static cds.gen.catalogservice.CatalogService_.GENRE_HIERARCHY;
@Component
@Profile("default") // non-HANA
@ServiceName(CatalogService_.CDS_NAME)
/**
* On HANA, requests for GenreHierarchy are handled generically.
*
* This handler is only in effect when running with the `default` profile on
* H2. It is a stand-in for non-HANA until the CAP Java runtime can also handle
* requests for hierarchies on non-HANA databases.
*
* The handler is neither functionally complete nor correct for all requests. It
* is not intended as a blue-print for custom code.
*/
public class HierarchyHandler implements EventHandler {
private final PersistenceService db;
HierarchyHandler(PersistenceService db) {
this.db = db;
}
@Before(event = CqnService.EVENT_READ, entity = GenreHierarchy_.CDS_NAME)
public void readGenreHierarchy(CdsReadEventContext event) {
List<CqnTransformation> trafos = event.getCqn().transformations();
List<GenreHierarchy> result = null;
if (trafos.size() < 1) {
return;
}
if (getTopLevels(trafos) instanceof CqnTopLevelsTransformation topLevels) {
result = topLevels(topLevels, CQL.TRUE);
} else if (trafos.get(0) instanceof CqnDescendantsTransformation descendants) {
result = handleDescendants(descendants);
} else if (trafos.get(0) instanceof CqnAncestorsTransformation ancestors) {
if (trafos.size() == 2 && trafos.get(1) instanceof CqnTopLevelsTransformation topLevels) {
result = handleAncestors(ancestors, topLevels);
} else if (trafos.size() == 3 && trafos.get(2) instanceof CqnTopLevelsTransformation topLevels) {
result = handleAncestors(ancestors, topLevels);
}
}
setResult(event, result);
}
private CqnTopLevelsTransformation getTopLevels(List<CqnTransformation> trafos) {
if (trafos.get(0) instanceof CqnTopLevelsTransformation topLevels) {
return topLevels;
} else if (trafos.size() == 2 && trafos.get(0) instanceof CqnOrderByTransformation
&& trafos.get(1) instanceof CqnTopLevelsTransformation topLevels) {
return topLevels;
}
return null;
}
private void setResult(CdsReadEventContext event, List<GenreHierarchy> result) {
if (!result.isEmpty()) {
addDrillState(result);
}
event.setResult(result);
}
private void addDrillState(List<GenreHierarchy> ghs) {
List<String> ids = ghs.stream().map(gh -> gh.getId()).toList();
Set<String> parents = ghs.stream().map(gh -> gh.getParentId()).filter(p -> p != null)
.collect(Collectors.toSet());
CqnSelect q = Select.from(GENRE_HIERARCHY).columns(gh -> gh.parent_ID().as("id"))
.where(gh -> gh.parent_ID().in(ids));
Set<Object> nonLeafs = db
.run(q)
.stream().map(r -> r.get("id")).collect(Collectors.toSet());
for (GenreHierarchy gh : ghs) {
String id = gh.getId();
if (nonLeafs.contains(id)) {
if (parents.contains(id)) {
gh.setDrillState("expanded");
} else {
gh.setDrillState("collapsed");
}
} else {
gh.setDrillState("leaf");
}
}
}
private CqnPredicate descendantsFilter(CqnDescendantsTransformation descendants) {
CqnTransformation trafo = descendants.transformations().get(0);
CqnPredicate start = ((CqnFilterTransformation) trafo).filter();
CqnPredicate result = CQL.FALSE;
if (descendants.keepStart()) {
result = CQL.or(result, start);
}
CqnPredicate children = CQL.copy(start, new Modifier() {
@Override
public CqnValue ref(CqnElementRef ref) {
return CQL.get(GenreHierarchy.PARENT_ID);
}
});
result = CQL.or(result, children);
return result;
}
private CqnPredicate ancestorsFilter(CqnAncestorsTransformation ancestors) {
CqnTransformation trafo = ancestors.transformations().get(0);
Select<GenreHierarchy_> inner = Select.from(GENRE_HIERARCHY).columns(gh -> gh.ID());
if (trafo instanceof CqnFilterTransformation filter) {
inner.where(filter.filter());
} else if (trafo instanceof CqnSearchTransformation search) {
inner.search(search.search());
}
Select<GenreHierarchy_> outer = Select.from(GENRE_HIERARCHY)
.columns(gh -> gh.ID().as("i0"),
gh -> gh.parent().ID().as("i1"),
gh -> gh.parent().parent().ID().as("i2"),
gh -> gh.parent().parent().parent().ID().as("i3"),
gh -> gh.parent().parent().parent().parent().ID().as("i4"))
.where(gh -> gh.ID().in(inner));
Set<String> ancestorIds = new HashSet<>();
db.run(outer).stream().forEach(r -> {
addIfNotNull(ancestorIds, r, "i0");
addIfNotNull(ancestorIds, r, "i1");
addIfNotNull(ancestorIds, r, "i2");
addIfNotNull(ancestorIds, r, "i3");
addIfNotNull(ancestorIds, r, "i4");
});
return CQL.get(GenreHierarchy_.ID).in(ancestorIds.stream().toList());
}
private List<GenreHierarchy> handleDescendants(CqnDescendantsTransformation descendants) {
CqnPredicate filter = descendantsFilter(descendants);
CqnSelect childrenCQN = Select.from(GENRE_HIERARCHY).where(filter);
List<GenreHierarchy> nodes = db.run(childrenCQN).listOf(GenreHierarchy.class);
connect(nodes);
return nodes.stream().sorted(new Sorter()).toList();
}
private static void connect(List<GenreHierarchy> nodes) {
Map<String, GenreHierarchy> lookup = new HashMap<>();
nodes.forEach(gh -> lookup.put(gh.getId(), gh));
nodes.forEach(gh -> gh.setParent(lookup.get(gh.getParentId())));
nodes.forEach(gh -> gh.setDistanceFromRoot(distanceFromRoot(gh)));
}
private List<GenreHierarchy> handleAncestors(CqnAncestorsTransformation ancestors,
CqnTopLevelsTransformation topLevels) {
CqnPredicate filter = ancestorsFilter(ancestors);
return topLevels(topLevels, filter);
}
private void addIfNotNull(Set<String> ancestorIds, Row r, String key) {
String id = (String) r.get(key);
if (id != null) {
ancestorIds.add(id);
}
}
private List<GenreHierarchy> topLevels(CqnTopLevelsTransformation topLevels, CqnPredicate filter) {
return topLevels.levels() < 0 ? topLevelsAll(filter) : topLevelsLimit(topLevels, filter);
}
private List<GenreHierarchy> topLevelsLimit(CqnTopLevelsTransformation topLevels, CqnPredicate filter) {
long limit = topLevels.levels();
Map<String, GenreHierarchy> lookup = new HashMap<>();
Map<Object, Long> expandLevels = topLevels.expandLevels();
CqnSelect getRoots = Select.from(GENRE_HIERARCHY).where(gh -> gh.parent_ID().isNull().and(filter));
List<GenreHierarchy> roots = db.run(getRoots).listOf(GenreHierarchy.class);
roots.forEach(root -> {
root.setDistanceFromRoot(0l);
lookup.put(root.getId(), root);
List<String> parents = List.of(root.getId());
for (long i = 1; i < limit; i++) {
List<String> ps = parents;
CqnSelect getChildren = Select.from(GENRE_HIERARCHY)
.where(gh -> gh.parent_ID().in(ps).and(filter));
List<GenreHierarchy> children = db.run(getChildren).listOf(GenreHierarchy.class);
if (children.isEmpty()) {
break;
}
long dfr = i;
parents = children.stream().peek(gh -> {
gh.setParent(lookup.get(gh.getParentId()));
gh.setDistanceFromRoot(dfr);
lookup.put(gh.getId(), gh);
}).map(GenreHierarchy::getId).toList();
}
});
if (!expandLevels.isEmpty()) {
List<String> expandedIds = expandLevels.keySet().stream().map(key -> (String) key).toList();
CqnSelect expandedCQN = Select.from(CatalogService_.GENRE_HIERARCHY).where(gh -> CQL.and(filter,
CQL.or(gh.ID().in(expandedIds), gh.parent_ID().in(expandedIds))));
List<GenreHierarchy> expanded = db.run(expandedCQN).listOf(GenreHierarchy.class);
expanded.forEach(gh -> {
if (!lookup.keySet().contains(gh.getId())) {
gh.setParent(lookup.get(gh.getParentId()));
gh.setDistanceFromRoot(distanceFromRoot(gh));
lookup.put(gh.getId(), gh);
}
});
}
return lookup.values().stream().sorted(new Sorter()).toList();
}
private List<GenreHierarchy> topLevelsAll(CqnPredicate filter) {
CqnSelect allCqn = Select.from(GENRE_HIERARCHY).where(filter);
var all = db.run(allCqn).listOf(GenreHierarchy.class);
connect(all);
return all.stream().sorted(new Sorter()).toList();
}
private static long distanceFromRoot(GenreHierarchy gh) {
long dfr = 0;
while (gh.getParent() != null) {
dfr++;
gh = gh.getParent();
}
return dfr;
}
static class Sorter implements Comparator<GenreHierarchy> {
@Override
public int compare(GenreHierarchy gh1, GenreHierarchy gh2) {
Deque<String> path1 = getPath(gh1);
Deque<String> path2 = getPath(gh2);
int res = 0;
while (true) {
if (path1.isEmpty()) {
return path2.isEmpty() ? 0 : -1;
}
if (path2.isEmpty()) {
return +1;
}
String last1 = path1.pop();
String last2 = path2.pop();
res = last1.compareTo(last2);
if (res != 0) {
return res;
}
}
}
Deque<String> getPath(GenreHierarchy gh) {
Deque<String> path = new ArrayDeque<>();
do {
path.push(gh.getName());
gh = gh.getParent();
} while (gh != null);
return path;
}
}
}