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;
76 private int order = 0;
78 private final Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>();
80 private final Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>();
81 private final Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>();
82 private final Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>();
85 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
86 return effectOfStatement;
90 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
91 effectOfStatement.add(ctx);
94 private ModelProcessingPhase completedPhase;
96 private final Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners =
97 Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>());
99 private final Multimap<ModelProcessingPhase, ContextMutation> phaseMutation =
100 Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>());
102 private D declaredInstance;
103 private E effectiveInstance;
105 private StatementContextBase<?, ?, ?> originalCtx;
106 private final List<TypeOfCopy> copyHistory = new ArrayList<>(1);
108 private boolean isSupportedToBuildEffective = true;
109 private SupportedByFeatures supportedByFeatures = SupportedByFeatures.UNDEFINED;
112 public SupportedByFeatures getSupportedByFeatures() {
113 return supportedByFeatures;
117 public void setSupportedByFeatures(final boolean isSupported) {
118 this.supportedByFeatures = isSupported ? SupportedByFeatures.SUPPORTED : SupportedByFeatures.NOT_SUPPORTED;
122 public boolean isSupportedToBuildEffective() {
123 return isSupportedToBuildEffective;
127 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
128 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
132 public List<TypeOfCopy> getCopyHistory() {
137 public void addToCopyHistory(final TypeOfCopy typeOfCopy) {
138 this.copyHistory.add(typeOfCopy);
142 public void addAllToCopyHistory(final List<TypeOfCopy> typeOfCopyList) {
143 this.copyHistory.addAll(typeOfCopyList);
147 public StatementContextBase<?, ?, ?> getOriginalCtx() {
152 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
153 this.originalCtx = originalCtx;
157 public void setOrder(final int order) {
162 public int getOrder() {
167 public ModelProcessingPhase getCompletedPhase() {
168 return completedPhase;
172 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
173 this.completedPhase = completedPhase;
176 StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) {
177 this.definition = builder.getDefinition();
178 this.identifier = builder.createIdentifier();
179 this.statementDeclSource = builder.getStamementSource();
180 this.completedPhase = null;
181 this.copyHistory.add(TypeOfCopy.ORIGINAL);
184 StatementContextBase(final StatementContextBase<A, D, E> original) {
185 this.definition = Preconditions.checkNotNull(original.definition,
186 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
187 this.identifier = Preconditions.checkNotNull(original.identifier,
188 "Statement context identifier cannot be null copying from: %s", original.getStatementSourceReference());
189 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
190 "Statement context statementDeclSource cannot be null copying from: %s",
191 original.getStatementSourceReference());
192 this.completedPhase = null;
193 this.copyHistory.add(TypeOfCopy.ORIGINAL);
197 * @return context of parent of statement
200 public abstract StatementContextBase<?, ?, ?> getParentContext();
203 * @return root context of statement
206 public abstract RootStatementContext<?, ?, ?> getRoot();
209 * @return statement identifier
212 public StatementIdentifier getIdentifier() {
217 * @return origin of statement
220 public StatementSource getStatementSource() {
221 return statementDeclSource.getStatementSource();
225 * @return reference of statement source
228 public StatementSourceReference getStatementSourceReference() {
229 return statementDeclSource;
233 * @return raw statement argument string
236 public String rawStatementArgument() {
237 return identifier.getArgument();
241 * @return collection of declared substatements
244 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
245 return Collections.unmodifiableCollection(declared);
249 * @return collection of substatements
252 public Collection<StatementContextBase<?, ?, ?>> substatements() {
253 return Collections.unmodifiableCollection(substatements.values());
257 * @return collection of effective substatements
260 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
261 return Collections.unmodifiableCollection(effective);
264 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
265 effective.removeAll(substatements);
268 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
269 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
270 while (iterator.hasNext()) {
271 final StatementContextBase<?, ?, ?> next = iterator.next();
272 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
279 * adds effective statement to collection of substatements
281 * @param substatement substatement
282 * @throws IllegalStateException
283 * if added in declared phase
284 * @throws NullPointerException
285 * if statement parameter is null
287 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
289 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
290 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
291 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
292 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
294 effective.add(Preconditions.checkNotNull(substatement,
295 "StatementContextBase effective substatement cannot be null at: %s", getStatementSourceReference()));
299 * adds declared statement to collection of substatements
301 * @param substatement substatement
302 * @throws IllegalStateException
303 * if added in effective phase
304 * @throws NullPointerException
305 * if statement parameter is null
307 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
309 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
310 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
311 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
313 declared.add(Preconditions.checkNotNull(substatement,
314 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
318 * builds new substatement from statement definition context and statement source reference
320 * @param def definition context
321 * @param ref source reference
323 * @return instance of ContextBuilder
325 @SuppressWarnings({ "rawtypes", "unchecked" })
326 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
327 final StatementSourceReference ref) {
328 return new ContextBuilder(def, ref) {
331 public StatementContextBase build() throws SourceException {
332 StatementContextBase<?, ?, ?> potential = null;
334 final StatementDefinition stmtDef = getDefinition().getPublicView();
335 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION
336 && stmtDef != Rfc6020Mapping.TYPE) {
337 potential = substatements.get(createIdentifier());
339 if (potential == null) {
340 potential = new SubstatementContext(StatementContextBase.this, this);
341 substatements.put(createIdentifier(), potential);
342 getDefinition().onStatementAdded(potential);
344 potential.resetLists();
345 switch (this.getStamementSource().getStatementSource()) {
347 addDeclaredSubstatement(potential);
350 addEffectiveSubstatement(potential);
359 * @return local namespace behaviour type {@link NamespaceBehaviour}
362 public StorageNodeType getStorageNodeType() {
363 return StorageNodeType.STATEMENT_LOCAL;
367 * builds {@link DeclaredStatement} for statement context
370 public D buildDeclared() {
371 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
372 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
373 if (declaredInstance == null) {
374 declaredInstance = definition().getFactory().createDeclared(this);
376 return declaredInstance;
380 * builds {@link EffectiveStatement} for statement context
383 public E buildEffective() {
384 if (effectiveInstance == null) {
385 effectiveInstance = definition().getFactory().createEffective(this);
387 return effectiveInstance;
391 * clears collection of declared substatements
393 * @throws IllegalStateException
394 * if invoked in effective build phase
398 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
399 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
400 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
406 * tries to execute current {@link ModelProcessingPhase} of source parsing
409 * to be executed (completed)
410 * @return if phase was successfully completed
411 * @throws SourceException
412 * when an error occured in source parsing
414 boolean tryToCompletePhase(final ModelProcessingPhase phase) {
415 final Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
416 boolean finished = true;
417 while (openMutations.hasNext()) {
418 final ContextMutation current = openMutations.next();
419 if (current.isFinished()) {
420 openMutations.remove();
425 for (final StatementContextBase<?, ?, ?> child : declared) {
426 finished &= child.tryToCompletePhase(phase);
428 for (final StatementContextBase<?, ?, ?> child : effective) {
429 finished &= child.tryToCompletePhase(phase);
433 onPhaseCompleted(phase);
440 * occurs on end of {@link ModelProcessingPhase} of source parsing
443 * that was to be completed (finished)
444 * @throws SourceException
445 * when an error occured in source parsing
447 private void onPhaseCompleted(final ModelProcessingPhase phase) {
448 completedPhase = phase;
449 final Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
450 while (listener.hasNext()) {
451 final OnPhaseFinished next = listener.next();
452 if (next.phaseFinished(this, phase)) {
459 * Ends declared section of current node.
462 * @throws SourceException
464 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) {
465 definition().onDeclarationFinished(this, phase);
469 * @return statement definition
471 protected final StatementDefinitionContext<A, D, E> definition() {
476 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
477 definition().checkNamespaceAllowed(type);
481 * occurs when an item is added to model namespace
483 * @throws SourceException instance of SourceException
486 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
487 // definition().onNamespaceElementAdded(this, type, key, value);
490 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
491 final OnNamespaceItemAdded listener) throws SourceException {
492 final Object potential = getFromNamespace(type, key);
493 if (potential != null) {
494 listener.namespaceItemAdded(this, type, key, potential);
497 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
498 if (behaviour instanceof NamespaceBehaviourWithListeners) {
499 final NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
500 casted.addValueListener(new ValueAddedListener<K>(this, key) {
502 void onValueAdded(final Object key, final Object value) {
504 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
505 } catch (final SourceException e) {
506 throw Throwables.propagate(e);
514 * @see StatementSupport#getPublicView()
517 public StatementDefinition getPublicDefinition() {
518 return definition().getPublicView();
522 * @return new {@link ModelActionBuilder} for the phase
525 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
526 return getRoot().getSourceContext().newInferenceAction(phase);
530 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
532 * @throws SourceException
534 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
536 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
537 getStatementSourceReference());
538 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
539 getStatementSourceReference());
541 ModelProcessingPhase finishedPhase = completedPhase;
542 while (finishedPhase != null) {
543 if (phase.equals(finishedPhase)) {
544 listener.phaseFinished(this, finishedPhase);
547 finishedPhase = finishedPhase.getPreviousPhase();
549 phaseListeners.put(phase, listener);
553 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
555 * @throws IllegalStateException
556 * when the mutation was registered after phase was completed
558 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
559 ModelProcessingPhase finishedPhase = completedPhase;
560 while (finishedPhase != null) {
561 if (phase.equals(finishedPhase)) {
562 throw new IllegalStateException("Mutation registered after phase was completed at: " +
563 getStatementSourceReference());
565 finishedPhase = finishedPhase.getPreviousPhase();
567 phaseMutation.put(phase, mutation);
571 * adds statement to namespace map with the key
574 * {@link StatementNamespace} child that determines namespace to be added to
576 * of type according to namespace class specification
578 * to be added to namespace map
581 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
582 final StmtContext<?, ?, ?> stmt) {
583 addContextToNamespace(namespace, (K) key, stmt);