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