Bug 2366 - Effective statments impl merge, retest & bugfix
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / NamespaceBehaviourWithListeners.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
9
10 import com.google.common.collect.HashMultimap;
11 import com.google.common.collect.Multimap;
12 import java.util.Iterator;
13 import java.util.Map;
14
15 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
16 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
17
18 final class NamespaceBehaviourWithListeners<K,V, N extends IdentifierNamespace<K, V>> extends NamespaceBehaviour<K, V, N> {
19
20     static abstract class ValueAddedListener {
21
22         private org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode ctxNode;
23
24         public ValueAddedListener(NamespaceStorageNode contextNode) {
25             this.ctxNode = contextNode;
26         }
27
28         abstract void onValueAdded(Object key, Object value);
29
30     }
31
32     private final NamespaceBehaviour<K, V, N> delegate;
33     private final Multimap<K, ValueAddedListener> listeners = HashMultimap.create();
34
35     protected NamespaceBehaviourWithListeners(NamespaceBehaviour<K, V, N> delegate) {
36         super(delegate.getIdentifier());
37         this.delegate = delegate;
38     }
39
40     @Override
41     public void addTo(NamespaceBehaviour.NamespaceStorageNode storage,
42             K key, V value) {
43         delegate.addTo(storage, key, value);
44
45         Iterator<ValueAddedListener> keyListeners = listeners.get(key).iterator();
46         while(keyListeners.hasNext()) {
47             ValueAddedListener listener = keyListeners.next();
48             if(listener.ctxNode == storage || hasIdentiticalValue(listener.ctxNode,key,value)) {
49                 keyListeners.remove();
50                 listener.onValueAdded(key, value);
51             }
52         }
53     }
54
55     private boolean hasIdentiticalValue(NamespaceBehaviour.NamespaceStorageNode ctxNode, K key, V value) {
56         return getFrom(ctxNode, key) == value;
57     }
58
59     void addValueListener(K key, ValueAddedListener listener) {
60         listeners.put(key, listener);
61     }
62
63     @Override
64     public V getFrom(NamespaceBehaviour.NamespaceStorageNode storage,
65             K key) {
66         return delegate.getFrom(storage, key);
67     }
68
69     @Override
70     public Map<K, V> getAllFrom(final NamespaceStorageNode storage) {
71         return delegate.getAllFrom(storage);
72     }
73 }