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 && stmtDef != Rfc6020Mapping.TYPE) {
324 potential = substatements.get(createIdentifier());
326 if (potential == null) {
327 potential = new SubstatementContext(StatementContextBase.this, this);
328 substatements.put(createIdentifier(), potential);
329 getDefinition().onStatementAdded(potential);
331 potential.resetLists();
332 switch (this.getStamementSource().getStatementSource()) {
334 addDeclaredSubstatement(potential);
337 addEffectiveSubstatement(potential);
346 * @return local namespace behaviour type {@link NamespaceBehaviour}
349 public StorageNodeType getStorageNodeType() {
350 return StorageNodeType.STATEMENT_LOCAL;
354 * builds {@link DeclaredStatement} for statement context
357 public D buildDeclared() {
358 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
359 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
360 if (declaredInstance == null) {
361 declaredInstance = definition().getFactory().createDeclared(this);
363 return declaredInstance;
367 * builds {@link EffectiveStatement} for statement context
370 public E buildEffective() {
371 if (effectiveInstance == null) {
372 effectiveInstance = definition().getFactory().createEffective(this);
374 return effectiveInstance;
378 * clears collection of declared substatements
380 * @throws IllegalStateException
381 * if invoked in effective build phase
385 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
386 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
387 "Declared statements list cannot be cleared in effective phase at: %s", getStatementSourceReference());
393 * tries to execute current {@link ModelProcessingPhase} of source parsing
396 * to be executed (completed)
397 * @return if phase was successfully completed
398 * @throws SourceException
399 * when an error occured in source parsing
401 boolean tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
402 Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
403 boolean finished = true;
404 while (openMutations.hasNext()) {
405 ContextMutation current = openMutations.next();
406 if (current.isFinished()) {
407 openMutations.remove();
412 for (StatementContextBase<?, ?, ?> child : declared) {
413 finished &= child.tryToCompletePhase(phase);
415 for (StatementContextBase<?, ?, ?> child : effective) {
416 finished &= child.tryToCompletePhase(phase);
420 onPhaseCompleted(phase);
427 * occurs on end of {@link ModelProcessingPhase} of source parsing
430 * that was to be completed (finished)
431 * @throws SourceException
432 * when an error occured in source parsing
434 private void onPhaseCompleted(final ModelProcessingPhase phase) throws SourceException {
435 completedPhase = phase;
436 Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
437 while (listener.hasNext()) {
438 OnPhaseFinished next = listener.next();
439 if (next.phaseFinished(this, phase)) {
446 * Ends declared section of current node.
449 * @throws SourceException
451 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) throws SourceException {
452 definition().onDeclarationFinished(this, phase);
456 * @return statement definition
458 protected final StatementDefinitionContext<A, D, E> definition() {
463 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
464 definition().checkNamespaceAllowed(type);
468 * occurs when an item is added to model namespace
470 * @throws SourceException instance of SourceException
473 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
474 // definition().onNamespaceElementAdded(this, type, key, value);
477 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
478 final OnNamespaceItemAdded listener) throws SourceException {
479 Object potential = getFromNamespace(type, key);
480 if (potential != null) {
481 listener.namespaceItemAdded(this, type, key, potential);
484 NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
485 if (behaviour instanceof NamespaceBehaviourWithListeners) {
486 NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
487 casted.addValueListener(new ValueAddedListener<K>(this, key) {
489 void onValueAdded(final Object key, final Object value) {
491 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
492 } catch (SourceException e) {
493 throw Throwables.propagate(e);
501 * @see StatementSupport#getPublicView()
504 public StatementDefinition getPublicDefinition() {
505 return definition().getPublicView();
509 * @return new {@link ModelActionBuilder} for the phase
512 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
513 return getRoot().getSourceContext().newInferenceAction(phase);
517 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
519 * @throws SourceException
521 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) throws SourceException {
523 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null at: %s",
524 getStatementSourceReference());
525 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null at: %s",
526 getStatementSourceReference());
528 ModelProcessingPhase finishedPhase = completedPhase;
529 while (finishedPhase != null) {
530 if (phase.equals(finishedPhase)) {
531 listener.phaseFinished(this, finishedPhase);
534 finishedPhase = finishedPhase.getPreviousPhase();
536 phaseListeners.put(phase, listener);
540 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
542 * @throws IllegalStateException
543 * when the mutation was registered after phase was completed
545 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
546 ModelProcessingPhase finishedPhase = completedPhase;
547 while (finishedPhase != null) {
548 if (phase.equals(finishedPhase)) {
549 throw new IllegalStateException("Mutation registered after phase was completed at: " +
550 getStatementSourceReference());
552 finishedPhase = finishedPhase.getPreviousPhase();
554 phaseMutation.put(phase, mutation);
558 * adds statement to namespace map with the key
561 * {@link StatementNamespace} child that determines namespace to be added to
563 * of type according to namespace class specification
565 * to be added to namespace map
568 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
569 final StmtContext<?, ?, ?> stmt) {
570 addContextToNamespace(namespace, (K) key, stmt);