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 java.util.LinkedList;
12 import java.util.List;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.HashMultimap;
16 import com.google.common.collect.Multimap;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.EventListener;
21 import java.util.Iterator;
22 import java.util.LinkedHashMap;
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 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value)
52 throws SourceException;
57 * event listener when a parsing {@link ModelProcessingPhase} is completed
59 interface OnPhaseFinished extends EventListener {
61 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase) throws SourceException;
66 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
68 interface ContextMutation {
74 private final StatementDefinitionContext<A, D, E> definition;
75 private final StatementIdentifier identifier;
76 private final StatementSourceReference statementDeclSource;
77 private int order = 0;
79 private Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>();
81 private Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>();
82 private Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>();
83 private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>();
85 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
86 return effectOfStatement;
89 public void addAsEffectOfStatement(StatementContextBase<?, ?, ?> ctx) {
90 effectOfStatement.add(ctx);
93 private ModelProcessingPhase completedPhase;
95 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = HashMultimap.create();
96 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = HashMultimap.create();
98 private D declaredInstance;
99 private E effectiveInstance;
101 private StatementContextBase<?, ?, ?> originalCtx;
102 private List<TypeOfCopy> copyHistory;
104 private boolean isSupportedToBuildEffective = true;
107 public boolean isSupportedToBuildEffective() {
108 return isSupportedToBuildEffective;
112 public void setIsSupportedToBuildEffective(boolean isSupportedToBuildEffective) {
113 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
117 public List<TypeOfCopy> getCopyHistory() {
122 public void addToCopyHistory(TypeOfCopy typeOfCopy) {
123 this.copyHistory.add(typeOfCopy);
127 public void addAllToCopyHistory(List<TypeOfCopy> typeOfCopyList) {
128 this.copyHistory.addAll(typeOfCopyList);
132 public StatementContextBase<?, ?, ?> getOriginalCtx() {
137 public void setOriginalCtx(StatementContextBase<?, ?, ?> originalCtx) {
138 this.originalCtx = originalCtx;
142 public void setOrder(int order) {
147 public int getOrder() {
152 public ModelProcessingPhase getCompletedPhase() {
153 return completedPhase;
157 public void setCompletedPhase(ModelProcessingPhase completedPhase) {
158 this.completedPhase = completedPhase;
161 StatementContextBase(@Nonnull 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;
169 StatementContextBase(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;
180 private void initCopyHistory() {
181 this.copyHistory = new LinkedList<>();
182 this.copyHistory.add(TypeOfCopy.ORIGINAL);
186 * @return context of parent of statement
189 public abstract StatementContextBase<?, ?, ?> getParentContext();
192 * @return root context of statement
195 public abstract RootStatementContext<?, ?, ?> getRoot();
198 * @return statement identifier
201 public StatementIdentifier getIdentifier() {
206 * @return origin of statement
209 public StatementSource getStatementSource() {
210 return statementDeclSource.getStatementSource();
214 * @return reference of statement source
217 public StatementSourceReference getStatementSourceReference() {
218 return statementDeclSource;
222 * @return raw statement argument string
225 public String rawStatementArgument() {
226 return identifier.getArgument();
230 * @return collection of declared substatements
233 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
234 return Collections.unmodifiableCollection(declared);
238 * @return collection of substatements
241 public Collection<StatementContextBase<?, ?, ?>> substatements() {
242 return Collections.unmodifiableCollection(substatements.values());
246 * @return collection of effective substatements
249 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
250 return Collections.unmodifiableCollection(effective);
253 public void removeStatementsFromEffectiveSubstatements(Collection<StatementContextBase<?, ?, ?>> substatements) {
254 effective.removeAll(substatements);
257 public void removeStatementFromEffectiveSubstatements(StatementDefinition refineSubstatementDef) {
258 Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
259 while (iterator.hasNext()) {
260 StatementContextBase<?, ?, ?> next = iterator.next();
261 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
268 * adds effective statement to collection of substatements
270 * @throws IllegalStateException
271 * if added in declared phase
272 * @throws NullPointerException
273 * if statement parameter is null
275 * @param substatement substatement
277 public void addEffectiveSubstatement(StatementContextBase<?, ?, ?> substatement) {
279 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
280 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
281 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
282 "Effective statement cannot be added in declared phase");
284 effective.add(Preconditions.checkNotNull(substatement,
285 "StatementContextBase effective substatement cannot be null"));
289 * adds declared statement to collection of substatements
291 * @throws IllegalStateException
292 * if added in effective phase
293 * @throws NullPointerException
294 * if statement parameter is null
296 * @param substatement substatement
298 public void addDeclaredSubstatement(StatementContextBase<?, ?, ?> substatement) {
300 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
301 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
302 "Declared statement cannot be added in effective phase");
304 declared.add(Preconditions.checkNotNull(substatement,
305 "StatementContextBase declared substatement cannot be null"));
309 * builds new substatement from statement definition context and statement source reference
311 * @param def definition context
312 * @param ref source reference
314 * @return instance of ContextBuilder
316 @SuppressWarnings({ "rawtypes", "unchecked" })
317 public ContextBuilder<?, ?, ?> substatementBuilder(StatementDefinitionContext<?, ?, ?> def,
318 StatementSourceReference ref) {
319 return new ContextBuilder(def, ref) {
322 public StatementContextBase build() throws SourceException {
323 StatementContextBase<?, ?, ?> potential = null;
325 if (getDefinition().getPublicView() != Rfc6020Mapping.AUGMENT) {
326 potential = substatements.get(createIdentifier());
328 if (potential == null) {
329 potential = new SubstatementContext(StatementContextBase.this, this);
330 substatements.put(createIdentifier(), potential);
331 getDefinition().onStatementAdded(potential);
333 potential.resetLists();
334 switch (this.getStamementSource().getStatementSource()) {
336 addDeclaredSubstatement(potential);
339 addEffectiveSubstatement(potential);
348 * @return local namespace behaviour type {@link NamespaceBehaviour}
351 public StorageNodeType getStorageNodeType() {
352 return StorageNodeType.STATEMENT_LOCAL;
356 * builds {@link DeclaredStatement} for statement context
359 public D buildDeclared() {
360 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
361 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
362 if (declaredInstance == null) {
363 declaredInstance = definition().getFactory().createDeclared(this);
365 return declaredInstance;
369 * builds {@link EffectiveStatement} for statement context
372 public E buildEffective() {
373 if (effectiveInstance == null) {
374 effectiveInstance = definition().getFactory().createEffective(this);
376 return effectiveInstance;
380 * clears collection of declared substatements
382 * @throws IllegalStateException
383 * if invoked in effective build phase
387 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
388 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
389 "Declared statements list cannot be cleared in effective phase");
395 * tries to execute current {@link ModelProcessingPhase} of source parsing
398 * to be executed (completed)
399 * @return if phase was successfully completed
400 * @throws SourceException
401 * when an error occured in source parsing
403 boolean tryToCompletePhase(ModelProcessingPhase phase) throws SourceException {
404 Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
405 boolean finished = true;
406 while (openMutations.hasNext()) {
407 ContextMutation current = openMutations.next();
408 if (current.isFinished()) {
409 openMutations.remove();
414 for (StatementContextBase<?, ?, ?> child : declared) {
415 finished &= child.tryToCompletePhase(phase);
417 for (StatementContextBase<?, ?, ?> child : effective) {
418 finished &= child.tryToCompletePhase(phase);
422 onPhaseCompleted(phase);
429 * occurs on end of {@link ModelProcessingPhase} of source parsing
432 * that was to be completed (finished)
433 * @throws SourceException
434 * when an error occured in source parsing
436 private void onPhaseCompleted(ModelProcessingPhase phase) throws SourceException {
437 completedPhase = phase;
438 Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
439 while (listener.hasNext()) {
440 OnPhaseFinished next = listener.next();
441 if (next.phaseFinished(this, phase)) {
448 * Ends declared section of current node.
451 * @throws SourceException
453 void endDeclared(StatementSourceReference ref, ModelProcessingPhase phase) throws SourceException {
454 definition().onDeclarationFinished(this, phase);
458 * @return statement definition
460 protected final StatementDefinitionContext<A, D, E> definition() {
465 protected void checkLocalNamespaceAllowed(Class<? extends IdentifierNamespace<?, ?>> type) {
466 definition().checkNamespaceAllowed(type);
470 * occurs when an item is added to model namespace
472 * @throws SourceException instance of SourceException
475 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(Class<N> type, K key, V value) {
476 // definition().onNamespaceElementAdded(this, type, key, value);
479 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, K key,
480 final OnNamespaceItemAdded listener) throws SourceException {
481 Object potential = getFromNamespace(type, key);
482 if (potential != null) {
483 listener.namespaceItemAdded(this, type, key, potential);
486 NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
487 if (behaviour instanceof NamespaceBehaviourWithListeners) {
488 NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
489 casted.addValueListener(key, new ValueAddedListener(this) {
491 void onValueAdded(Object key, Object value) {
493 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
494 } catch (SourceException e) {
495 throw Throwables.propagate(e);
503 * @see StatementSupport#getPublicView()
506 public StatementDefinition getPublicDefinition() {
507 return definition().getPublicView();
511 * @return new {@link ModelActionBuilder} for the phase
514 public ModelActionBuilder newInferenceAction(ModelProcessingPhase phase) {
515 return getRoot().getSourceContext().newInferenceAction(phase);
519 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
521 * @throws SourceException
523 void addPhaseCompletedListener(ModelProcessingPhase phase, OnPhaseFinished listener) throws SourceException {
525 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null");
526 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null");
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(ModelProcessingPhase phase, 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.");
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(Class<N> namespace, KT key,
568 StmtContext<?, ?, ?> stmt) {
569 addContextToNamespace(namespace, (K) key, stmt);