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
171 .checkNotNull(original.definition, "Statement context definition cannot be null");
172 this.identifier = Preconditions
173 .checkNotNull(original.identifier, "Statement context identifier cannot be null");
174 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
175 "Statement context statementDeclSource cannot be null");
176 this.completedPhase = null;
177 this.copyHistory.add(TypeOfCopy.ORIGINAL);
181 * @return context of parent of statement
184 public abstract StatementContextBase<?, ?, ?> getParentContext();
187 * @return root context of statement
190 public abstract RootStatementContext<?, ?, ?> getRoot();
193 * @return statement identifier
196 public StatementIdentifier getIdentifier() {
201 * @return origin of statement
204 public StatementSource getStatementSource() {
205 return statementDeclSource.getStatementSource();
209 * @return reference of statement source
212 public StatementSourceReference getStatementSourceReference() {
213 return statementDeclSource;
217 * @return raw statement argument string
220 public String rawStatementArgument() {
221 return identifier.getArgument();
225 * @return collection of declared substatements
228 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
229 return Collections.unmodifiableCollection(declared);
233 * @return collection of substatements
236 public Collection<StatementContextBase<?, ?, ?>> substatements() {
237 return Collections.unmodifiableCollection(substatements.values());
241 * @return collection of effective substatements
244 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
245 return Collections.unmodifiableCollection(effective);
248 public void removeStatementsFromEffectiveSubstatements(final Collection<StatementContextBase<?, ?, ?>> substatements) {
249 effective.removeAll(substatements);
252 public void removeStatementFromEffectiveSubstatements(final StatementDefinition refineSubstatementDef) {
253 Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
254 while (iterator.hasNext()) {
255 StatementContextBase<?, ?, ?> next = iterator.next();
256 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
263 * adds effective statement to collection of substatements
265 * @throws IllegalStateException
266 * if added in declared phase
267 * @throws NullPointerException
268 * if statement parameter is null
270 * @param substatement substatement
272 public void addEffectiveSubstatement(final StatementContextBase<?, ?, ?> substatement) {
274 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
275 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
276 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
277 "Effective statement cannot be added in declared phase");
279 effective.add(Preconditions.checkNotNull(substatement,
280 "StatementContextBase effective substatement cannot be null"));
284 * adds declared statement to collection of substatements
286 * @throws IllegalStateException
287 * if added in effective phase
288 * @throws NullPointerException
289 * if statement parameter is null
291 * @param substatement substatement
293 public void addDeclaredSubstatement(final StatementContextBase<?, ?, ?> substatement) {
295 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
296 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
297 "Declared statement cannot be added in effective phase");
299 declared.add(Preconditions.checkNotNull(substatement,
300 "StatementContextBase declared substatement cannot be null"));
304 * builds new substatement from statement definition context and statement source reference
306 * @param def definition context
307 * @param ref source reference
309 * @return instance of ContextBuilder
311 @SuppressWarnings({ "rawtypes", "unchecked" })
312 public ContextBuilder<?, ?, ?> substatementBuilder(final StatementDefinitionContext<?, ?, ?> def,
313 final StatementSourceReference ref) {
314 return new ContextBuilder(def, ref) {
317 public StatementContextBase build() throws SourceException {
318 StatementContextBase<?, ?, ?> potential = null;
320 StatementDefinition stmtDef = getDefinition().getPublicView();
321 if (stmtDef != Rfc6020Mapping.AUGMENT && stmtDef != Rfc6020Mapping.DEVIATION) {
322 potential = substatements.get(createIdentifier());
324 if (potential == null) {
325 potential = new SubstatementContext(StatementContextBase.this, this);
326 substatements.put(createIdentifier(), potential);
327 getDefinition().onStatementAdded(potential);
329 potential.resetLists();
330 switch (this.getStamementSource().getStatementSource()) {
332 addDeclaredSubstatement(potential);
335 addEffectiveSubstatement(potential);
344 * @return local namespace behaviour type {@link NamespaceBehaviour}
347 public StorageNodeType getStorageNodeType() {
348 return StorageNodeType.STATEMENT_LOCAL;
352 * builds {@link DeclaredStatement} for statement context
355 public D buildDeclared() {
356 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
357 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
358 if (declaredInstance == null) {
359 declaredInstance = definition().getFactory().createDeclared(this);
361 return declaredInstance;
365 * builds {@link EffectiveStatement} for statement context
368 public E buildEffective() {
369 if (effectiveInstance == null) {
370 effectiveInstance = definition().getFactory().createEffective(this);
372 return effectiveInstance;
376 * clears collection of declared substatements
378 * @throws IllegalStateException
379 * if invoked in effective build phase
383 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
384 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
385 "Declared statements list cannot be cleared in effective phase");
391 * tries to execute current {@link ModelProcessingPhase} of source parsing
394 * to be executed (completed)
395 * @return if phase was successfully completed
396 * @throws SourceException
397 * when an error occured in source parsing
399 boolean tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
400 Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
401 boolean finished = true;
402 while (openMutations.hasNext()) {
403 ContextMutation current = openMutations.next();
404 if (current.isFinished()) {
405 openMutations.remove();
410 for (StatementContextBase<?, ?, ?> child : declared) {
411 finished &= child.tryToCompletePhase(phase);
413 for (StatementContextBase<?, ?, ?> child : effective) {
414 finished &= child.tryToCompletePhase(phase);
418 onPhaseCompleted(phase);
425 * occurs on end of {@link ModelProcessingPhase} of source parsing
428 * that was to be completed (finished)
429 * @throws SourceException
430 * when an error occured in source parsing
432 private void onPhaseCompleted(final ModelProcessingPhase phase) throws SourceException {
433 completedPhase = phase;
434 Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
435 while (listener.hasNext()) {
436 OnPhaseFinished next = listener.next();
437 if (next.phaseFinished(this, phase)) {
444 * Ends declared section of current node.
447 * @throws SourceException
449 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) throws SourceException {
450 definition().onDeclarationFinished(this, phase);
454 * @return statement definition
456 protected final StatementDefinitionContext<A, D, E> definition() {
461 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
462 definition().checkNamespaceAllowed(type);
466 * occurs when an item is added to model namespace
468 * @throws SourceException instance of SourceException
471 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
472 // definition().onNamespaceElementAdded(this, type, key, value);
475 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
476 final OnNamespaceItemAdded listener) throws SourceException {
477 Object potential = getFromNamespace(type, key);
478 if (potential != null) {
479 listener.namespaceItemAdded(this, type, key, potential);
482 NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
483 if (behaviour instanceof NamespaceBehaviourWithListeners) {
484 NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
485 casted.addValueListener(new ValueAddedListener<K>(this, key) {
487 void onValueAdded(final Object key, final Object value) {
489 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
490 } catch (SourceException e) {
491 throw Throwables.propagate(e);
499 * @see StatementSupport#getPublicView()
502 public StatementDefinition getPublicDefinition() {
503 return definition().getPublicView();
507 * @return new {@link ModelActionBuilder} for the phase
510 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
511 return getRoot().getSourceContext().newInferenceAction(phase);
515 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
517 * @throws SourceException
519 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) throws SourceException {
521 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null");
522 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null");
524 ModelProcessingPhase finishedPhase = completedPhase;
525 while (finishedPhase != null) {
526 if (phase.equals(finishedPhase)) {
527 listener.phaseFinished(this, finishedPhase);
530 finishedPhase = finishedPhase.getPreviousPhase();
532 phaseListeners.put(phase, listener);
536 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
538 * @throws IllegalStateException
539 * when the mutation was registered after phase was completed
541 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
542 ModelProcessingPhase finishedPhase = completedPhase;
543 while (finishedPhase != null) {
544 if (phase.equals(finishedPhase)) {
545 throw new IllegalStateException("Mutation registered after phase was completed.");
547 finishedPhase = finishedPhase.getPreviousPhase();
549 phaseMutation.put(phase, mutation);
553 * adds statement to namespace map with the key
556 * {@link StatementNamespace} child that determines namespace to be added to
558 * of type according to namespace class specification
560 * to be added to namespace map
563 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
564 final StmtContext<?, ?, ?> stmt) {
565 addContextToNamespace(namespace, (K) key, stmt);