/
Filters.java
368 lines (342 loc) · 15.6 KB
/
Filters.java
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2018 the original author or authors.
*/
package org.assertj.core.api.filter;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.util.Lists.newArrayList;
import static org.assertj.core.util.Objects.areEqual;
import static org.assertj.core.util.Preconditions.checkArgument;
import static org.assertj.core.util.Preconditions.checkNotNull;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.Condition;
import org.assertj.core.util.Strings;
import org.assertj.core.util.VisibleForTesting;
import org.assertj.core.util.introspection.IntrospectionError;
import org.assertj.core.util.introspection.PropertyOrFieldSupport;
/**
* Filters the elements of a given <code>{@link Iterable}</code> or array according to the specified filter criteria.
* <p>
* Filter criteria can be expressed either by a {@link Condition} or a pseudo filter language on elements properties.
* <p>
* With fluent filter language on element properties/fields :
* <pre><code class='java'> assertThat(filter(players).with("pointsPerGame").greaterThan(20)
* .and("assistsPerGame").greaterThan(7).get())
* .containsOnly(james, rose);</code></pre>
*
* With {@link Condition} :
* <pre><code class='java'> List<Player> players = ...;
*
* Condition<Player> potentialMVP = new Condition<Player>("is a possible MVP"){
* public boolean matches(Player player) {
* return player.getPointsPerGame() > 20 && player.getAssistsPerGame() > 7;
* };
* };
*
* // use filter static method to build Filters
* assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);</code></pre>
*
* @param <E> the type of element of group to filter.
*
* @author Joel Costigliola
* @author Mikhail Mazursky
*/
public class Filters<E> {
// initialIterable is never modified, it represents the group before any filters have been performed
@VisibleForTesting
final Iterable<E> initialIterable;
List<E> filteredIterable;
private final PropertyOrFieldSupport propertyOrFieldSupport = PropertyOrFieldSupport.EXTRACTION;
/**
* The name of the property used for filtering.
*/
private String propertyOrFieldNameToFilterOn;
/**
* Creates a new <code>{@link Filters}</code> with the {@link Iterable} to filter.
* <p>
* Chain this call to express filter criteria either by a {@link Condition} or a pseudo filter language on elements
* properties or fields (reading private fields is supported but disabled by calling
* {@link Assertions#setAllowExtractingPrivateFields(boolean) Assertions.setAllowExtractingPrivateFields(false)}.
* <p>
* Note that the given {@link Iterable} is not modified, the filters are performed on a copy.
* <p>
* With fluent filter language on element properties/fields :
* <pre><code class='java'> List<Player> players = ...;
*
* assertThat(filter(players).with("pointsPerGame").greaterThan(20)
* .and("assistsPerGame").greaterThan(7).get())
* .containsOnly(james, rose);</code></pre>
*
* With {@link Condition} :
* <pre><code class='java'>
* public boolean matches(Player player) {
* return player.getPointsPerGame() > 20 && player.getAssistsPerGame() > 7;
* };
* };
*
* // use filter static method to build Filters
* assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);</code></pre>
*
* @param <E> the iterable elements type.
* @param iterable the {@code Iterable} to filter.
* @throws NullPointerException if the given iterable is {@code null}.
* @return the created <code>{@link Filters}</code>.
*/
public static <E> Filters<E> filter(Iterable<E> iterable) {
return new Filters<>(checkNotNull(iterable, "The iterable to filter should not be null"));
}
/**
* Creates a new <code>{@link Filters}</code> with the array to filter.
* <p>
* Chain this call to express filter criteria either by a {@link Condition} or a pseudo filter language on elements
* properties.
* <p>
* Note that the given array is not modified, the filters are performed on an {@link Iterable} copy of the array.
* <p>
* With {@link Condition} :
* <pre><code class='java'> Player[] players = ...;
*
* assertThat(filter(players).with("pointsPerGame").greaterThan(20)
* .and("assistsPerGame").greaterThan(7).get())
* .containsOnly(james, rose);</code></pre>
*
* With {@link Condition} :
* <pre><code class='java'> Condition<Player> potentialMVP = new Condition<Player>("is a possible MVP"){
* public boolean matches(Player player) {
* return player.getPointsPerGame() > 20 && player.getAssistsPerGame() > 7;
* };
* };
*
* // use filter static method to build Filters
* assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);</code></pre>
*
* @param <E> the array elements type.
* @param array the array to filter.
* @throws NullPointerException if the given array is {@code null}.
* @return the created <code>{@link Filters}</code>.
*/
public static <E> Filters<E> filter(E[] array) {
return new Filters<>(checkNotNull(array, "The array to filter should not be null"));
}
private Filters(Iterable<E> iterable) {
this.initialIterable = iterable;
// copy list to avoid modifying iterable
this.filteredIterable = newArrayList(iterable);
}
private Filters(E[] array) {
this(newArrayList(array));
}
/**
* Filter the underlying group, keeping only elements satisfying the given {@link Condition}.<br>
* Same as {@link #having(Condition)} - pick the method you prefer to have the most readable code.
*
* <pre><code class='java'> List<Player> players = ...;
*
* Condition<Player> potentialMVP = new Condition<Player>("is a possible MVP") {
* public boolean matches(Player player) {
* return player.getPointsPerGame() > 20 && player.getAssistsPerGame() > 7;
* };
* };
*
* // use filter static method to build Filters
* assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);</code></pre>
*
* @param condition the filter {@link Condition}.
* @return this {@link Filters} to chain other filter operations.
* @throws IllegalArgumentException if the given condition is {@code null}.
*/
public Filters<E> being(Condition<? super E> condition) {
checkArgument(condition != null, "The filter condition should not be null");
return applyFilterCondition(condition);
}
/**
* Filter the underlying group, keeping only elements satisfying the given {@link Condition}.<br>
* Same as {@link #being(Condition)} - pick the method you prefer to have the most readable code.
*
* <pre><code class='java'> List<Player> players = ...;
*
* Condition<Player> mvpStats = new Condition<Player>("is a possible MVP") {
* public boolean matches(Player player) {
* return player.getPointsPerGame() > 20 && player.getAssistsPerGame() > 7;
* };
* };
*
* // use filter static method to build Filters
* assertThat(filter(players).having(mvpStats).get()).containsOnly(james, rose);</code></pre>
*
* @param condition the filter {@link Condition}.
* @return this {@link Filters} to chain other filter operations.
* @throws IllegalArgumentException if the given condition is {@code null}.
*/
public Filters<E> having(Condition<? super E> condition) {
checkArgument(condition != null, "The filter condition should not be null");
return applyFilterCondition(condition);
}
private Filters<E> applyFilterCondition(Condition<? super E> condition) {
this.filteredIterable = filteredIterable.stream().filter(condition::matches).collect(toList());
return this;
}
/**
* Filter the underlying group, keeping only elements with a property equals to given value.
* <p>
* Let's, for example, filter Employees with name "Alex" :
* <pre><code class='java'> filter(employees).with("name", "Alex").get();</code></pre>
*
* which is shortcut of :
* <pre><code class='java'> filter(employees).with("name").equalsTo("Alex").get();</code></pre>
*
* @param propertyOrFieldName the name of the property/field whose value will compared to given value. It may be a
* nested property.
* @param propertyValue the expected property value.
* @return this {@link Filters} to chain other filter operations.
* @throws IntrospectionError if an element in the given {@code Iterable} does not have a property with a given
* propertyOrFieldName.
* @throws IllegalArgumentException if the given propertyOrFieldName is {@code null}.
*/
public Filters<E> with(String propertyOrFieldName, Object propertyValue) {
validatePropertyOrFieldName(propertyOrFieldName);
propertyOrFieldNameToFilterOn = propertyOrFieldName;
return equalsTo(propertyValue);
}
/**
* Sets the name of the property used for filtering, it may be a nested property like
* <code>"adress.street.name"</code>.
* <p>
* The typical usage is to chain this call with a comparison method, for example :
* <pre><code class='java'> filter(employees).with("name").equalsTo("Alex").get();</code></pre>
*
* @param propertyOrFieldName the name of the property/field used for filtering. It may be a nested property.
* @return this {@link Filters} to chain other filter operation.
* @throws IllegalArgumentException if the given propertyOrFieldName is {@code null}.
*/
public Filters<E> with(String propertyOrFieldName) {
validatePropertyOrFieldName(propertyOrFieldName);
propertyOrFieldNameToFilterOn = propertyOrFieldName;
return this;
}
private void validatePropertyOrFieldName(String propertyOrFieldName) {
checkArgument(!Strings.isNullOrEmpty(propertyOrFieldName),
"The property/field name to filter on should not be null or empty");
}
/**
* Alias of {@link #with(String)} for synthetic sugar to write things like :
* <pre><code class='java'> filter(employees).with("name").equalsTo("Alex").and("job").notEqualsTo("lawyer").get();</code></pre>
*
* @param propertyOrFieldName the name of the property/field used for filtering. It may be a nested property.
* @return this {@link Filters} to chain other filter operation.
* @throws IllegalArgumentException if the given propertyOrFieldName is {@code null}.
*/
public Filters<E> and(String propertyOrFieldName) {
return with(propertyOrFieldName);
}
/**
* Filters the underlying iterable to keep object with property (specified by {@link #with(String)}) <b>equals to</b>
* given value.
* <p>
* Typical usage :
* <pre><code class='java'> filter(employees).with("name").equalsTo("Luke").get();</code></pre>
*
* @param propertyValue the filter value.
* @return this {@link Filters} to chain other filter operation.
* @throws IllegalArgumentException if the property name to filter on has not been set.
*/
public Filters<E> equalsTo(Object propertyValue) {
checkPropertyNameToFilterOnIsNotNull();
this.filteredIterable = filteredIterable.stream().filter(element -> {
Object propertyValueOfCurrentElement = propertyOrFieldSupport.getValueOf(propertyOrFieldNameToFilterOn, element);
return areEqual(propertyValueOfCurrentElement, propertyValue);
}).collect(toList());
return this;
}
/**
* Filters the underlying iterable to keep object with property (specified by {@link #with(String)}) <b>not equals
* to</b> given
* value.
* <p>
* Typical usage :
* <pre><code class='java'> filter(employees).with("name").notEqualsTo("Vader").get();</code></pre>
*
* @param propertyValue the filter value.
* @return this {@link Filters} to chain other filter operation.
* @throws IllegalArgumentException if the property name to filter on has not been set.
*/
public Filters<E> notEqualsTo(Object propertyValue) {
checkPropertyNameToFilterOnIsNotNull();
this.filteredIterable = filteredIterable.stream().filter(element -> {
Object propertyValueOfCurrentElement = propertyOrFieldSupport.getValueOf(propertyOrFieldNameToFilterOn, element);
return !areEqual(propertyValueOfCurrentElement, propertyValue);
}).collect(toList());
return this;
}
private void checkPropertyNameToFilterOnIsNotNull() {
checkArgument(propertyOrFieldNameToFilterOn != null,
"The property name to filter on has not been set - no filtering is possible");
}
/**
* Filters the underlying iterable to keep object with property (specified by {@link #with(String)}) <b>equals to</b>
* one of the given values.
* <p>
* Typical usage :
* <pre><code class='java'>filter(players).with("team").in("Bulls", "Lakers").get();</code></pre>
*
* @param propertyValues the filter values.
* @return this {@link Filters} to chain other filter operation.
* @throws IllegalArgumentException if the property name to filter on has not been set.
*/
public Filters<E> in(Object... propertyValues) {
checkPropertyNameToFilterOnIsNotNull();
this.filteredIterable = filteredIterable.stream().filter(element -> {
Object propertyValueOfCurrentElement = propertyOrFieldSupport.getValueOf(propertyOrFieldNameToFilterOn, element);
return isItemInArray(propertyValueOfCurrentElement, propertyValues);
}).collect(toList());
return this;
}
/**
* Filters the underlying iterable to keep object with property (specified by {@link #with(String)}) <b>not in</b> the
* given values.
* <p>
* Typical usage :
* <pre><code class='java'> filter(players).with("team").notIn("Heat", "Lakers").get();</code></pre>
*
* @param propertyValues the filter values.
* @return this {@link Filters} to chain other filter operation.
* @throws IllegalArgumentException if the property name to filter on has not been set.
*/
public Filters<E> notIn(Object... propertyValues) {
checkPropertyNameToFilterOnIsNotNull();
this.filteredIterable = filteredIterable.stream().filter(element -> {
Object propertyValueOfCurrentElement = propertyOrFieldSupport.getValueOf(propertyOrFieldNameToFilterOn, element);
return !isItemInArray(propertyValueOfCurrentElement, propertyValues);
}).collect(toList());
return this;
}
/**
* Returns <code>true</code> if given item is in given array, <code>false</code> otherwise.
*
* @param item the object to look for in arrayOfValues
* @param arrayOfValues the array of values
* @return <code>true</code> if given item is in given array, <code>false</code> otherwise.
*/
private static boolean isItemInArray(Object item, Object[] arrayOfValues) {
for (Object value : arrayOfValues)
if (areEqual(value, item)) return true;
return false;
}
/**
* Returns the resulting filtered Iterable<E> (even if the constructor parameter type was an array).
*
* @return the Iterable<E> containing the filtered elements.
*/
public List<E> get() {
return filteredIterable;
}
}