-
Notifications
You must be signed in to change notification settings - Fork 5
/
Snapshot.java
663 lines (597 loc) · 20.7 KB
/
Snapshot.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
package org.genericsystem.api.core;
import java.lang.invoke.MethodHandles;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
* Represents a <code>Set</code> of results <em>aware</em> of its context.
* <p>
* This is a functional interface whose functional method is {@link #unfilteredStream}.
* </p>
*
* @author Nicolas Feybesse
*
* @param <T>
* the type of element contained by the <code>Snapshot</code>.
*/
@FunctionalInterface
public interface Snapshot<T> extends Iterable<T> {
/**
* Returns an empty Snapshot.
*
* @return an empty Snapshot.
*/
public static<T> Snapshot<T> empty() {
return new Snapshot<T>() {
@Override public Stream<T> unfilteredStream() {
return Stream.empty();
}
};
}
/**
* Returns a Snapshot containing only an element.
*
* @param element The returned Snapshot’s element.
* @return A Snapshot with an element.
*/
public static<T> Snapshot<T> singleton(T element) {
return new Snapshot<T>() {
@Override
public Stream<T> unfilteredStream() {
return Stream.of(element);
}
};
}
/**
* Returns a Snapshot containing the elements of the given Collection.
*
* @param elements The returned Snapshot’s elements.
* @return A Snapshot with the given elements.
*/
public static<T> Snapshot<T> fromCollection(Collection<T> elements) {
return new Snapshot<T>() {
@Override
public Stream<T> unfilteredStream() {
return elements.stream();
}
};
}
/**
* Returns this Snapshot’s parent. The return value must be non-null iff
* {@link #getFilter()}’s return value is not null.
*
* @return This Snapshot’s parent.
*/
default Snapshot<T> getParent() {
return null;
}
/**
* Returns the {@link IndexFilter} to apply to the parent to build this Snapshot.
* The return value must be non-null iff {@link #getParent()}’s return value is not null.
*
* @return This Snapshot’s filter.
*/
default IndexFilter getFilter() {
return null;
}
/**
* Returns an Iterator over the elements of this Snapshot.
*
* @return An iterator for this Snapshot.
*/
@Override
default Iterator<T> iterator() {
return stream().iterator();
}
/**
* Returns a <code>Stream</code> of this <code>Snapshot</code>.
* This method builds this Snapshot’s stream(), taking into account
* the values of {@link #getFilter()} and {@link #getParent()} if any.
* It must not be overridden. To define the Snapshot contents, override
* the methods {@link #unfilteredStream()}, {@link #getAddsObservable()}
* and {@link #getRemovesObservable()}.
*
* @return a <code>Stream</code> of this <code>Snapshot</code>.
*/
default Stream<T> stream() {
List<IndexFilter> filters = new LinkedList<>();
Snapshot<T> current = this;
while (current.getParent() != null) {
filters.add(0, current.getFilter());
current = current.getParent();
}
if (!filters.isEmpty())
return current.filter(filters).unfilteredStream();
return unfilteredStream();
}
/**
* Defines a Stream of this Snapshot.
* If this Snapshot’s {@link #getFilter()}’s method returns {@code null}, the return value of
* {@link #stream()} is the same as the return value of unfilteredStream().
* This method must be overridden when defining a new Snapshot that can then be filtered
* with {@link #filter(IndexFilter)} However, to obtain a Stream of any Snapshot,
* {@link #stream()} should be used, never {@link #unfilteredStream()}.
*
* @return a Stream of this Snapshot.
*/
public Stream<T> unfilteredStream();
/**
* Returns the number of elements in this snapshot.
*
* @return the number of elements in this snapshot.
*/
default int size() {
return (int) stream().count();
}
/**
* Returns <code>true</code> if this snapshot contains no elements.
*
* @return <code>true</code> if this snapshot contains no elements.
*/
default boolean isEmpty() {
return stream().count() == 0;
}
/**
* Returns <code>true</code> if this snapshot contains the specified element.
*
* @param o
* element whose presence in this snapshot is to be tested.
* @return <code>true</code> if this snapshot contains the specified element.
*/
default boolean contains(Object o) {
return o.equals(get(o));
}
/**
* Returns <code>true</code> if this snapshot contains all of the elements in the specified snapshot.
*
* @param c
* collection to be checked for containment in this snapshot.
* @return <code>true</code> if this snapshot contains all of the elements in the specified snapshot.
*/
default boolean containsAll(Collection<?> c) {
return c.stream().allMatch(this::contains);
}
/**
* Returns the first element in this snapshot equals to the specified object or <code>null</code> if no element in this snapshot is equal to the specified object.
*
* @param o
* object to be tested for equality.
* @return the first element in this snapshot equals to the specified object or <code>null</code> if no element in this snapshot is equal to the specified object.
*/
default T get(Object o) {
return stream().filter(o::equals).findFirst().orElse(null);
}
/**
* Returns a <code>String</code> representation of all vertices contained in this snapshot.
*
* @return a <code>String</code> representation of all vertices contained in this snapshot.
*/
default String info() {
return stream().collect(Collectors.toList()).toString();
}
/**
* Returns the first element of this snapshot or <code>null</code> if this snapshot is empty.
*
* @return the first element of this snapshot or <code>null</code> if this snapshot is empty.
*/
default T first() {
return (iterator().hasNext() ? iterator().next() : null);
}
/**
* Returns the Snapshot’s element with the given index.
* Returns the element at the given index in the iterator returned by
* {@link #iterator()}. If there is no such element, returns {@code null}.
*
* @param index The index of the wanted element.
* @return The element at the given index, or {@code null} if there is no
* element at that index.
*/
default T getByIndex(int index) {
Iterator<T> iterator = iterator();
int i = 0;
while (iterator.hasNext()) {
if (index == i)
return iterator.next();
iterator.next();
i++;
}
return null;
}
/**
* Returns an {@link Observable} emitting the items added to the Snapshot after it was created.
* This must be overridden if these updates are necessary, e.g. to update a view of the Snapshot’s contents.
*
* @return An {@link Observable} emitting the elements added to the Snapshot after its creation.
* An empty Observable by default.
*/
default Observable<T> getAddsObservable() {
return Observable.empty();
}
/**
* Returns an {@link Observable} emitting the items deleted from the Snapshot after it was created.
* This must be overridden if these updates are necessary, e.g. to update a view of the Snapshot’s contents.
*
* @return An {@link Observable} emitting the elements removed from the Snapshot since its creation.
* An empty Observable by default.
*/
default Observable<T> getRemovesObservable() {
return Observable.empty();
}
/**
* Returns the {@link Comparator} for this Snapshot. This is used only to determine the indices of the elements
* in {@link #getIndexedElements()}, and to order the emitted sets in {@link #setOnChanged()}.
* The Comparator provided must be consistent with equals (see {@link Comparator}).
*
* @return The Comparator for this Snapshot. {@code null} by default.
*/
default Comparator<T> getComparator() {
return null;
}
/**
* Returns an {@link Observable} emitting each element of the Snapshot with its index.
* Returns an Observable that emits {@link IndexedElement}s corresponding to:
* <ul>
* <li>
* The items initially contained in this Snapshot, with an index
* corresponding to their position in a List representing the Snapshot.
* </li>
* <li>
* The items added to this Snapshot as they are emitted by the Observable obtained
* with {@link #getAddsObservable()}, with an index corresponding to their position
* in a List representing the Snapshot.
* </li>
* <li>
* The items removed from this Snapshot as they are emitted by the Observable obtained
* with {@link #getRemovesObservable()}, with an index of -1.
* </li>
* </ul>
*
* <p>
* <b>Warning:</b> Although this method returns indices as though the Snapshot was represented by a List, it
* uses a Set internally to forbid duplicates.
* </p>
*
* <p>
* If {@link #getComparator()} returns a non-null value, the provided {@link Comparator} is used to order
* the elements of the Snapshot.
* </p>
*
* @return An {@link Observable} emitting the indexed elements of this Snapshot.
*/
default Observable<IndexedElement<T>> getIndexedElements() {
Set<T> set = getComparator() != null ? new TreeSet<>(getComparator()) : new HashSet<T>();
return Observable.merge(Observable.concat(Observable.fromIterable(toList()), getAddsObservable()).map(g -> new TaggedElement<T, ChangeType>(g, ChangeType.ADD)),
getRemovesObservable().map(g -> new TaggedElement<T, ChangeType>(g, ChangeType.REMOVE)))
.scan(new TaggedElement<Set<T>, IndexedElement<T>>(set, null), (acc, change) -> {
if (change.tag == ChangeType.ADD) {
if (acc.element.add(change.element)) {
if (getComparator() != null)
return new TaggedElement<>(acc.element, new IndexedElement<T>(change.element, Collections.binarySearch(new ArrayList<T>(acc.element), change.element, getComparator())));
else
return new TaggedElement<>(acc.element, new IndexedElement<T>(change.element, new ArrayList<T>(acc.element).indexOf(change.element)));
}
return new TaggedElement<>(acc.element, null);
} else {
acc.element.remove(change.element);
return new TaggedElement<>(acc.element, new IndexedElement<T>(change.element, -1));
}
}).filter(tagElt -> tagElt.tag != null).map(tagElt -> tagElt.tag);
}
/**
* Returns an {@link Observable} emitting a {@link Set} representing the Snapshot after each change.
*
* If {@link #getComparator()} provides a {@link Comparator} to use for this Snapshot, the emitted set
* is ordered with the given comparator.
*
* @return An {@link Observable} emitting a {@link Set} representing the Snapshot after each change.
*/
default Observable<Set<T>> setOnChanged() {
Set<T> set = getComparator() != null ? new TreeSet<>(getComparator()) : new HashSet<T>();
set.addAll(toList());
return Observable.merge(getAddsObservable().map(g -> new TaggedElement<T, ChangeType>(g, ChangeType.ADD)),
getRemovesObservable().map(g -> new TaggedElement<T, ChangeType>(g, ChangeType.REMOVE)))
.scan(new TaggedElement<Set<T>, Boolean>(set, true), (acc, change) -> {
if (change.tag == ChangeType.ADD) {
if (acc.element.add(change.element))
return new TaggedElement<>(acc.element, true);
return new TaggedElement<>(acc.element, false);
} else {
if (acc.element.remove(change.element))
return new TaggedElement<>(acc.element, true);
return new TaggedElement<>(acc.element, false);
}
}).filter(tagElt -> tagElt.tag).map(tagElt -> Collections.unmodifiableSet(tagElt.element));
}
/**
* Returns a new Snapshot sorted with the given {@link Comparator}.
*
* @param comparator The {@link Comparator} to use for the new Snapshot.
* @return A Snapshot sorted with the given Comparator.
*/
default Snapshot<T> sort(Comparator<T> comparator) {
return new Snapshot<T>() {
@Override
public Stream<T> unfilteredStream() {
return Snapshot.this.stream();
}
@Override
public Comparator<T> getComparator() {
return comparator;
}
@Override
public Observable<T> getAddsObservable() {
return Snapshot.this.getAddsObservable();
}
@Override
public Observable<T> getRemovesObservable() {
return Snapshot.this.getRemovesObservable();
}
};
}
/**
* Returns a new Snapshot sorted according to the natural order.
*
* If the Snapshot’s elements implement {@link Comparable}, the new Snapshot uses
* this implementation to sort the elements. Otherwise, the elements are sorted according
* to the Strings returned by {@link #toString()}, using the {@link Collator} for the current
* default Locale.
*
* @return A Snapshot sorted with the natural order.
*/
default Snapshot<T> sorted() {
Comparator<T> naturalOrder = new Comparator<T>() {
@SuppressWarnings("unchecked")
@Override
public int compare(T o1, T o2) {
if (o1 == null && o2 == null)
return 0;
if (o1 == null)
return -1;
if (o2 == null)
return 1;
if (o1 instanceof Comparable) {
return ((Comparable<T>) o1).compareTo(o2);
}
return Collator.getInstance().compare(o1.toString(), o2.toString());
}
};
return sort(naturalOrder);
}
/**
* Returns a new Snapshot containing only the elements matching the given {@link Predicate}.
*
* If {@link #getComparator()} defines a {@link Comparator} for the current Snapshot, the sort order
* is kept for the returned Snapshot.
*
* @param predicate The predicate used to filter the Snapshot.
* @return A Snapshot filtered with the given predicate.
*/
default Snapshot<T> filter(Predicate<T> predicate) {
return new Snapshot<T>() {
@Override
public Stream<T> unfilteredStream() {
return Snapshot.this.stream().filter(predicate);
}
@Override
public Comparator<T> getComparator() {
return Snapshot.this.getComparator();
}
@Override
public Observable<T> getAddsObservable() {
return Snapshot.this.getAddsObservable().filter(g -> predicate.test(g)).replay().refCount();
}
@Override
public Observable<T> getRemovesObservable() {
return Snapshot.this.getRemovesObservable().filter(g -> predicate.test(g)).replay().refCount();
}
@Override
public T get(Object o) {
T result = Snapshot.this.get(o);
return result != null && predicate.test(result) ? result : null;
}
};
}
/**
* A new Snapshot filtered with the given {@link IndexFilter}.
*
* The returned Snapshot is a child of the current Snapshot.
* If {@link #getComparator()} defines a {@link Comparator} for the current Snapshot, the sort order
* is kept for the returned Snapshot.
*
* @param filter The filter to use to select the elements to keep.
* @return A Snapshot filtered with the given IndexFilter.
*/
default Snapshot<T> filter(IndexFilter filter) {
return new Snapshot<T>() {
@Override
public Snapshot<T> getParent() {
return Snapshot.this;
}
@Override
public IndexFilter getFilter() {
return filter;
}
@Override
public Comparator<T> getComparator() {
return Snapshot.this.getComparator();
}
@Override
public Observable<T> getAddsObservable() {
return getParent().getAddsObservable().filter(g -> filter.test((IGeneric<?>) g)).replay().refCount();
}
@Override
public Observable<T> getRemovesObservable() {
return getParent().getRemovesObservable().filter(g -> filter.test((IGeneric<?>) g)).replay().refCount();
}
@Override
public Stream<T> unfilteredStream() {
throw new UnsupportedOperationException("unfilteredStream() should be called only on unfiltered snapshots.");
}
};
}
/**
* A new Snapshot filtered with the given {@link IndexFilter}s.
*
* If {@link #getComparator()} defines a {@link Comparator} for the current Snapshot, the sort order
* is kept for the returned Snapshot.
*
* @param filters The filters to use to select the elements to keep.
* @return A Snapshot filtered with the given IndexFilters.
*/
default Snapshot<T> filter(List<IndexFilter> filters) {
return new Snapshot<T>() {
@Override
public Stream<T> unfilteredStream() {
return Snapshot.this.stream().filter(g -> filters.stream().allMatch(filter -> filter.test((IGeneric<?>) g)));
}
@Override
public Comparator<T> getComparator() {
return Snapshot.this.getComparator();
}
@Override
public Observable<T> getAddsObservable() {
return Snapshot.this.getAddsObservable().filter(g -> filters.stream().allMatch(filter -> filter.test((IGeneric<?>) g))).replay().refCount();
}
@Override
public Observable<T> getRemovesObservable() {
return Snapshot.this.getRemovesObservable().filter(g -> filters.stream().allMatch(filter -> filter.test((IGeneric<?>) g))).replay().refCount();
}
@Override
public T get(Object o) {
T result = Snapshot.this.get(o);
return result != null && filters.stream().allMatch(filter -> filter.test((IGeneric<?>) result)) ? result : null;
}
};
}
/**
* Applies a transformation to each element of the Snapshot.
*
* If {@link #getComparator()} defines a {@link Comparator} for the current Snapshot, the sort order
* is kept for the returned Snapshot.
*
* @param mapper The transformation to apply to the Snapshot’s elements.
* @return A Snapshot containing the result of the application of the given function
* to each Snapshot element.
*/
default <U> Snapshot<U> map(Function<T, U> mapper) {
return new Snapshot<U>() {
@Override
public Stream<U> unfilteredStream() {
return Snapshot.this.stream().map(e -> {
try {
return mapper.apply(e);
} catch (Exception ex) {
throw new IllegalStateException("Exception while handling Snapshot.", ex);
}
});
}
// Keep order from before the mapping.
@Override
public Observable<IndexedElement<U>> getIndexedElements() {
return Snapshot.this.getIndexedElements().map(ie -> new IndexedElement<>(mapper.apply(ie.getElement()), ie.getIndex()));
}
@Override
public Observable<U> getAddsObservable() {
return Snapshot.this.getAddsObservable().map(mapper);
}
@Override
public Observable<U> getRemovesObservable() {
return Snapshot.this.getRemovesObservable().map(mapper);
}
};
}
/**
* Returns a List representation of the Snapshot.
*
* @return A list representation of the Snapshot.
*/
default List<T> toList() {
return stream().collect(Collectors.toList());
}
/**
* Returns an ObservableList representing the Snapshot’s state.
*
* Deprecated because is does not allow disposal of the subscriptions
* to getAddsObservable() and getRemovesObservable().
*
* @return an ObservableList representing this Snapshot.
*/
@Deprecated
default ObservableList<T> toObservableList() {
Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
ObservableList<T> list = FXCollections.observableArrayList(toList());
CompositeDisposable disposables = new CompositeDisposable();
disposables.add(getAddsObservable().subscribe(g -> {
if (!list.contains(g)) {
list.add(g);
logger.debug("Snapshot {}, generic added, {}", System.identityHashCode(this), g);
}
}, e -> logger.error("Exception while computing observable list.", e)));
disposables.add(getRemovesObservable().subscribe(g -> {
list.remove(g);
logger.debug("Snapshot {}, generic removed, {}", System.identityHashCode(this), g);
}, e -> logger.error("Exception while computing observable list.", e)));
return list;
}
public static enum ChangeType {
ADD, REMOVE;
}
public static class TaggedElement<T, U> {
protected final T element;
protected final U tag;
public TaggedElement(T element, U tag) {
this.element = element;
this.tag = tag;
}
}
/**
* Helper class whose instances contain an element of type T and an int index.
* Used by {@link Snapshot#getIndexedElements()} to return both an added or removed
* element with the corresponding index.
*
* @param <T>
*/
public static class IndexedElement<T> {
private final int index;
private final T element;
public IndexedElement(T element, int index) {
this.element = element;
this.index = index;
}
public int getIndex() {
return index;
}
public T getElement() {
return element;
}
@Override
public int hashCode() {
return element.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof IndexedElement))
return false;
IndexedElement<?> other = (IndexedElement<?>) obj;
return other.index == index && element.equals(other.element);
}
}
}