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.ImmutableList;
13 import com.google.common.collect.Multimap;
14 import com.google.common.collect.Multimaps;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.EnumMap;
19 import java.util.EventListener;
20 import java.util.Iterator;
21 import java.util.LinkedHashMap;
22 import java.util.List;
24 import javax.annotation.Nonnull;
25 import org.opendaylight.yangtools.concepts.Identifiable;
26 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
30 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
31 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
39 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
40 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
41 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
43 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
44 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
47 * event listener when an item is added to model namespace
49 interface OnNamespaceItemAdded extends EventListener {
51 * @throws SourceException
53 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
57 * event listener when a parsing {@link ModelProcessingPhase} is completed
59 interface OnPhaseFinished extends EventListener {
61 * @throws SourceException
63 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase);
67 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
69 interface ContextMutation {
74 private final static List<TypeOfCopy> ORIGINAL_COPY = ImmutableList.of(TypeOfCopy.ORIGINAL);
76 private final StatementDefinitionContext<A, D, E> definition;
77 private final StatementIdentifier identifier;
78 private final StatementSourceReference statementDeclSource;
80 private final Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners =
81 Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
83 private final Multimap<ModelProcessingPhase, ContextMutation> phaseMutation =
84 Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
86 private final Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>(1);
88 private final Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>(1);
89 private final Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>(1);
90 private final Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>(1);
92 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
93 private List<TypeOfCopy> copyHistory = ORIGINAL_COPY;
94 private boolean isSupportedToBuildEffective = true;
95 private ModelProcessingPhase completedPhase = null;
96 private StatementContextBase<?, ?, ?> originalCtx;
97 private D declaredInstance;
98 private E effectiveInstance;
99 private int order = 0;
101 StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) {
102 this.definition = builder.getDefinition();
103 this.identifier = builder.createIdentifier();
104 this.statementDeclSource = builder.getStamementSource();
107 StatementContextBase(final StatementContextBase<A, D, E> original) {
108 this.definition = Preconditions.checkNotNull(original.definition,
109 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
110 this.identifier = Preconditions.checkNotNull(original.identifier,
111 "Statement context identifier cannot be null copying from: %s", original.getStatementSourceReference());
112 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
113 "Statement context statementDeclSource cannot be null copying from: %s",
114 original.getStatementSourceReference());
118 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
119 return effectOfStatement;
123 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
124 effectOfStatement.add(ctx);
127 public SupportedByFeatures getSupportedByFeatures() {
128 return supportedByFeatures;
132 public void setSupportedByFeatures(final boolean isSupported) {
133 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
137 public boolean isSupportedToBuildEffective() {
138 return isSupportedToBuildEffective;
142 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
143 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
147 public List<TypeOfCopy> getCopyHistory() {
151 private void growCopyHistory(final int growBy) {
152 if (copyHistory == ORIGINAL_COPY) {
153 final List<TypeOfCopy> newCopyHistory = new ArrayList<>(growBy + 1);
154 newCopyHistory.add(TypeOfCopy.ORIGINAL);
155 copyHistory = newCopyHistory;
160 public void addToCopyHistory(final TypeOfCopy typeOfCopy) {
162 this.copyHistory.add(typeOfCopy);
166 public void addAllToCopyHistory(final List<TypeOfCopy> typeOfCopyList) {
167 growCopyHistory(typeOfCopyList.size());
168 this.copyHistory.addAll(typeOfCopyList);
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();
246 * @return collection of declared substatements
249 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
250 return Collections.unmodifiableCollection(declared);
254 * @return collection of substatements
257 public Collection<StatementContextBase<?, ?, ?>> substatements() {
258 return Collections.unmodifiableCollection(substatements.values());
262 * @return collection of effective substatements
265 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
266 return Collections.unmodifiableCollection(effective);
269 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
270 effective.removeAll(substatements);
273 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
274 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
275 while (iterator.hasNext()) {
276 final StatementContextBase<?, ?, ?> next = iterator.next();
277 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
284 * adds effective statement to collection of substatements
286 * @param substatement substatement
287 * @throws IllegalStateException
288 * if added in declared phase
289 * @throws NullPointerException
290 * if statement parameter is null
292 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
294 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
295 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
296 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
297 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
299 effective.add(Preconditions.checkNotNull(substatement,
300 "StatementContextBase effective substatement cannot be null at: %s", getStatementSourceReference()));
304 * adds declared statement to collection of substatements
306 * @param substatement substatement
307 * @throws IllegalStateException
308 * if added in effective phase
309 * @throws NullPointerException
310 * if statement parameter is null
312 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
314 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
315 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
316 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
318 declared.add(Preconditions.checkNotNull(substatement,
319 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
323 * builds new substatement from statement definition context and statement source reference
325 * @param def definition context
326 * @param ref source reference
328 * @return instance of ContextBuilder
330 @SuppressWarnings({ "rawtypes", "unchecked" })
331 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
332 final StatementSourceReference ref) {
333 return new ContextBuilder(def, ref) {
336 public StatementContextBase build() throws SourceException {
337 StatementContextBase<?, ?, ?> potential = null;
339 final StatementDefinition stmtDef = getDefinition().getPublicView();
340 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
341 && stmtDef != Rfc6020Mapping.TYPE) {
342 potential = substatements.get(createIdentifier());
344 if (potential == null) {
345 potential = new SubstatementContext(StatementContextBase.this, this);
346 substatements.put(createIdentifier(), potential);
347 getDefinition().onStatementAdded(potential);
349 potential.resetLists();
350 switch (this.getStamementSource().getStatementSource()) {
352 addDeclaredSubstatement(potential);
355 addEffectiveSubstatement(potential);
364 * @return local namespace behaviour type {@link NamespaceBehaviour}
367 public StorageNodeType getStorageNodeType() {
368 return StorageNodeType.STATEMENT_LOCAL;
372 * builds {@link DeclaredStatement} for statement context
375 public D buildDeclared() {
376 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
377 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
378 if (declaredInstance == null) {
379 declaredInstance = definition().getFactory().createDeclared(this);
381 return declaredInstance;
385 * builds {@link EffectiveStatement} for statement context
388 public E buildEffective() {
389 if (effectiveInstance == null) {
390 effectiveInstance = definition().getFactory().createEffective(this);
392 return effectiveInstance;
396 * clears collection of declared substatements
398 * @throws IllegalStateException
399 * if invoked in effective build phase
403 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
404 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
405 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
411 * tries to execute current {@link ModelProcessingPhase} of source parsing
414 * to be executed (completed)
415 * @return if phase was successfully completed
416 * @throws SourceException
417 * when an error occured in source parsing
419 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
420 final Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
421 boolean finished = true;
422 while (openMutations.hasNext()) {
423 final ContextMutation current = openMutations.next();
424 if (current.isFinished()) {
425 openMutations.remove();
430 for (final StatementContextBase<?, ?, ?> child : declared) {
431 finished &= child.tryToCompletePhase(phase);
433 for (final StatementContextBase<?, ?, ?> child : effective) {
434 finished &= child.tryToCompletePhase(phase);
438 onPhaseCompleted(phase);
445 * occurs on end of {@link ModelProcessingPhase} of source parsing
448 * that was to be completed (finished)
449 * @throws SourceException
450 * when an error occured in source parsing
452 private void onPhaseCompleted(final ModelProcessingPhase phase) {
453 completedPhase = phase;
454 final Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
455 while (listener.hasNext()) {
456 final OnPhaseFinished next = listener.next();
457 if (next.phaseFinished(this, phase)) {
464 * Ends declared section of current node.
467 * @throws SourceException
469 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
470 definition().onDeclarationFinished(this, phase);
474 * @return statement definition
476 protected final StatementDefinitionContext<A, D, E> definition() {
481 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
482 definition().checkNamespaceAllowed(type);
486 * occurs when an item is added to model namespace
488 * @throws SourceException instance of SourceException
491 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
492 // definition().onNamespaceElementAdded(this, type, key, value);
495 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
496 final OnNamespaceItemAdded listener) throws SourceException {
497 final Object potential = getFromNamespace(type, key);
498 if (potential != null) {
499 listener.namespaceItemAdded(this, type, key, potential);
502 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
503 if (behaviour instanceof NamespaceBehaviourWithListeners) {
504 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
505 casted.addValueListener(new ValueAddedListener<K>(this, key) {
507 void onValueAdded(final Object key, final Object value) {
509 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
510 } catch (final SourceException e) {
511 throw Throwables.propagate(e);
519 * @see StatementSupport#getPublicView()
522 public StatementDefinition getPublicDefinition() {
523 return definition().getPublicView();
527 * @return new {@link ModelActionBuilder} for the phase
530 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
531 return getRoot().getSourceContext().newInferenceAction(phase);
535 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
537 * @throws SourceException
539 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
541 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
542 getStatementSourceReference());
543 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
544 getStatementSourceReference());
546 ModelProcessingPhase finishedPhase = completedPhase;
547 while (finishedPhase != null) {
548 if (phase.equals(finishedPhase)) {
549 listener.phaseFinished(this, finishedPhase);
552 finishedPhase = finishedPhase.getPreviousPhase();
554 phaseListeners.put(phase, listener);
558 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
560 * @throws IllegalStateException
561 * when the mutation was registered after phase was completed
563 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
564 ModelProcessingPhase finishedPhase = completedPhase;
565 while (finishedPhase != null) {
566 if (phase.equals(finishedPhase)) {
567 throw new IllegalStateException("Mutation registered after phase was completed at: " +
568 getStatementSourceReference());
570 finishedPhase = finishedPhase.getPreviousPhase();
572 phaseMutation.put(phase, mutation);
576 * adds statement to namespace map with the key
579 * {@link StatementNamespace} child that determines namespace to be added to
581 * of type according to namespace class specification
583 * to be added to namespace map
586 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
587 final StmtContext<?, ?, ?> stmt) {
588 addContextToNamespace(namespace, (K) key, stmt);