-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathContext.java
More file actions
105 lines (87 loc) · 2.5 KB
/
Context.java
File metadata and controls
105 lines (87 loc) · 2.5 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
package u027;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Context {
private static Map<String, List<Row>> tables = new HashMap<>();
static {
List<Row> list = new ArrayList<>();
list.add(new Row("John", "Doe"));
list.add(new Row("Jan", "Kowalski"));
list.add(new Row("Dominic", "Doom"));
tables.put("people", list);
}
private String table;
private String column;
/**
* Index of column to be shown in result. Calculated in {@link #setColumnMapper()}
*/
private int colIndex = -1;
/**
* Default setup, used for clearing the context for next queries. See {@link Context#clear()}
*/
private static final Predicate<String> matchAnyString = s -> s.length() > 0;
private static final Function<String, Stream<? extends String>> matchAllColumns = Stream::of;
/**
* Varies based on setup in subclasses of {@link Expression}
*/
private Predicate<String> whereFilter = matchAnyString;
private Function<String, Stream<? extends String>> columnMapper = matchAllColumns;
void setColumn(String column) {
this.column = column;
setColumnMapper();
}
void setTable(String table) {
this.table = table;
}
void setFilter(Predicate<String> filter) {
whereFilter = filter;
}
/**
* Clears the context to defaults. No filters, match all columns.
*/
void clear() {
column = "";
columnMapper = matchAllColumns;
whereFilter = matchAnyString;
}
List<String> search() {
List<String> result = tables.entrySet()
.stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(table))
.flatMap(entry -> Stream.of(entry.getValue()))
.flatMap(Collection::stream)
.map(Row::toString)
.flatMap(columnMapper)
.filter(whereFilter)
.collect(Collectors.toList());
clear();
return result;
}
/**
* Sets column mapper based on {@link #column} attribute. Note: If column is unknown, will remain
* to look for all columns.
*/
private void setColumnMapper() {
switch (column) {
case "*":
colIndex = -1;
break;
case "name":
colIndex = 0;
break;
case "surname":
colIndex = 1;
break;
}
if (colIndex != -1) {
columnMapper = s -> Stream.of(s.split(" ")[colIndex]);
}
}
}