Bug 2366 - Effective statments impl merge, retest & bugfix
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / StatementContextBase.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.base.Preconditions;
11 import com.google.common.base.Throwables;
12 import com.google.common.collect.HashMultimap;
13 import com.google.common.collect.Multimap;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.EventListener;
18 import java.util.Iterator;
19 import java.util.LinkedHashMap;
20 import java.util.Map;
21 import javax.annotation.Nonnull;
22 import org.opendaylight.yangtools.concepts.Identifiable;
23 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
27 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
36 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
37 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
38 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
39
40 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
41         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
42
43     /**
44      * event listener when an item is added to model namespace
45      */
46     interface OnNamespaceItemAdded extends EventListener {
47
48         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value)
49                 throws SourceException;
50
51     }
52
53     /**
54      * event listener when a parsing {@link ModelProcessingPhase} is completed
55      */
56     interface OnPhaseFinished extends EventListener {
57
58         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase) throws SourceException;
59
60     }
61
62     /**
63      * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
64      */
65     interface ContextMutation {
66
67         boolean isFinished();
68
69     }
70
71     private final StatementDefinitionContext<A, D, E> definition;
72     private final StatementIdentifier identifier;
73     private final StatementSourceReference statementDeclSource;
74
75     private Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>();
76
77     private Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>();
78     private Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>();
79     private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>();
80
81     public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
82         return effectOfStatement;
83     }
84
85     public void addAsEffectOfStatement(StatementContextBase<?, ?, ?> ctx) {
86         effectOfStatement.add(ctx);
87     }
88
89     private ModelProcessingPhase completedPhase;
90
91     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = HashMultimap.create();
92     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = HashMultimap.create();
93
94     private D declaredInstance;
95     private E effectiveInstance;
96
97     private StatementContextBase<?, ?, ?> originalCtx;
98     private TypeOfCopy typeOfCopy = TypeOfCopy.ORIGINAL;
99
100     private boolean isSupportedToBuildEffective = true;
101
102     @Override
103     public boolean isSupportedToBuildEffective() {
104         return isSupportedToBuildEffective;
105     }
106
107     @Override
108     public void setIsSupportedToBuildEffective(boolean isSupportedToBuildEffective) {
109         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
110     }
111
112     @Override
113     public TypeOfCopy getTypeOfCopy() {
114         return typeOfCopy;
115     }
116
117     @Override
118     public void setTypeOfCopy(TypeOfCopy typeOfCopy) {
119         this.typeOfCopy = typeOfCopy;
120     }
121
122     @Override
123     public StatementContextBase<?, ?, ?> getOriginalCtx() {
124         return originalCtx;
125     }
126
127     @Override
128     public void setOriginalCtx(StatementContextBase<?, ?, ?> originalCtx) {
129         this.originalCtx = originalCtx;
130     }
131
132     @Override
133     public ModelProcessingPhase getCompletedPhase() {
134         return completedPhase;
135     }
136
137     @Override
138     public void setCompletedPhase(ModelProcessingPhase completedPhase) {
139         this.completedPhase = completedPhase;
140     }
141
142     StatementContextBase(@Nonnull ContextBuilder<A, D, E> builder) throws SourceException {
143         this.definition = builder.getDefinition();
144         this.identifier = builder.createIdentifier();
145         this.statementDeclSource = builder.getStamementSource();
146         this.completedPhase = null;
147     }
148
149     StatementContextBase(StatementContextBase<A, D, E> original) {
150         this.definition = Preconditions
151                 .checkNotNull(original.definition, "Statement context definition cannot be null");
152         this.identifier = Preconditions
153                 .checkNotNull(original.identifier, "Statement context identifier cannot be null");
154         this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
155                 "Statement context statementDeclSource cannot be null");
156         this.completedPhase = null;
157     }
158
159     /**
160      * @return context of parent of statement
161      */
162     @Override
163     public abstract StatementContextBase<?, ?, ?> getParentContext();
164
165     /**
166      * @return root context of statement
167      */
168     @Override
169     public abstract RootStatementContext<?, ?, ?> getRoot();
170
171     /**
172      * @return statement identifier
173      */
174     @Override
175     public StatementIdentifier getIdentifier() {
176         return identifier;
177     }
178
179     /**
180      * @return origin of statement
181      */
182     @Override
183     public StatementSource getStatementSource() {
184         return statementDeclSource.getStatementSource();
185     }
186
187     /**
188      * @return reference of statement source
189      */
190     @Override
191     public StatementSourceReference getStatementSourceReference() {
192         return statementDeclSource;
193     }
194
195     /**
196      * @return raw statement argument string
197      */
198     @Override
199     public String rawStatementArgument() {
200         return identifier.getArgument();
201     }
202
203     /**
204      * @return collection of declared substatements
205      */
206     @Override
207     public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
208         return Collections.unmodifiableCollection(declared);
209     }
210
211     /**
212      * @return collection of effective substatements
213      */
214     @Override
215     public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
216         return Collections.unmodifiableCollection(effective);
217     }
218
219     public void removeStatementsFromEffectiveSubstatements(Collection<StatementContextBase<?, ?, ?>> substatements) {
220         effective.removeAll(substatements);
221     }
222
223     public void removeStatementFromEffectiveSubstatements(StatementDefinition refineSubstatementDef) {
224         Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
225         while (iterator.hasNext()) {
226             StatementContextBase<?, ?, ?> next = iterator.next();
227             if (next.getPublicDefinition().equals(refineSubstatementDef)) {
228                 iterator.remove();
229             }
230         }
231     }
232
233     /**
234      * adds effective statement to collection of substatements
235      *
236      * @throws IllegalStateException
237      *             if added in declared phase
238      * @throws NullPointerException
239      *             if statement parameter is null
240      */
241     public void addEffectiveSubstatement(StatementContextBase<?, ?, ?> substatement) {
242
243         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
244         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
245                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
246                 "Effective statement cannot be added in declared phase");
247
248         effective.add(Preconditions.checkNotNull(substatement,
249                 "StatementContextBase effective substatement cannot be null"));
250     }
251
252     /**
253      * adds declared statement to collection of substatements
254      *
255      * @throws IllegalStateException
256      *             if added in effective phase
257      * @throws NullPointerException
258      *             if statement parameter is null
259      */
260     public void addDeclaredSubstatement(StatementContextBase<?, ?, ?> substatement) {
261
262         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
263         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
264                 "Declared statement cannot be added in effective phase");
265
266         declared.add(Preconditions.checkNotNull(substatement,
267                 "StatementContextBase declared substatement cannot be null"));
268     }
269
270     /**
271      * builds new substatement from statement definition context and statement source reference
272      */
273     @SuppressWarnings({ "rawtypes", "unchecked" })
274     public ContextBuilder<?, ?, ?> substatementBuilder(StatementDefinitionContext<?, ?, ?> def,
275             StatementSourceReference ref) {
276         return new ContextBuilder(def, ref) {
277
278             @Override
279             public StatementContextBase build() throws SourceException {
280                 StatementContextBase<?, ?, ?> potential = null;
281
282                 if (getDefinition().getPublicView() != Rfc6020Mapping.AUGMENT) {
283                     potential = substatements.get(createIdentifier());
284                 }
285                 if (potential == null) {
286                     potential = new SubstatementContext(StatementContextBase.this, this);
287                     substatements.put(createIdentifier(), potential);
288                 }
289                 potential.resetLists();
290                 switch (this.getStamementSource().getStatementSource()) {
291                 case DECLARATION:
292                     addDeclaredSubstatement(potential);
293                     break;
294                 case CONTEXT:
295                     addEffectiveSubstatement(potential);
296                     break;
297                 }
298                 return potential;
299             }
300         };
301     }
302
303     /**
304      * @return local namespace behaviour type {@link NamespaceBehaviour}
305      */
306     @Override
307     public StorageNodeType getStorageNodeType() {
308         return StorageNodeType.STATEMENT_LOCAL;
309     }
310
311     /**
312      * builds {@link DeclaredStatement} for statement context
313      */
314     @Override
315     public D buildDeclared() {
316         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
317                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
318         if (declaredInstance == null) {
319             declaredInstance = definition().getFactory().createDeclared(this);
320         }
321         return declaredInstance;
322     }
323
324     /**
325      * builds {@link EffectiveStatement} for statement context
326      */
327     @Override
328     public E buildEffective() {
329         if (effectiveInstance == null) {
330             effectiveInstance = definition().getFactory().createEffective(this);
331         }
332         return effectiveInstance;
333     }
334
335     /**
336      * clears collection of declared substatements
337      *
338      * @throws IllegalStateException
339      *             if invoked in effective build phase
340      */
341     void resetLists() {
342
343         final SourceSpecificContext sourceContext = getRoot().getSourceContext();
344         Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
345                 "Declared statements list cannot be cleared in effective phase");
346
347         declared.clear();
348     }
349
350     /**
351      * tries to execute current {@link ModelProcessingPhase} of source parsing
352      *
353      * @param phase
354      *            to be executed (completed)
355      * @return if phase was successfully completed
356      * @throws SourceException
357      *             when an error occured in source parsing
358      */
359     boolean tryToCompletePhase(ModelProcessingPhase phase) throws SourceException {
360         Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
361         boolean finished = true;
362         while (openMutations.hasNext()) {
363             ContextMutation current = openMutations.next();
364             if (current.isFinished()) {
365                 openMutations.remove();
366             } else {
367                 finished = false;
368             }
369         }
370         for (StatementContextBase<?, ?, ?> child : declared) {
371             finished &= child.tryToCompletePhase(phase);
372         }
373         for (StatementContextBase<?, ?, ?> child : effective) {
374             finished &= child.tryToCompletePhase(phase);
375         }
376
377         if (finished) {
378             onPhaseCompleted(phase);
379             return true;
380         }
381         return false;
382     }
383
384     /**
385      * occurs on end of {@link ModelProcessingPhase} of source parsing
386      *
387      * @param phase
388      *            that was to be completed (finished)
389      * @throws SourceException
390      *             when an error occured in source parsing
391      */
392     private void onPhaseCompleted(ModelProcessingPhase phase) throws SourceException {
393         completedPhase = phase;
394         Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
395         while (listener.hasNext()) {
396             OnPhaseFinished next = listener.next();
397             if (next.phaseFinished(this, phase)) {
398                 listener.remove();
399             }
400         }
401     }
402
403     /**
404      * Ends declared section of current node.
405      *
406      * @param ref
407      * @throws SourceException
408      */
409     void endDeclared(StatementSourceReference ref, ModelProcessingPhase phase) throws SourceException {
410         definition().onDeclarationFinished(this, phase);
411     }
412
413     /**
414      * @return statement definition
415      */
416     protected final StatementDefinitionContext<A, D, E> definition() {
417         return definition;
418     }
419
420     @Override
421     protected void checkLocalNamespaceAllowed(Class<? extends IdentifierNamespace<?, ?>> type) {
422         definition().checkNamespaceAllowed(type);
423     }
424
425     /**
426      * occurs when an item is added to model namespace
427      *
428      * @throws SourceException
429      */
430     @Override
431     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(Class<N> type, K key, V value) {
432         // definition().onNamespaceElementAdded(this, type, key, value);
433     }
434
435     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, K key,
436             final OnNamespaceItemAdded listener) throws SourceException {
437         Object potential = getFromNamespace(type, key);
438         if (potential != null) {
439             listener.namespaceItemAdded(this, type, key, potential);
440             return;
441         }
442         NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
443         if (behaviour instanceof NamespaceBehaviourWithListeners) {
444             NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
445             casted.addValueListener(key, new ValueAddedListener(this) {
446                 @Override
447                 void onValueAdded(Object key, Object value) {
448                     try {
449                         listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
450                     } catch (SourceException e) {
451                         throw Throwables.propagate(e);
452                     }
453                 }
454             });
455         }
456     }
457
458     /**
459      * @see StatementSupport#getPublicView()
460      */
461     @Override
462     public StatementDefinition getPublicDefinition() {
463         return definition().getPublicView();
464     }
465
466     /**
467      * @return new {@link ModelActionBuilder} for the phase
468      */
469     @Override
470     public ModelActionBuilder newInferenceAction(ModelProcessingPhase phase) {
471         return getRoot().getSourceContext().newInferenceAction(phase);
472     }
473
474     /**
475      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
476      *
477      * @throws SourceException
478      */
479     void addPhaseCompletedListener(ModelProcessingPhase phase, OnPhaseFinished listener) throws SourceException {
480
481         Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null");
482         Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null");
483
484         ModelProcessingPhase finishedPhase = completedPhase;
485         while (finishedPhase != null) {
486             if (phase.equals(finishedPhase)) {
487                 listener.phaseFinished(this, finishedPhase);
488                 return;
489             }
490             finishedPhase = finishedPhase.getPreviousPhase();
491         }
492         phaseListeners.put(phase, listener);
493     }
494
495     /**
496      * adds {@link ContextMutation} to {@link ModelProcessingPhase}
497      *
498      * @throws IllegalStateException
499      *             when the mutation was registered after phase was completed
500      */
501     void addMutation(ModelProcessingPhase phase, ContextMutation mutation) {
502         ModelProcessingPhase finishedPhase = completedPhase;
503         while (finishedPhase != null) {
504             if (phase.equals(finishedPhase)) {
505                 throw new IllegalStateException("Mutation registered after phase was completed.");
506             }
507             finishedPhase = finishedPhase.getPreviousPhase();
508         }
509         phaseMutation.put(phase, mutation);
510     }
511
512     /**
513      * adds statement to namespace map with the key
514      *
515      * @param namespace
516      *            {@link StatementNamespace} child that determines namespace to be added to
517      * @param key
518      *            of type according to namespace class specification
519      * @param stmt
520      *            to be added to namespace map
521      */
522     @Override
523     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(Class<N> namespace, KT key,
524             StmtContext<?, ?, ?> stmt) {
525         addContextToNamespace(namespace, (K) key, stmt);
526     }
527 }