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