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 (ctxs.isEmpty()) {
135 if (effectOfStatement.isEmpty()) {
136 effectOfStatement = new ArrayList<>(ctxs.size());
138 effectOfStatement.addAll(ctxs);
142 public SupportedByFeatures getSupportedByFeatures() {
143 return supportedByFeatures;
147 public void setSupportedByFeatures(final boolean isSupported) {
148 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
152 public boolean isSupportedToBuildEffective() {
153 return isSupportedToBuildEffective;
157 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
158 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
162 public CopyHistory getCopyHistory() {
167 public void appendCopyHistory(final CopyType typeOfCopy, final CopyHistory toAppend) {
168 copyHistory = copyHistory.append(typeOfCopy, toAppend);
172 public StatementContextBase<?, ?, ?> getOriginalCtx() {
177 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
178 this.originalCtx = originalCtx;
182 public void setOrder(final int order) {
187 public int getOrder() {
192 public ModelProcessingPhase getCompletedPhase() {
193 return completedPhase;
197 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
198 this.completedPhase = completedPhase;
202 * @return context of parent of statement
205 public abstract StatementContextBase<?, ?, ?> getParentContext();
208 * @return root context of statement
211 public abstract RootStatementContext<?, ?, ?> getRoot();
214 * @return statement identifier
217 public StatementIdentifier getIdentifier() {
222 * @return origin of statement
225 public StatementSource getStatementSource() {
226 return statementDeclSource.getStatementSource();
230 * @return reference of statement source
233 public StatementSourceReference getStatementSourceReference() {
234 return statementDeclSource;
238 * @return raw statement argument string
241 public String rawStatementArgument() {
242 return identifier.getArgument();
245 private static final <T> Collection<T> maybeWrap(final Collection<T> input) {
246 if (input instanceof ImmutableCollection) {
250 return Collections.unmodifiableCollection(input);
254 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
255 return maybeWrap(declared);
259 * @return collection of all substatements
262 public Collection<StatementContextBase<?, ?, ?>> substatements() {
263 return maybeWrap(substatements.values());
267 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
268 return maybeWrap(effective);
271 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
272 if (!effective.isEmpty()) {
273 effective.removeAll(substatements);
278 private void shrinkEffective() {
279 if (effective.isEmpty()) {
280 effective = ImmutableList.of();
284 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
285 if (effective.isEmpty()) {
289 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
290 while (iterator.hasNext()) {
291 final StatementContextBase<?, ?, ?> next = iterator.next();
292 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
301 * adds effective statement to collection of substatements
303 * @param substatement substatement
304 * @throws IllegalStateException
305 * if added in declared phase
306 * @throws NullPointerException
307 * if statement parameter is null
309 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
310 Preconditions.checkNotNull(substatement, "StatementContextBase effective substatement cannot be null at: %s",
311 getStatementSourceReference());
312 beforeAddEffectiveStatement(1);
313 effective.add(substatement);
317 * adds effective statement to collection of substatements
319 * @param substatements substatements
320 * @throws IllegalStateException
321 * if added in declared phase
322 * @throws NullPointerException
323 * if statement parameter is null
325 public void addEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
326 if (substatements.isEmpty()) {
330 substatements.forEach(Preconditions::checkNotNull);
331 beforeAddEffectiveStatement(substatements.size());
332 effective.addAll(substatements);
335 private void beforeAddEffectiveStatement(final int toAdd) {
336 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
337 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
338 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
339 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
341 if (effective.isEmpty()) {
342 effective = new ArrayList<>(toAdd);
347 * adds declared statement to collection of substatements
349 * @param substatement substatement
350 * @throws IllegalStateException
351 * if added in effective phase
352 * @throws NullPointerException
353 * if statement parameter is null
355 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
357 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
358 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
359 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
361 if (declared.isEmpty()) {
362 declared = new ArrayList<>(1);
364 declared.add(Preconditions.checkNotNull(substatement,
365 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
369 * builds a new substatement from statement definition context and statement source reference
371 * @param def definition context
372 * @param ref source reference
374 * @return instance of ContextBuilder
376 @SuppressWarnings({ "rawtypes", "unchecked" })
377 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
378 final StatementSourceReference ref) {
379 return new ContextBuilder(def, ref) {
382 public StatementContextBase build() throws SourceException {
383 StatementContextBase<?, ?, ?> potential = null;
385 final StatementDefinition stmtDef = getDefinition().getPublicView();
386 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
387 && stmtDef != Rfc6020Mapping.TYPE) {
388 potential = substatements.get(createIdentifier());
390 if (potential == null) {
391 potential = new SubstatementContext(StatementContextBase.this, this);
392 if (substatements.isEmpty()) {
393 substatements = new LinkedHashMap<>(1);
395 substatements.put(createIdentifier(), potential);
396 getDefinition().onStatementAdded(potential);
398 potential.resetLists();
399 switch (this.getStamementSource().getStatementSource()) {
401 addDeclaredSubstatement(potential);
404 addEffectiveSubstatement(potential);
413 * @return local namespace behaviour type {@link NamespaceBehaviour}
416 public StorageNodeType getStorageNodeType() {
417 return StorageNodeType.STATEMENT_LOCAL;
421 * builds {@link DeclaredStatement} for statement context
424 public D buildDeclared() {
425 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
426 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
427 if (declaredInstance == null) {
428 declaredInstance = definition().getFactory().createDeclared(this);
430 return declaredInstance;
434 * builds {@link EffectiveStatement} for statement context
437 public E buildEffective() {
438 if (effectiveInstance == null) {
439 effectiveInstance = definition().getFactory().createEffective(this);
441 return effectiveInstance;
445 * clears collection of declared substatements
447 * @throws IllegalStateException
448 * if invoked in effective build phase
452 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
453 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
454 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
456 declared = ImmutableList.of();
460 * tries to execute current {@link ModelProcessingPhase} of source parsing
463 * to be executed (completed)
464 * @return if phase was successfully completed
465 * @throws SourceException
466 * when an error occured in source parsing
468 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
470 boolean finished = true;
471 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
472 if (!openMutations.isEmpty()) {
473 final Iterator<ContextMutation> it = openMutations.iterator();
474 while (it.hasNext()) {
475 final ContextMutation current = it.next();
476 if (current.isFinished()) {
483 if (openMutations.isEmpty()) {
484 phaseMutation.removeAll(phase);
485 if (phaseMutation.isEmpty()) {
486 phaseMutation = ImmutableMultimap.of();
491 for (final StatementContextBase<?, ?, ?> child : declared) {
492 finished &= child.tryToCompletePhase(phase);
494 for (final StatementContextBase<?, ?, ?> child : effective) {
495 finished &= child.tryToCompletePhase(phase);
499 onPhaseCompleted(phase);
506 * occurs on end of {@link ModelProcessingPhase} of source parsing
509 * that was to be completed (finished)
510 * @throws SourceException
511 * when an error occured in source parsing
513 private void onPhaseCompleted(final ModelProcessingPhase phase) {
514 completedPhase = phase;
516 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
517 if (listeners.isEmpty()) {
521 final Iterator<OnPhaseFinished> listener = listeners.iterator();
522 while (listener.hasNext()) {
523 final OnPhaseFinished next = listener.next();
524 if (next.phaseFinished(this, phase)) {
529 if (listeners.isEmpty()) {
530 phaseListeners.removeAll(phase);
531 if (phaseListeners.isEmpty()) {
532 phaseListeners = ImmutableMultimap.of();
538 * Ends declared section of current node.
541 * @throws SourceException
543 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
544 definition().onDeclarationFinished(this, phase);
548 * @return statement definition
550 protected final StatementDefinitionContext<A, D, E> definition() {
555 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
556 definition().checkNamespaceAllowed(type);
560 * occurs when an item is added to model namespace
562 * @throws SourceException instance of SourceException
565 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
566 // definition().onNamespaceElementAdded(this, type, key, value);
569 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
570 final OnNamespaceItemAdded listener) throws SourceException {
571 final Object potential = getFromNamespace(type, key);
572 if (potential != null) {
573 listener.namespaceItemAdded(this, type, key, potential);
576 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
577 if (behaviour instanceof NamespaceBehaviourWithListeners) {
578 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
579 casted.addValueListener(new ValueAddedListener<K>(this, key) {
581 void onValueAdded(final Object key, final Object value) {
583 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
584 } catch (final SourceException e) {
585 throw Throwables.propagate(e);
593 * @see StatementSupport#getPublicView()
596 public StatementDefinition getPublicDefinition() {
597 return definition().getPublicView();
601 * @return new {@link ModelActionBuilder} for the phase
604 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
605 return getRoot().getSourceContext().newInferenceAction(phase);
608 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
609 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
613 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
615 * @throws SourceException
617 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
619 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
620 getStatementSourceReference());
621 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
622 getStatementSourceReference());
624 ModelProcessingPhase finishedPhase = completedPhase;
625 while (finishedPhase != null) {
626 if (phase.equals(finishedPhase)) {
627 listener.phaseFinished(this, finishedPhase);
630 finishedPhase = finishedPhase.getPreviousPhase();
632 if (phaseListeners.isEmpty()) {
633 phaseListeners = newMultimap();
636 phaseListeners.put(phase, listener);
640 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
642 * @throws IllegalStateException
643 * when the mutation was registered after phase was completed
645 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
646 ModelProcessingPhase finishedPhase = completedPhase;
647 while (finishedPhase != null) {
648 if (phase.equals(finishedPhase)) {
649 throw new IllegalStateException("Mutation registered after phase was completed at: " +
650 getStatementSourceReference());
652 finishedPhase = finishedPhase.getPreviousPhase();
655 if (phaseMutation.isEmpty()) {
656 phaseMutation = newMultimap();
658 phaseMutation.put(phase, mutation);
662 * adds statement to namespace map with the key
665 * {@link StatementNamespace} child that determines namespace to be added to
667 * of type according to namespace class specification
669 * to be added to namespace map
672 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
673 final StmtContext<?, ?, ?> stmt) {
674 addContextToNamespace(namespace, (K) key, stmt);
678 public final String toString() {
679 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
682 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
683 return toStringHelper.add("definition", definition).add("id", identifier);