TransformationSet.java
01 /*
02  * Copyright 2008-2017 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package griffon.javafx.collections.transformation;
17 
18 import griffon.javafx.collections.ObservableSetBase;
19 import javafx.collections.ObservableSet;
20 import javafx.collections.SetChangeListener;
21 import javafx.collections.WeakSetChangeListener;
22 
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import java.util.Set;
26 
27 import static java.util.Objects.requireNonNull;
28 
29 /**
30  @author Andres Almiray
31  @since 2.11.0
32  */
33 public abstract class TransformationSet<E, F> extends ObservableSetBase<E> implements ObservableSet<E> {
34     private final ObservableSet<? extends F> source;
35     private SetChangeListener<F> sourceListener;
36 
37     protected TransformationSet(@Nonnull ObservableSet<? extends F> source) {
38         this.source = requireNonNull(source, "Argument 'source' must not be null");
39         source.addListener(new WeakSetChangeListener<>(getListener()));
40     }
41 
42     @Nonnull
43     public final ObservableSet<? extends F> getSource() {
44         return source;
45     }
46 
47     public SetChangeListener<F> getListener() {
48         if (sourceListener == null) {
49             sourceListener = TransformationSet.this::sourceChanged;
50         }
51         return sourceListener;
52     }
53 
54     public final boolean isInTransformationChain(@Nullable ObservableSet<?> set) {
55         if (source == set) {
56             return true;
57         }
58         Set<?> currentSource = source;
59         while (currentSource instanceof TransformationSet) {
60             currentSource = ((TransformationSetcurrentSource).source;
61             if (currentSource == set) {
62                 return true;
63             }
64         }
65         return false;
66     }
67 
68     protected abstract void sourceChanged(SetChangeListener.Change<? extends F> c);
69 }