2a99e6e143c4cc9f5ee0368e8bf456dac0a006cc
[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 org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
14 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
15
16 final class NamespaceBehaviourWithListeners<K,V, N extends IdentifierNamespace<K, V>> extends NamespaceBehaviour<K, V, N> {
17
18     static abstract class ValueAddedListener {
19
20         private org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode ctxNode;
21
22         public ValueAddedListener(NamespaceStorageNode contextNode) {
23             this.ctxNode = contextNode;
24         }
25
26         abstract void onValueAdded(Object key, Object value);
27
28     }
29
30     private final NamespaceBehaviour<K, V, N> delegate;
31     private final Multimap<K, ValueAddedListener> listeners = HashMultimap.create();
32
33     protected NamespaceBehaviourWithListeners(NamespaceBehaviour<K, V, N> delegate) {
34         super(delegate.getIdentifier());
35         this.delegate = delegate;
36     }
37
38     @Override
39     public void addTo(NamespaceBehaviour.NamespaceStorageNode storage,
40             K key, V value) {
41         delegate.addTo(storage, key, value);
42
43         Iterator<ValueAddedListener> keyListeners = listeners.get(key).iterator();
44         while(keyListeners.hasNext()) {
45             ValueAddedListener listener = keyListeners.next();
46             if(listener.ctxNode == storage || hasIdentiticalValue(listener.ctxNode,key,value)) {
47                 keyListeners.remove();
48                 listener.onValueAdded(key, value);
49             }
50         }
51     }
52
53     private boolean hasIdentiticalValue(NamespaceBehaviour.NamespaceStorageNode ctxNode, K key, V value) {
54         return getFrom(ctxNode, key) == value;
55     }
56
57     void addValueListener(K key, ValueAddedListener listener) {
58         listeners.put(key, listener);
59     }
60
61     @Override
62     public V getFrom(NamespaceBehaviour.NamespaceStorageNode storage,
63             K key) {
64         return delegate.getFrom(storage, key);
65     }
66 }