2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
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.base.Throwables;
14 import com.google.common.collect.ImmutableCollection;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableMultimap;
18 import com.google.common.collect.Multimap;
19 import com.google.common.collect.Multimaps;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.EnumMap;
24 import java.util.EventListener;
25 import java.util.Iterator;
26 import java.util.LinkedHashMap;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.yangtools.concepts.Identifiable;
30 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
31 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
32 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
34 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
35 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
46 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
49 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
50 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
53 * event listener when an item is added to model namespace
55 interface OnNamespaceItemAdded extends EventListener {
57 * @throws SourceException
59 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
63 * event listener when a parsing {@link ModelProcessingPhase} is completed
65 interface OnPhaseFinished extends EventListener {
67 * @throws SourceException
69 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
73 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
75 interface ContextMutation {
80 private final StatementDefinitionContext<A, D, E> definition;
81 private final StatementIdentifier identifier;
82 private final StatementSourceReference statementDeclSource;
84 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
85 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
86 private Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = ImmutableMap.of();
87 private Collection<StatementContextBase<?, ?, ?>> declared = ImmutableList.of();
88 private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
89 private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
91 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
92 private CopyHistory copyHistory = CopyHistory.original();
93 private boolean isSupportedToBuildEffective = true;
94 private ModelProcessingPhase completedPhase = null;
95 private StatementContextBase<?, ?, ?> originalCtx;
96 private D declaredInstance;
97 private E effectiveInstance;
98 private int order = 0;
100 StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) {
101 this.definition = builder.getDefinition();
102 this.identifier = builder.createIdentifier();
103 this.statementDeclSource = builder.getStamementSource();
106 StatementContextBase(final StatementContextBase<A, D, E> original) {
107 this.definition = Preconditions.checkNotNull(original.definition,
108 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
109 this.identifier = Preconditions.checkNotNull(original.identifier,
110 "Statement context identifier cannot be null copying from: %s", original.getStatementSourceReference());
111 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
112 "Statement context statementDeclSource cannot be null copying from: %s",
113 original.getStatementSourceReference());
117 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
118 return effectOfStatement;
122 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
123 if (effectOfStatement.isEmpty()) {
124 effectOfStatement = new ArrayList<>(1);
126 effectOfStatement.add(ctx);
130 public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
131 if (effectOfStatement.isEmpty()) {
132 effectOfStatement = new ArrayList<>(ctxs.size());
134 effectOfStatement.addAll(ctxs);
138 public SupportedByFeatures getSupportedByFeatures() {
139 return supportedByFeatures;
143 public void setSupportedByFeatures(final boolean isSupported) {
144 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
148 public boolean isSupportedToBuildEffective() {
149 return isSupportedToBuildEffective;
153 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
154 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
158 public CopyHistory getCopyHistory() {
163 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
164 copyHistory = copyHistory.append(typeOfCopy, toAppend);
168 public StatementContextBase<?, ?, ?> getOriginalCtx() {
173 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
174 this.originalCtx = originalCtx;
178 public void setOrder(final int order) {
183 public int getOrder() {
188 public ModelProcessingPhase getCompletedPhase() {
189 return completedPhase;
193 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
194 this.completedPhase = completedPhase;
198 * @return context of parent of statement
201 public abstract StatementContextBase<?, ?, ?> getParentContext();
204 * @return root context of statement
207 public abstract RootStatementContext<?, ?, ?> getRoot();
210 * @return statement identifier
213 public StatementIdentifier getIdentifier() {
218 * @return origin of statement
221 public StatementSource getStatementSource() {
222 return statementDeclSource.getStatementSource();
226 * @return reference of statement source
229 public StatementSourceReference getStatementSourceReference() {
230 return statementDeclSource;
234 * @return raw statement argument string
237 public String rawStatementArgument() {
238 return identifier.getArgument();
241 private static final <T> Collection<T> maybeWrap(final Collection<T> input) {
242 if (input instanceof ImmutableCollection) {
246 return Collections.unmodifiableCollection(input);
250 * @return collection of declared substatements
253 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
254 return maybeWrap(declared);
258 * @return collection of substatements
261 public Collection<StatementContextBase<?, ?, ?>> substatements() {
262 return maybeWrap(substatements.values());
266 * @return collection of effective substatements
269 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
270 return maybeWrap(effective);
273 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
274 if (!effective.isEmpty()) {
275 effective.removeAll(substatements);
280 private void shrinkEffective() {
281 if (effective.isEmpty()) {
282 effective = ImmutableList.of();
286 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
287 if (effective.isEmpty()) {
291 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
292 while (iterator.hasNext()) {
293 final StatementContextBase<?, ?, ?> next = iterator.next();
294 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
303 * adds effective statement to collection of substatements
305 * @param substatement substatement
306 * @throws IllegalStateException
307 * if added in declared phase
308 * @throws NullPointerException
309 * if statement parameter is null
311 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
312 Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
313 getStatementSourceReference());
314 beforeAddEffectiveStatement(1);
315 effective.add(substatement);
319 * adds effective statement to collection of substatements
321 * @param substatements substatements
322 * @throws IllegalStateException
323 * if added in declared phase
324 * @throws NullPointerException
325 * if statement parameter is null
327 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
328 substatements.forEach(Preconditions::checkNotNull);
329 beforeAddEffectiveStatement(substatements.size());
330 effective.addAll(substatements);
333 private void beforeAddEffectiveStatement(final int toAdd) {
334 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
335 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
336 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
337 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
339 if (effective.isEmpty()) {
340 effective = new ArrayList<>(toAdd);
345 * adds declared statement to collection of substatements
347 * @param substatement substatement
348 * @throws IllegalStateException
349 * if added in effective phase
350 * @throws NullPointerException
351 * if statement parameter is null
353 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
355 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
356 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
357 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
359 if (declared.isEmpty()) {
360 declared = new ArrayList<>(1);
362 declared.add(Preconditions.checkNotNull(substatement,
363 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
367 * builds a new substatement from statement definition context and statement source reference
369 * @param def definition context
370 * @param ref source reference
372 * @return instance of ContextBuilder
374 @SuppressWarnings({ "rawtypes", "unchecked" })
375 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
376 final StatementSourceReference ref) {
377 return new ContextBuilder(def, ref) {
380 public StatementContextBase build() throws SourceException {
381 StatementContextBase<?, ?, ?> potential = null;
383 final StatementDefinition stmtDef = getDefinition().getPublicView();
384 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
385 && stmtDef != Rfc6020Mapping.TYPE) {
386 potential = substatements.get(createIdentifier());
388 if (potential == null) {
389 potential = new SubstatementContext(StatementContextBase.this, this);
390 if (substatements.isEmpty()) {
391 substatements = new LinkedHashMap<>(1);
393 substatements.put(createIdentifier(), potential);
394 getDefinition().onStatementAdded(potential);
396 potential.resetLists();
397 switch (this.getStamementSource().getStatementSource()) {
399 addDeclaredSubstatement(potential);
402 addEffectiveSubstatement(potential);
411 * @return local namespace behaviour type {@link NamespaceBehaviour}
414 public StorageNodeType getStorageNodeType() {
415 return StorageNodeType.STATEMENT_LOCAL;
419 * builds {@link DeclaredStatement} for statement context
422 public D buildDeclared() {
423 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
424 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
425 if (declaredInstance == null) {
426 declaredInstance = definition().getFactory().createDeclared(this);
428 return declaredInstance;
432 * builds {@link EffectiveStatement} for statement context
435 public E buildEffective() {
436 if (effectiveInstance == null) {
437 effectiveInstance = definition().getFactory().createEffective(this);
439 return effectiveInstance;
443 * clears collection of declared substatements
445 * @throws IllegalStateException
446 * if invoked in effective build phase
450 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
451 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
452 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
454 declared = ImmutableList.of();
458 * tries to execute current {@link ModelProcessingPhase} of source parsing
461 * to be executed (completed)
462 * @return if phase was successfully completed
463 * @throws SourceException
464 * when an error occured in source parsing
466 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
468 boolean finished = true;
469 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
470 if (!openMutations.isEmpty()) {
471 final Iterator<ContextMutation> it = openMutations.iterator();
472 while (it.hasNext()) {
473 final ContextMutation current = it.next();
474 if (current.isFinished()) {
481 if (openMutations.isEmpty()) {
482 phaseMutation.removeAll(phase);
483 if (phaseMutation.isEmpty()) {
484 phaseMutation = ImmutableMultimap.of();
489 for (final StatementContextBase<?, ?, ?> child : declared) {
490 finished &= child.tryToCompletePhase(phase);
492 for (final StatementContextBase<?, ?, ?> child : effective) {
493 finished &= child.tryToCompletePhase(phase);
497 onPhaseCompleted(phase);
504 * occurs on end of {@link ModelProcessingPhase} of source parsing
507 * that was to be completed (finished)
508 * @throws SourceException
509 * when an error occured in source parsing
511 private void onPhaseCompleted(final ModelProcessingPhase phase) {
512 completedPhase = phase;
514 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
515 if (listeners.isEmpty()) {
519 final Iterator<OnPhaseFinished> listener = listeners.iterator();
520 while (listener.hasNext()) {
521 final OnPhaseFinished next = listener.next();
522 if (next.phaseFinished(this, phase)) {
527 if (listeners.isEmpty()) {
528 phaseListeners.removeAll(phase);
529 if (phaseListeners.isEmpty()) {
530 phaseListeners = ImmutableMultimap.of();
536 * Ends declared section of current node.
539 * @throws SourceException
541 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
542 definition().onDeclarationFinished(this, phase);
546 * @return statement definition
548 protected final StatementDefinitionContext<A, D, E> definition() {
553 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
554 definition().checkNamespaceAllowed(type);
558 * occurs when an item is added to model namespace
560 * @throws SourceException instance of SourceException
563 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
564 // definition().onNamespaceElementAdded(this, type, key, value);
567 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
568 final OnNamespaceItemAdded listener) throws SourceException {
569 final Object potential = getFromNamespace(type, key);
570 if (potential != null) {
571 listener.namespaceItemAdded(this, type, key, potential);
574 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
575 if (behaviour instanceof NamespaceBehaviourWithListeners) {
576 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
577 casted.addValueListener(new ValueAddedListener<K>(this, key) {
579 void onValueAdded(final Object key, final Object value) {
581 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
582 } catch (final SourceException e) {
583 throw Throwables.propagate(e);
591 * @see StatementSupport#getPublicView()
594 public StatementDefinition getPublicDefinition() {
595 return definition().getPublicView();
599 * @return new {@link ModelActionBuilder} for the phase
602 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
603 return getRoot().getSourceContext().newInferenceAction(phase);
606 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
607 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
611 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
613 * @throws SourceException
615 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
617 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
618 getStatementSourceReference());
619 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
620 getStatementSourceReference());
622 ModelProcessingPhase finishedPhase = completedPhase;
623 while (finishedPhase != null) {
624 if (phase.equals(finishedPhase)) {
625 listener.phaseFinished(this, finishedPhase);
628 finishedPhase = finishedPhase.getPreviousPhase();
630 if (phaseListeners.isEmpty()) {
631 phaseListeners = newMultimap();
634 phaseListeners.put(phase, listener);
638 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
640 * @throws IllegalStateException
641 * when the mutation was registered after phase was completed
643 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
644 ModelProcessingPhase finishedPhase = completedPhase;
645 while (finishedPhase != null) {
646 if (phase.equals(finishedPhase)) {
647 throw new IllegalStateException("Mutation registered after phase was completed at: " +
648 getStatementSourceReference());
650 finishedPhase = finishedPhase.getPreviousPhase();
653 if (phaseMutation.isEmpty()) {
654 phaseMutation = newMultimap();
656 phaseMutation.put(phase, mutation);
660 * adds statement to namespace map with the key
663 * {@link StatementNamespace} child that determines namespace to be added to
665 * of type according to namespace class specification
667 * to be added to namespace map
670 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
671 final StmtContext<?, ?, ?> stmt) {
672 addContextToNamespace(namespace, (K) key, stmt);
676 public final String toString() {
677 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
680 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
681 return toStringHelper.add("definition", definition).add("id", identifier);