Merge branch 'master' of ../controller
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SimpleNamespaceContext.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 java.util.ArrayList;
11 import java.util.Collection;
12 import java.util.Iterator;
13 import java.util.List;
14 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
15 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
16
17 final class SimpleNamespaceContext<K, V, N extends IdentifierNamespace<K, V>>
18         extends NamespaceBehaviourWithListeners<K, V, N> {
19     // FIXME: Change this to Multimap, once issue with modules is resolved.
20     private List<KeyedValueAddedListener<K>> listeners;
21
22     private Collection<PredicateValueAddedListener<K, V>> predicateListeners;
23
24     SimpleNamespaceContext(final NamespaceBehaviour<K, V, N> delegate) {
25         super(delegate);
26     }
27
28     @Override
29     void addListener(final KeyedValueAddedListener<K> listener) {
30         if (listeners == null) {
31             listeners = new ArrayList<>();
32         }
33         listeners.add(listener);
34     }
35
36     @Override
37     void addListener(final PredicateValueAddedListener<K, V> listener) {
38         if (predicateListeners == null) {
39             predicateListeners = new ArrayList<>();
40         }
41         predicateListeners.add(listener);
42     }
43
44     @Override
45     public void addTo(final NamespaceStorageNode storage, final K key, final V value) {
46         delegate.addTo(storage, key, value);
47
48         if (listeners != null) {
49             notifyListeners(storage, listeners.iterator(), value);
50             if (listeners.isEmpty()) {
51                 listeners = null;
52             }
53         }
54
55         if (predicateListeners != null) {
56             final Iterator<PredicateValueAddedListener<K, V>> it = predicateListeners.iterator();
57             while (it.hasNext()) {
58                 if (it.next().onValueAdded(key, value)) {
59                     it.remove();
60                 }
61             }
62             if (predicateListeners.isEmpty()) {
63                 predicateListeners = null;
64             }
65         }
66
67         notifyDerivedNamespaces(storage, key, value);
68     }
69 }