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.HashMultimap;
13 import com.google.common.collect.Multimap;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.EventListener;
18 import java.util.Iterator;
19 import java.util.LinkedHashMap;
20 import java.util.List;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.yangtools.concepts.Identifiable;
24 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
37 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
38 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
39 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.ValueAddedListener;
41 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
42 extends NamespaceStorageSupport implements StmtContext.Mutable<A, D, E>, Identifiable<StatementIdentifier> {
45 * event listener when an item is added to model namespace
47 interface OnNamespaceItemAdded extends EventListener {
49 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value)
50 throws SourceException;
55 * event listener when a parsing {@link ModelProcessingPhase} is completed
57 interface OnPhaseFinished extends EventListener {
59 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase) throws SourceException;
64 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
66 interface ContextMutation {
72 private final StatementDefinitionContext<A, D, E> definition;
73 private final StatementIdentifier identifier;
74 private final StatementSourceReference statementDeclSource;
75 private int order = 0;
77 private final Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>();
79 private final Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>();
80 private final Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>();
81 private final Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>();
84 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
85 return effectOfStatement;
89 public void addAsEffectOfStatement(final StatementContextBase<?, ?, ?> ctx) {
90 effectOfStatement.add(ctx);
93 private ModelProcessingPhase completedPhase;
95 private final Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = HashMultimap.create();
96 private final Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = HashMultimap.create();
98 private D declaredInstance;
99 private E effectiveInstance;
101 private StatementContextBase<?, ?, ?> originalCtx;
102 private final List<TypeOfCopy> copyHistory = new ArrayList<>(1);
104 private boolean isSupportedToBuildEffective = true;
107 public boolean isSupportedToBuildEffective() {
108 return isSupportedToBuildEffective;
112 public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
113 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
117 public List<TypeOfCopy> getCopyHistory() {
122 public void addToCopyHistory(final TypeOfCopy typeOfCopy) {
123 this.copyHistory.add(typeOfCopy);
127 public void addAllToCopyHistory(final List<TypeOfCopy> typeOfCopyList) {
128 this.copyHistory.addAll(typeOfCopyList);
132 public StatementContextBase<?, ?, ?> getOriginalCtx() {
137 public void setOriginalCtx(final StatementContextBase<?, ?, ?> originalCtx) {
138 this.originalCtx = originalCtx;
142 public void setOrder(final int order) {
147 public int getOrder() {
152 public ModelProcessingPhase getCompletedPhase() {
153 return completedPhase;
157 public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
158 this.completedPhase = completedPhase;
161 StatementContextBase(@Nonnull final ContextBuilder<A, D, E> builder) throws SourceException {
162 this.definition = builder.getDefinition();
163 this.identifier = builder.createIdentifier();
164 this.statementDeclSource = builder.getStamementSource();
165 this.completedPhase = null;
166 this.copyHistory.add(TypeOfCopy.ORIGINAL);
169 StatementContextBase(final StatementContextBase<A, D, E> original) {
170 this.definition = Preconditions.checkNotNull(original.definition,
171 "Statement context definition cannot be null copying from: %s", original.getStatementSourceReference());
172 this.identifier = Preconditions.checkNotNull(original.identifier,
173 "Statement context identifier cannot be null copying from: %s", original.getStatementSourceReference());
174 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
175 "Statement context statementDeclSource cannot be null copying from: %s",
176 original.getStatementSourceReference());
177 this.completedPhase = null;
178 this.copyHistory.add(TypeOfCopy.ORIGINAL);
182 * @return context of parent of statement
185 public abstract StatementContextBase<?, ?, ?> getParentContext();
188 * @return root context of statement
191 public abstract RootStatementContext<?, ?, ?> getRoot();
194 * @return statement identifier
197 public StatementIdentifier getIdentifier() {
202 * @return origin of statement
205 public StatementSource getStatementSource() {
206 return statementDeclSource.getStatementSource();
210 * @return reference of statement source
213 public StatementSourceReference getStatementSourceReference() {
214 return statementDeclSource;
218 * @return raw statement argument string
221 public String rawStatementArgument() {
222 return identifier.getArgument();
226 * @return collection of declared substatements
229 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
230 return Collections.unmodifiableCollection(declared);
234 * @return collection of substatements
237 public Collection<StatementContextBase<?, ?, ?>> substatements() {
238 return Collections.unmodifiableCollection(substatements.values());
242 * @return collection of effective substatements
245 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
246 return Collections.unmodifiableCollection(effective);
249 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
250 effective.removeAll(substatements);
253 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
254 Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
255 while (iterator.hasNext()) {
256 StatementContextBase<?, ?, ?> next = iterator.next();
257 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
264 * adds effective statement to collection of substatements
266 * @throws IllegalStateException
267 * if added in declared phase
268 * @throws NullPointerException
269 * if statement parameter is null
271 * @param substatement substatement
273 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
275 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
276 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
277 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
278 "Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
280 effective.add(Preconditions.checkNotNull(substatement,
281 "StatementContextBase effective substatement cannot be null at: %s", getStatementSourceReference()));
285 * adds declared statement to collection of substatements
287 * @throws IllegalStateException
288 * if added in effective phase
289 * @throws NullPointerException
290 * if statement parameter is null
292 * @param substatement substatement
294 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
296 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
297 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
298 "Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
300 declared.add(Preconditions.checkNotNull(substatement,
301 "StatementContextBase declared substatement cannot be null at: %s", getStatementSourceReference()));
305 * builds new substatement from statement definition context and statement source reference
307 * @param def definition context
308 * @param ref source reference
310 * @return instance of ContextBuilder
312 @SuppressWarnings({ "rawtypes", "unchecked" })
313 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
314 final StatementSourceReference ref) {
315 return new ContextBuilder(def, ref) {
318 public StatementContextBase build() throws SourceException {
319 StatementContextBase<?, ?, ?> potential = null;
321 StatementDefinition stmtDef = getDefinition().getPublicView();
322 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION) {
323 potential = substatements.get(createIdentifier());
325 if (potential == null) {
326 potential = new SubstatementContext(StatementContextBase.this, this);
327 substatements.put(createIdentifier(), potential);
328 getDefinition().onStatementAdded(potential);
330 potential.resetLists();
331 switch (this.getStamementSource().getStatementSource()) {
333 addDeclaredSubstatement(potential);
336 addEffectiveSubstatement(potential);
345 * @return local namespace behaviour type {@link NamespaceBehaviour}
348 public StorageNodeType getStorageNodeType() {
349 return StorageNodeType.STATEMENT_LOCAL;
353 * builds {@link DeclaredStatement} for statement context
356 public D buildDeclared() {
357 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
358 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
359 if (declaredInstance == null) {
360 declaredInstance = definition().getFactory().createDeclared(this);
362 return declaredInstance;
366 * builds {@link EffectiveStatement} for statement context
369 public E buildEffective() {
370 if (effectiveInstance == null) {
371 effectiveInstance = definition().getFactory().createEffective(this);
373 return effectiveInstance;
377 * clears collection of declared substatements
379 * @throws IllegalStateException
380 * if invoked in effective build phase
384 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
385 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
386 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
392 * tries to execute current {@link ModelProcessingPhase} of source parsing
395 * to be executed (completed)
396 * @return if phase was successfully completed
397 * @throws SourceException
398 * when an error occured in source parsing
400 boolean tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
401 Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
402 boolean finished = true;
403 while (openMutations.hasNext()) {
404 ContextMutation current = openMutations.next();
405 if (current.isFinished()) {
406 openMutations.remove();
411 for (StatementContextBase<?, ?, ?> child : declared) {
412 finished &= child.tryToCompletePhase(phase);
414 for (StatementContextBase<?, ?, ?> child : effective) {
415 finished &= child.tryToCompletePhase(phase);
419 onPhaseCompleted(phase);
426 * occurs on end of {@link ModelProcessingPhase} of source parsing
429 * that was to be completed (finished)
430 * @throws SourceException
431 * when an error occured in source parsing
433 private void onPhaseCompleted(final ModelProcessingPhase phase) throws SourceException {
434 completedPhase = phase;
435 Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
436 while (listener.hasNext()) {
437 OnPhaseFinished next = listener.next();
438 if (next.phaseFinished(this, phase)) {
445 * Ends declared section of current node.
448 * @throws SourceException
450 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) throws SourceException {
451 definition().onDeclarationFinished(this, phase);
455 * @return statement definition
457 protected final StatementDefinitionContext<A, D, E> definition() {
462 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
463 definition().checkNamespaceAllowed(type);
467 * occurs when an item is added to model namespace
469 * @throws SourceException instance of SourceException
472 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
473 // definition().onNamespaceElementAdded(this, type, key, value);
476 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
477 final OnNamespaceItemAdded listener) throws SourceException {
478 Object potential = getFromNamespace(type, key);
479 if (potential != null) {
480 listener.namespaceItemAdded(this, type, key, potential);
483 NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
484 if (behaviour instanceof NamespaceBehaviourWithListeners) {
485 NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
486 casted.addValueListener(new ValueAddedListener<K>(this, key) {
488 void onValueAdded(final Object key, final Object value) {
490 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
491 } catch (SourceException e) {
492 throw Throwables.propagate(e);
500 * @see StatementSupport#getPublicView()
503 public StatementDefinition getPublicDefinition() {
504 return definition().getPublicView();
508 * @return new {@link ModelActionBuilder} for the phase
511 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
512 return getRoot().getSourceContext().newInferenceAction(phase);
516 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
518 * @throws SourceException
520 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) throws SourceException {
522 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
523 getStatementSourceReference());
524 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
525 getStatementSourceReference());
527 ModelProcessingPhase finishedPhase = completedPhase;
528 while (finishedPhase != null) {
529 if (phase.equals(finishedPhase)) {
530 listener.phaseFinished(this, finishedPhase);
533 finishedPhase = finishedPhase.getPreviousPhase();
535 phaseListeners.put(phase, listener);
539 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
541 * @throws IllegalStateException
542 * when the mutation was registered after phase was completed
544 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
545 ModelProcessingPhase finishedPhase = completedPhase;
546 while (finishedPhase != null) {
547 if (phase.equals(finishedPhase)) {
548 throw new IllegalStateException("Mutation registered after phase was completed at: " +
549 getStatementSourceReference());
551 finishedPhase = finishedPhase.getPreviousPhase();
553 phaseMutation.put(phase, mutation);
557 * adds statement to namespace map with the key
560 * {@link StatementNamespace} child that determines namespace to be added to
562 * of type according to namespace class specification
564 * to be added to namespace map
567 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
568 final StmtContext<?, ?, ?> stmt) {
569 addContextToNamespace(namespace, (K) key, stmt);