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