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.Preconditions;
11 import com.google.common.base.Throwables;
12 import com.google.common.collect.ImmutableCollection;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
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.LinkedHashMap;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.yangtools.concepts.Identifiable;
28 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
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.NamespaceBehaviour.StorageNodeType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
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.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
47 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
48 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
51 * event listener when an item is added to model namespace
53 interface OnNamespaceItemAdded extends EventListener {
55 * @throws SourceException
57 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
61 * event listener when a parsing {@link ModelProcessingPhase} is completed
63 interface OnPhaseFinished extends EventListener {
65 * @throws SourceException
67 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
71 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
73 interface ContextMutation {
78 private final StatementDefinitionContext<A, D, E> definition;
79 private final StatementIdentifier identifier;
80 private final StatementSourceReference statementDeclSource;
82 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
83 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
84 private Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = ImmutableMap.of();
85 private Collection<StatementContextBase<?, ?, ?>> declared = ImmutableList.of();
86 private Collection<StatementContextBase<?, ?, ?>> effective = ImmutableList.of();
87 private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = ImmutableList.of();
89 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
90 private CopyHistory copyHistory = CopyHistory.original();
91 private boolean isSupportedToBuildEffective = true;
92 private ModelProcessingPhase completedPhase = null;
93 private StatementContextBase<?, ?, ?> originalCtx;
94 private D declaredInstance;
95 private E effectiveInstance;
96 private int order = 0;
98 StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) {
99 this.definition = builder.getDefinition();
100 this.identifier = builder.createIdentifier();
101 this.statementDeclSource = builder.getStamementSource();
104 StatementContextBase(final StatementContextBase<A, D, E> original) {
105 this.definition = Preconditions.checkNotNull(original.definition,
106 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
107 this.identifier = Preconditions.checkNotNull(original.identifier,
108 "Statement context identifier cannot be null copying from: %s", original.getStatementSourceReference());
109 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
110 "Statement context statementDeclSource cannot be null copying from: %s",
111 original.getStatementSourceReference());
115 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
116 return effectOfStatement;
120 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
121 if (effectOfStatement.isEmpty()) {
122 effectOfStatement = new ArrayList<>(1);
124 effectOfStatement.add(ctx);
128 public void addAsEffectOfStatement(final Collection<StatementContextBase<?, ?, ?>> ctxs) {
129 if (effectOfStatement.isEmpty()) {
130 effectOfStatement = new ArrayList<>(ctxs.size());
132 effectOfStatement.addAll(ctxs);
136 public SupportedByFeatures getSupportedByFeatures() {
137 return supportedByFeatures;
141 public void setSupportedByFeatures(final boolean isSupported) {
142 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
146 public boolean isSupportedToBuildEffective() {
147 return isSupportedToBuildEffective;
151 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
152 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
156 public CopyHistory getCopyHistory() {
161 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
162 copyHistory = copyHistory.append(typeOfCopy, toAppend);
166 public StatementContextBase<?, ?, ?> getOriginalCtx() {
171 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
172 this.originalCtx = originalCtx;
176 public void setOrder(final int order) {
181 public int getOrder() {
186 public ModelProcessingPhase getCompletedPhase() {
187 return completedPhase;
191 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
192 this.completedPhase = completedPhase;
196 * @return context of parent of statement
199 public abstract StatementContextBase<?, ?, ?> getParentContext();
202 * @return root context of statement
205 public abstract RootStatementContext<?, ?, ?> getRoot();
208 * @return statement identifier
211 public StatementIdentifier getIdentifier() {
216 * @return origin of statement
219 public StatementSource getStatementSource() {
220 return statementDeclSource.getStatementSource();
224 * @return reference of statement source
227 public StatementSourceReference getStatementSourceReference() {
228 return statementDeclSource;
232 * @return raw statement argument string
235 public String rawStatementArgument() {
236 return identifier.getArgument();
239 private static final <T> Collection<T> maybeWrap(final Collection<T> input) {
240 if (input instanceof ImmutableCollection) {
244 return Collections.unmodifiableCollection(input);
248 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
249 return maybeWrap(declared);
253 * @return collection of all substatements
256 public Collection<StatementContextBase<?, ?, ?>> substatements() {
257 return maybeWrap(substatements.values());
261 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
262 return maybeWrap(effective);
265 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
266 if (!effective.isEmpty()) {
267 effective.removeAll(substatements);
272 private void shrinkEffective() {
273 if (effective.isEmpty()) {
274 effective = ImmutableList.of();
278 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
279 if (effective.isEmpty()) {
283 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
284 while (iterator.hasNext()) {
285 final StatementContextBase<?, ?, ?> next = iterator.next();
286 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
295 * adds effective statement to collection of substatements
297 * @param substatement substatement
298 * @throws IllegalStateException
299 * if added in declared phase
300 * @throws NullPointerException
301 * if statement parameter is null
303 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
304 Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
305 getStatementSourceReference());
306 beforeAddEffectiveStatement(1);
307 effective.add(substatement);
311 * adds effective statement to collection of substatements
313 * @param substatements substatements
314 * @throws IllegalStateException
315 * if added in declared phase
316 * @throws NullPointerException
317 * if statement parameter is null
319 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
320 substatements.forEach(Preconditions::checkNotNull);
321 beforeAddEffectiveStatement(substatements.size());
322 effective.addAll(substatements);
325 private void beforeAddEffectiveStatement(final int toAdd) {
326 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
327 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
328 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
329 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
331 if (effective.isEmpty()) {
332 effective = new ArrayList<>(toAdd);
337 * adds declared statement to collection of substatements
339 * @param substatement substatement
340 * @throws IllegalStateException
341 * if added in effective phase
342 * @throws NullPointerException
343 * if statement parameter is null
345 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
347 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
348 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
349 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
351 if (declared.isEmpty()) {
352 declared = new ArrayList<>(1);
354 declared.add(Preconditions.checkNotNull(substatement,
355 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
359 * builds a new substatement from statement definition context and statement source reference
361 * @param def definition context
362 * @param ref source reference
364 * @return instance of ContextBuilder
366 @SuppressWarnings({ "rawtypes", "unchecked" })
367 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
368 final StatementSourceReference ref) {
369 return new ContextBuilder(def, ref) {
372 public StatementContextBase build() throws SourceException {
373 StatementContextBase<?, ?, ?> potential = null;
375 final StatementDefinition stmtDef = getDefinition().getPublicView();
376 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
377 && stmtDef != Rfc6020Mapping.TYPE) {
378 potential = substatements.get(createIdentifier());
380 if (potential == null) {
381 potential = new SubstatementContext(StatementContextBase.this, this);
382 if (substatements.isEmpty()) {
383 substatements = new LinkedHashMap<>(1);
385 substatements.put(createIdentifier(), potential);
386 getDefinition().onStatementAdded(potential);
388 potential.resetLists();
389 switch (this.getStamementSource().getStatementSource()) {
391 addDeclaredSubstatement(potential);
394 addEffectiveSubstatement(potential);
403 * @return local namespace behaviour type {@link NamespaceBehaviour}
406 public StorageNodeType getStorageNodeType() {
407 return StorageNodeType.STATEMENT_LOCAL;
411 * builds {@link DeclaredStatement} for statement context
414 public D buildDeclared() {
415 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
416 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
417 if (declaredInstance == null) {
418 declaredInstance = definition().getFactory().createDeclared(this);
420 return declaredInstance;
424 * builds {@link EffectiveStatement} for statement context
427 public E buildEffective() {
428 if (effectiveInstance == null) {
429 effectiveInstance = definition().getFactory().createEffective(this);
431 return effectiveInstance;
435 * clears collection of declared substatements
437 * @throws IllegalStateException
438 * if invoked in effective build phase
442 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
443 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
444 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
446 declared = ImmutableList.of();
450 * tries to execute current {@link ModelProcessingPhase} of source parsing
453 * to be executed (completed)
454 * @return if phase was successfully completed
455 * @throws SourceException
456 * when an error occured in source parsing
458 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
460 boolean finished = true;
461 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
462 if (!openMutations.isEmpty()) {
463 final Iterator<ContextMutation> it = openMutations.iterator();
464 while (it.hasNext()) {
465 final ContextMutation current = it.next();
466 if (current.isFinished()) {
473 if (openMutations.isEmpty()) {
474 phaseMutation.removeAll(phase);
475 if (phaseMutation.isEmpty()) {
476 phaseMutation = ImmutableMultimap.of();
481 for (final StatementContextBase<?, ?, ?> child : declared) {
482 finished &= child.tryToCompletePhase(phase);
484 for (final StatementContextBase<?, ?, ?> child : effective) {
485 finished &= child.tryToCompletePhase(phase);
489 onPhaseCompleted(phase);
496 * occurs on end of {@link ModelProcessingPhase} of source parsing
499 * that was to be completed (finished)
500 * @throws SourceException
501 * when an error occured in source parsing
503 private void onPhaseCompleted(final ModelProcessingPhase phase) {
504 completedPhase = phase;
506 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
507 if (listeners.isEmpty()) {
511 final Iterator<OnPhaseFinished> listener = listeners.iterator();
512 while (listener.hasNext()) {
513 final OnPhaseFinished next = listener.next();
514 if (next.phaseFinished(this, phase)) {
519 if (listeners.isEmpty()) {
520 phaseListeners.removeAll(phase);
521 if (phaseListeners.isEmpty()) {
522 phaseListeners = ImmutableMultimap.of();
528 * Ends declared section of current node.
531 * @throws SourceException
533 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
534 definition().onDeclarationFinished(this, phase);
538 * @return statement definition
540 protected final StatementDefinitionContext<A, D, E> definition() {
545 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
546 definition().checkNamespaceAllowed(type);
550 * occurs when an item is added to model namespace
552 * @throws SourceException instance of SourceException
555 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
556 // definition().onNamespaceElementAdded(this, type, key, value);
559 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
560 final OnNamespaceItemAdded listener) throws SourceException {
561 final Object potential = getFromNamespace(type, key);
562 if (potential != null) {
563 listener.namespaceItemAdded(this, type, key, potential);
566 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
567 if (behaviour instanceof NamespaceBehaviourWithListeners) {
568 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
569 casted.addValueListener(new ValueAddedListener<K>(this, key) {
571 void onValueAdded(final Object key, final Object value) {
573 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
574 } catch (final SourceException e) {
575 throw Throwables.propagate(e);
583 * @see StatementSupport#getPublicView()
586 public StatementDefinition getPublicDefinition() {
587 return definition().getPublicView();
591 * @return new {@link ModelActionBuilder} for the phase
594 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
595 return getRoot().getSourceContext().newInferenceAction(phase);
598 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
599 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
603 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
605 * @throws SourceException
607 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
609 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
610 getStatementSourceReference());
611 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
612 getStatementSourceReference());
614 ModelProcessingPhase finishedPhase = completedPhase;
615 while (finishedPhase != null) {
616 if (phase.equals(finishedPhase)) {
617 listener.phaseFinished(this, finishedPhase);
620 finishedPhase = finishedPhase.getPreviousPhase();
622 if (phaseListeners.isEmpty()) {
623 phaseListeners = newMultimap();
626 phaseListeners.put(phase, listener);
630 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
632 * @throws IllegalStateException
633 * when the mutation was registered after phase was completed
635 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
636 ModelProcessingPhase finishedPhase = completedPhase;
637 while (finishedPhase != null) {
638 if (phase.equals(finishedPhase)) {
639 throw new IllegalStateException("Mutation registered after phase was completed at: " +
640 getStatementSourceReference());
642 finishedPhase = finishedPhase.getPreviousPhase();
645 if (phaseMutation.isEmpty()) {
646 phaseMutation = newMultimap();
648 phaseMutation.put(phase, mutation);
652 * adds statement to namespace map with the key
655 * {@link StatementNamespace} child that determines namespace to be added to
657 * of type according to namespace class specification
659 * to be added to namespace map
662 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
663 final StmtContext<?, ?, ?> stmt) {
664 addContextToNamespace(namespace, (K) key, stmt);