BUG-6972: Add OptionaBoolean utility
[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.MoreObjects;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableCollection;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMultimap;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Multimaps;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.EnumMap;
22 import java.util.EventListener;
23 import java.util.Iterator;
24 import java.util.Optional;
25 import java.util.Set;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.yangtools.util.OptionalBoolean;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
32 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
33 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
44 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
52         extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E> {
53     /**
54      * event listener when an item is added to model namespace.
55      */
56     interface OnNamespaceItemAdded extends EventListener {
57         /**
58          * @throws SourceException
59          */
60         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
61     }
62
63     /**
64      * event listener when a parsing {@link ModelProcessingPhase} is completed.
65      */
66     interface OnPhaseFinished extends EventListener {
67         /**
68          * @throws SourceException
69          */
70         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
71     }
72
73     /**
74      * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
75      */
76     interface ContextMutation {
77
78         boolean isFinished();
79     }
80
81     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
82
83     private final StatementDefinitionContext<A, D, E> definition;
84     private final StatementSourceReference statementDeclSource;
85     private final StmtContext<?, ?, ?> originalCtx;
86     private final CopyHistory copyHistory;
87     private final String rawArgument;
88
89     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
90     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
91     private Collection<Mutable<?, ?, ?>> effective = ImmutableList.of();
92     private Collection<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
93     private StatementMap substatements = StatementMap.empty();
94
95     private boolean isSupportedToBuildEffective = true;
96     private ModelProcessingPhase completedPhase = null;
97     private D declaredInstance;
98     private E effectiveInstance;
99     private int order = 0;
100
101     // BooleanFields value
102     private byte supportedByFeatures;
103
104     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
105             final String rawArgument) {
106         this.definition = Preconditions.checkNotNull(def);
107         this.statementDeclSource = Preconditions.checkNotNull(ref);
108         this.rawArgument = def.internArgument(rawArgument);
109         this.copyHistory = CopyHistory.original();
110         this.originalCtx = null;
111     }
112
113     StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
114         this.definition = Preconditions.checkNotNull(original.definition,
115                 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
116         this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
117                 "Statement context statementDeclSource cannot be null copying from: %s",
118                 original.getStatementSourceReference());
119         this.rawArgument = original.rawArgument;
120         this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
121         this.originalCtx = original.getOriginalCtx().orElse(original);
122     }
123
124     @Override
125     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
126         return effectOfStatement;
127     }
128
129     @Override
130     public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
131         if (effectOfStatement.isEmpty()) {
132             effectOfStatement = new ArrayList<>(1);
133         }
134         effectOfStatement.add(ctx);
135     }
136
137     @Override
138     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
139         if (ctxs.isEmpty()) {
140             return;
141         }
142
143         if (effectOfStatement.isEmpty()) {
144             effectOfStatement = new ArrayList<>(ctxs.size());
145         }
146         effectOfStatement.addAll(ctxs);
147     }
148
149     @Override
150     public boolean isSupportedByFeatures() {
151         if (OptionalBoolean.isPresent(supportedByFeatures)) {
152             return OptionalBoolean.get(supportedByFeatures);
153         }
154
155         // If the set of supported features has not been provided, all features are supported by default.
156         final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
157             SupportedFeatures.SUPPORTED_FEATURES);
158         final boolean ret = supportedFeatures == null ? true
159             : StmtContextUtils.checkFeatureSupport(this, supportedFeatures);
160
161         supportedByFeatures = OptionalBoolean.of(ret);
162         return ret;
163
164     }
165
166     @Override
167     public boolean isSupportedToBuildEffective() {
168         return isSupportedToBuildEffective;
169     }
170
171     @Override
172     public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
173         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
174     }
175
176     @Override
177     public CopyHistory getCopyHistory() {
178         return copyHistory;
179     }
180
181     @Override
182     public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
183         return Optional.ofNullable(originalCtx);
184     }
185
186     @Override
187     public void setOrder(final int order) {
188         this.order = order;
189     }
190
191     @Override
192     public int getOrder() {
193         return order;
194     }
195
196     @Override
197     public ModelProcessingPhase getCompletedPhase() {
198         return completedPhase;
199     }
200
201     @Override
202     public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
203         this.completedPhase = completedPhase;
204     }
205
206     @Override
207     public abstract StatementContextBase<?, ?, ?> getParentContext();
208
209     /**
210      * @return root context of statement
211      */
212     @Nonnull
213     @Override
214     public abstract RootStatementContext<?, ?, ?> getRoot();
215
216     /**
217      * @return origin of statement
218      */
219     @Nonnull
220     @Override
221     public StatementSource getStatementSource() {
222         return statementDeclSource.getStatementSource();
223     }
224
225     /**
226      * @return reference of statement source
227      */
228     @Nonnull
229     @Override
230     public StatementSourceReference getStatementSourceReference() {
231         return statementDeclSource;
232     }
233
234     @Override
235     public final String rawStatementArgument() {
236         return rawArgument;
237     }
238
239     @Nonnull
240     @Override
241     public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
242         return substatements.values();
243     }
244
245     @Nonnull
246     @Override
247     public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
248         return substatements.values();
249     }
250
251     @Override
252     public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
253         return mutableEffectiveSubstatements();
254     }
255
256     @Nonnull
257     @Override
258     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
259         if (effective instanceof ImmutableCollection) {
260             return effective;
261         }
262
263         return Collections.unmodifiableCollection(effective);
264     }
265
266     public void removeStatementsFromEffectiveSubstatements(final Collection<? extends StmtContext<?, ?, ?>> substatements) {
267         if (!effective.isEmpty()) {
268             effective.removeAll(substatements);
269             shrinkEffective();
270         }
271     }
272
273     private void shrinkEffective() {
274         if (effective.isEmpty()) {
275             effective = ImmutableList.of();
276         }
277     }
278
279     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
280         if (effective.isEmpty()) {
281             return;
282         }
283
284         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
285         while (iterator.hasNext()) {
286             final StmtContext<?, ?, ?> next = iterator.next();
287             if (statementDef.equals(next.getPublicDefinition())) {
288                 iterator.remove();
289             }
290         }
291
292         shrinkEffective();
293     }
294
295     /**
296      * Removes a statement context from the effective substatements
297      * based on its statement definition (i.e statement keyword) and raw (in String form) statement argument.
298      * The statement context is removed only if both statement definition and statement argument match with
299      * one of the effective substatements' statement definition and argument.
300      *
301      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
302      *
303      * @param statementDef statement definition of the statement context to remove
304      * @param statementArg statement argument of the statement context to remove
305      */
306     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
307             final String statementArg) {
308         if (statementArg == null) {
309             removeStatementFromEffectiveSubstatements(statementDef);
310         }
311
312         if (effective.isEmpty()) {
313             return;
314         }
315
316         final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
317         while (iterator.hasNext()) {
318             final Mutable<?, ?, ?> next = iterator.next();
319             if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
320                 iterator.remove();
321             }
322         }
323
324         shrinkEffective();
325     }
326
327     /**
328      * adds effective statement to collection of substatements
329      *
330      * @param substatement substatement
331      * @throws IllegalStateException
332      *             if added in declared phase
333      * @throws NullPointerException
334      *             if statement parameter is null
335      */
336     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
337         beforeAddEffectiveStatement(1);
338         effective.add(substatement);
339     }
340
341     /**
342      * adds effective statement to collection of substatements
343      *
344      * @param substatements substatements
345      * @throws IllegalStateException
346      *             if added in declared phase
347      * @throws NullPointerException
348      *             if statement parameter is null
349      */
350     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> substatements) {
351         if (substatements.isEmpty()) {
352             return;
353         }
354
355         substatements.forEach(Preconditions::checkNotNull);
356         beforeAddEffectiveStatement(substatements.size());
357         effective.addAll(substatements);
358     }
359
360     private void beforeAddEffectiveStatement(final int toAdd) {
361         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
362         Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
363                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
364                 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
365
366         if (effective.isEmpty()) {
367             effective = new ArrayList<>(toAdd);
368         }
369     }
370
371     /**
372      * Create a new substatement at the specified offset.
373      *
374      * @param offset Substatement offset
375      * @param def definition context
376      * @param ref source reference
377      * @param argument statement argument
378      * @return A new substatement
379      */
380     public final <CA, CD extends DeclaredStatement<CA>, CE extends EffectiveStatement<CA, CD>> StatementContextBase<CA, CD, CE> createSubstatement(
381             final int offset, final StatementDefinitionContext<CA, CD, CE> def, final StatementSourceReference ref,
382             final String argument) {
383         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
384         Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
385                 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
386
387         final Optional<StatementContextBase<?, ?, ?>> implicitStatement = definition.beforeSubStatementCreated(this,
388             offset, def, ref, argument);
389         if (implicitStatement.isPresent()) {
390             return implicitStatement.get().createSubstatement(offset, def, ref, argument);
391         }
392
393         final StatementContextBase<CA, CD, CE> ret = new SubstatementContext<>(this, def, ref, argument);
394         substatements = substatements.put(offset, ret);
395         def.onStatementAdded(ret);
396         return ret;
397     }
398
399     /**
400      * Lookup substatement by its offset in this statement.
401      *
402      * @param offset Substatement offset
403      * @return Substatement, or null if substatement does not exist.
404      */
405     final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
406         return substatements.get(offset);
407     }
408
409     @Override
410     public D buildDeclared() {
411         Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
412                 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
413         if (declaredInstance == null) {
414             declaredInstance = definition().getFactory().createDeclared(this);
415         }
416         return declaredInstance;
417     }
418
419     @Override
420     public E buildEffective() {
421         if (effectiveInstance == null) {
422             effectiveInstance = definition().getFactory().createEffective(this);
423         }
424         return effectiveInstance;
425     }
426
427     /**
428      * tries to execute current {@link ModelProcessingPhase} of source parsing.
429      *
430      * @param phase
431      *            to be executed (completed)
432      * @return if phase was successfully completed
433      * @throws SourceException
434      *             when an error occured in source parsing
435      */
436     boolean tryToCompletePhase(final ModelProcessingPhase phase) {
437
438         boolean finished = true;
439         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
440         if (!openMutations.isEmpty()) {
441             final Iterator<ContextMutation> it = openMutations.iterator();
442             while (it.hasNext()) {
443                 final ContextMutation current = it.next();
444                 if (current.isFinished()) {
445                     it.remove();
446                 } else {
447                     finished = false;
448                 }
449             }
450
451             if (openMutations.isEmpty()) {
452                 phaseMutation.removeAll(phase);
453                 if (phaseMutation.isEmpty()) {
454                     phaseMutation = ImmutableMultimap.of();
455                 }
456             }
457         }
458
459         for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
460             finished &= child.tryToCompletePhase(phase);
461         }
462         for (final Mutable<?, ?, ?> child : effective) {
463             if (child instanceof StatementContextBase) {
464                 finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
465             }
466         }
467
468         if (finished) {
469             onPhaseCompleted(phase);
470             return true;
471         }
472         return false;
473     }
474
475     /**
476      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
477      *
478      * @param phase
479      *            that was to be completed (finished)
480      * @throws SourceException
481      *             when an error occurred in source parsing
482      */
483     private void onPhaseCompleted(final ModelProcessingPhase phase) {
484         completedPhase = phase;
485
486         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
487         if (listeners.isEmpty()) {
488             return;
489         }
490
491         final Iterator<OnPhaseFinished> listener = listeners.iterator();
492         while (listener.hasNext()) {
493             final OnPhaseFinished next = listener.next();
494             if (next.phaseFinished(this, phase)) {
495                 listener.remove();
496             }
497         }
498
499         if (listeners.isEmpty()) {
500             phaseListeners.removeAll(phase);
501             if (phaseListeners.isEmpty()) {
502                 phaseListeners = ImmutableMultimap.of();
503             }
504         }
505     }
506
507     /**
508      * Ends declared section of current node.
509      *
510      * @param ref
511      * @throws SourceException
512      */
513     void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
514         definition().onDeclarationFinished(this, phase);
515     }
516
517     /**
518      * @return statement definition
519      */
520     protected final StatementDefinitionContext<A, D, E> definition() {
521         return definition;
522     }
523
524     @Override
525     protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
526         definition().checkNamespaceAllowed(type);
527     }
528
529     @Override
530     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
531             final V value) {
532         // definition().onNamespaceElementAdded(this, type, key, value);
533     }
534
535     <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
536             final OnNamespaceItemAdded listener) throws SourceException {
537         final Object potential = getFromNamespace(type, key);
538         if (potential != null) {
539             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
540             listener.namespaceItemAdded(this, type, key, potential);
541             return;
542         }
543
544         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
545         Preconditions.checkArgument(behaviour instanceof NamespaceBehaviourWithListeners,
546             "Namespace {} does not support listeners", type);
547
548         final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
549         casted.addValueListener(new ValueAddedListener<K>(this, key) {
550             @Override
551             void onValueAdded(final Object key, final Object value) {
552                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
553             }
554         });
555     }
556
557     /**
558      * See {@link StatementSupport#getPublicView()}.
559      */
560     @Nonnull
561     @Override
562     public StatementDefinition getPublicDefinition() {
563         return definition().getPublicView();
564     }
565
566     @Override
567     public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
568         return getRoot().getSourceContext().newInferenceAction(phase);
569     }
570
571     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
572         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
573     }
574
575     /**
576      * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
577      *
578      * @throws SourceException
579      */
580     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
581
582         Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
583                 getStatementSourceReference());
584         Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
585                 getStatementSourceReference());
586
587         ModelProcessingPhase finishedPhase = completedPhase;
588         while (finishedPhase != null) {
589             if (phase.equals(finishedPhase)) {
590                 listener.phaseFinished(this, finishedPhase);
591                 return;
592             }
593             finishedPhase = finishedPhase.getPreviousPhase();
594         }
595         if (phaseListeners.isEmpty()) {
596             phaseListeners = newMultimap();
597         }
598
599         phaseListeners.put(phase, listener);
600     }
601
602     /**
603      * adds {@link ContextMutation} to {@link ModelProcessingPhase}
604      *
605      * @throws IllegalStateException
606      *             when the mutation was registered after phase was completed
607      */
608     void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
609         ModelProcessingPhase finishedPhase = completedPhase;
610         while (finishedPhase != null) {
611             if (phase.equals(finishedPhase)) {
612                 throw new IllegalStateException("Mutation registered after phase was completed at: "  +
613                         getStatementSourceReference());
614             }
615             finishedPhase = finishedPhase.getPreviousPhase();
616         }
617
618         if (phaseMutation.isEmpty()) {
619             phaseMutation = newMultimap();
620         }
621         phaseMutation.put(phase, mutation);
622     }
623
624     @Override
625     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
626             final KT key,final StmtContext<?, ?, ?> stmt) {
627         addContextToNamespace(namespace, key, stmt);
628     }
629
630     @Override
631     public final String toString() {
632         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
633     }
634
635     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
636         return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
637     }
638 }