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.Multimap;
13 import com.google.common.collect.Multimaps;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.EnumMap;
18 import java.util.EventListener;
19 import java.util.Iterator;
20 import java.util.LinkedHashMap;
21 import java.util.List;
23 import javax.annotation.Nonnull;
24 import org.opendaylight.yangtools.concepts.Identifiable;
25 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
29 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
30 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
38 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
39 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
40 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
42 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
43 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
46 * event listener when an item is added to model namespace
48 interface OnNamespaceItemAdded extends EventListener {
50 * @throws SourceException
52 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
56 * event listener when a parsing {@link ModelProcessingPhase} is completed
58 interface OnPhaseFinished extends EventListener {
60 * @throws SourceException
62 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
66 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
68 interface ContextMutation {
73 private final StatementDefinitionContext<A, D, E> definition;
74 private final StatementIdentifier identifier;
75 private final StatementSourceReference statementDeclSource;
77 private final Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners =
78 Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
80 private final Multimap<ModelProcessingPhase, ContextMutation> phaseMutation =
81 Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
83 private final Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>(1);
85 private final List<TypeOfCopy> copyHistory = new ArrayList<>(1);
86 private final Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>(1);
87 private final Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>(1);
88 private final Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>(1);
90 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
91 private boolean isSupportedToBuildEffective = true;
92 private StatementContextBase<?, ?, ?> originalCtx;
93 private ModelProcessingPhase completedPhase;
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();
102 this.completedPhase = null;
103 this.copyHistory.add(TypeOfCopy.ORIGINAL);
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());
114 this.completedPhase = null;
115 this.copyHistory.add(TypeOfCopy.ORIGINAL);
119 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
120 return effectOfStatement;
124 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
125 effectOfStatement.add(ctx);
128 public SupportedByFeatures getSupportedByFeatures() {
129 return supportedByFeatures;
133 public void setSupportedByFeatures(final boolean isSupported) {
134 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
138 public boolean isSupportedToBuildEffective() {
139 return isSupportedToBuildEffective;
143 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
144 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
148 public List<TypeOfCopy> getCopyHistory() {
153 public void addToCopyHistory(final TypeOfCopy typeOfCopy) {
154 this.copyHistory.add(typeOfCopy);
158 public void addAllToCopyHistory(final List<TypeOfCopy> typeOfCopyList) {
159 this.copyHistory.addAll(typeOfCopyList);
163 public StatementContextBase<?, ?, ?> getOriginalCtx() {
168 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
169 this.originalCtx = originalCtx;
173 public void setOrder(final int order) {
178 public int getOrder() {
183 public ModelProcessingPhase getCompletedPhase() {
184 return completedPhase;
188 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
189 this.completedPhase = completedPhase;
193 * @return context of parent of statement
196 public abstract StatementContextBase<?, ?, ?> getParentContext();
199 * @return root context of statement
202 public abstract RootStatementContext<?, ?, ?> getRoot();
205 * @return statement identifier
208 public StatementIdentifier getIdentifier() {
213 * @return origin of statement
216 public StatementSource getStatementSource() {
217 return statementDeclSource.getStatementSource();
221 * @return reference of statement source
224 public StatementSourceReference getStatementSourceReference() {
225 return statementDeclSource;
229 * @return raw statement argument string
232 public String rawStatementArgument() {
233 return identifier.getArgument();
237 * @return collection of declared substatements
240 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
241 return Collections.unmodifiableCollection(declared);
245 * @return collection of substatements
248 public Collection<StatementContextBase<?, ?, ?>> substatements() {
249 return Collections.unmodifiableCollection(substatements.values());
253 * @return collection of effective substatements
256 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
257 return Collections.unmodifiableCollection(effective);
260 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
261 effective.removeAll(substatements);
264 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
265 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
266 while (iterator.hasNext()) {
267 final StatementContextBase<?, ?, ?> next = iterator.next();
268 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
275 * adds effective statement to collection of substatements
277 * @param substatement substatement
278 * @throws IllegalStateException
279 * if added in declared phase
280 * @throws NullPointerException
281 * if statement parameter is null
283 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
285 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
286 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
287 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
288 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
290 effective.add(Preconditions.checkNotNull(substatement,
291 "StatementContextBase effective substatement cannot be null at: %s", getStatementSourceReference()));
295 * adds declared statement to collection of substatements
297 * @param substatement substatement
298 * @throws IllegalStateException
299 * if added in effective phase
300 * @throws NullPointerException
301 * if statement parameter is null
303 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
305 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
306 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
307 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
309 declared.add(Preconditions.checkNotNull(substatement,
310 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
314 * builds new substatement from statement definition context and statement source reference
316 * @param def definition context
317 * @param ref source reference
319 * @return instance of ContextBuilder
321 @SuppressWarnings({ "rawtypes", "unchecked" })
322 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
323 final StatementSourceReference ref) {
324 return new ContextBuilder(def, ref) {
327 public StatementContextBase build() throws SourceException {
328 StatementContextBase<?, ?, ?> potential = null;
330 final StatementDefinition stmtDef = getDefinition().getPublicView();
331 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
332 && stmtDef != Rfc6020Mapping.TYPE) {
333 potential = substatements.get(createIdentifier());
335 if (potential == null) {
336 potential = new SubstatementContext(StatementContextBase.this, this);
337 substatements.put(createIdentifier(), potential);
338 getDefinition().onStatementAdded(potential);
340 potential.resetLists();
341 switch (this.getStamementSource().getStatementSource()) {
343 addDeclaredSubstatement(potential);
346 addEffectiveSubstatement(potential);
355 * @return local namespace behaviour type {@link NamespaceBehaviour}
358 public StorageNodeType getStorageNodeType() {
359 return StorageNodeType.STATEMENT_LOCAL;
363 * builds {@link DeclaredStatement} for statement context
366 public D buildDeclared() {
367 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
368 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
369 if (declaredInstance == null) {
370 declaredInstance = definition().getFactory().createDeclared(this);
372 return declaredInstance;
376 * builds {@link EffectiveStatement} for statement context
379 public E buildEffective() {
380 if (effectiveInstance == null) {
381 effectiveInstance = definition().getFactory().createEffective(this);
383 return effectiveInstance;
387 * clears collection of declared substatements
389 * @throws IllegalStateException
390 * if invoked in effective build phase
394 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
395 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
396 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
402 * tries to execute current {@link ModelProcessingPhase} of source parsing
405 * to be executed (completed)
406 * @return if phase was successfully completed
407 * @throws SourceException
408 * when an error occured in source parsing
410 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
411 final Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
412 boolean finished = true;
413 while (openMutations.hasNext()) {
414 final ContextMutation current = openMutations.next();
415 if (current.isFinished()) {
416 openMutations.remove();
421 for (final StatementContextBase<?, ?, ?> child : declared) {
422 finished &= child.tryToCompletePhase(phase);
424 for (final StatementContextBase<?, ?, ?> child : effective) {
425 finished &= child.tryToCompletePhase(phase);
429 onPhaseCompleted(phase);
436 * occurs on end of {@link ModelProcessingPhase} of source parsing
439 * that was to be completed (finished)
440 * @throws SourceException
441 * when an error occured in source parsing
443 private void onPhaseCompleted(final ModelProcessingPhase phase) {
444 completedPhase = phase;
445 final Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
446 while (listener.hasNext()) {
447 final OnPhaseFinished next = listener.next();
448 if (next.phaseFinished(this, phase)) {
455 * Ends declared section of current node.
458 * @throws SourceException
460 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
461 definition().onDeclarationFinished(this, phase);
465 * @return statement definition
467 protected final StatementDefinitionContext<A, D, E> definition() {
472 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
473 definition().checkNamespaceAllowed(type);
477 * occurs when an item is added to model namespace
479 * @throws SourceException instance of SourceException
482 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
483 // definition().onNamespaceElementAdded(this, type, key, value);
486 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
487 final OnNamespaceItemAdded listener) throws SourceException {
488 final Object potential = getFromNamespace(type, key);
489 if (potential != null) {
490 listener.namespaceItemAdded(this, type, key, potential);
493 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
494 if (behaviour instanceof NamespaceBehaviourWithListeners) {
495 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
496 casted.addValueListener(new ValueAddedListener<K>(this, key) {
498 void onValueAdded(final Object key, final Object value) {
500 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
501 } catch (final SourceException e) {
502 throw Throwables.propagate(e);
510 * @see StatementSupport#getPublicView()
513 public StatementDefinition getPublicDefinition() {
514 return definition().getPublicView();
518 * @return new {@link ModelActionBuilder} for the phase
521 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
522 return getRoot().getSourceContext().newInferenceAction(phase);
526 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
528 * @throws SourceException
530 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
532 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
533 getStatementSourceReference());
534 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
535 getStatementSourceReference());
537 ModelProcessingPhase finishedPhase = completedPhase;
538 while (finishedPhase != null) {
539 if (phase.equals(finishedPhase)) {
540 listener.phaseFinished(this, finishedPhase);
543 finishedPhase = finishedPhase.getPreviousPhase();
545 phaseListeners.put(phase, listener);
549 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
551 * @throws IllegalStateException
552 * when the mutation was registered after phase was completed
554 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
555 ModelProcessingPhase finishedPhase = completedPhase;
556 while (finishedPhase != null) {
557 if (phase.equals(finishedPhase)) {
558 throw new IllegalStateException("Mutation registered after phase was completed at: " +
559 getStatementSourceReference());
561 finishedPhase = finishedPhase.getPreviousPhase();
563 phaseMutation.put(phase, mutation);
567 * adds statement to namespace map with the key
570 * {@link StatementNamespace} child that determines namespace to be added to
572 * of type according to namespace class specification
574 * to be added to namespace map
577 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
578 final StmtContext<?, ?, ?> stmt) {
579 addContextToNamespace(namespace, (K) key, stmt);