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.LinkedList;
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 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value)
51 throws SourceException;
56 * event listener when a parsing {@link ModelProcessingPhase} is completed
58 interface OnPhaseFinished extends EventListener {
60 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase phase) throws SourceException;
65 * interface for all mutations within an {@link ModelActionBuilder.InferenceAction}
67 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 Map<StatementIdentifier, StatementContextBase<?, ?, ?>> substatements = new LinkedHashMap<>();
80 private Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>();
81 private Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>();
82 private Collection<StatementContextBase<?, ?, ?>> effectOfStatement = new ArrayList<>();
84 public Collection<StatementContextBase<?, ?, ?>> getEffectOfStatement() {
85 return effectOfStatement;
88 public void addAsEffectOfStatement(StatementContextBase<?, ?, ?> ctx) {
89 effectOfStatement.add(ctx);
92 private ModelProcessingPhase completedPhase;
94 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = HashMultimap.create();
95 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = HashMultimap.create();
97 private D declaredInstance;
98 private E effectiveInstance;
100 private StatementContextBase<?, ?, ?> originalCtx;
101 private List<TypeOfCopy> copyHistory;
103 private boolean isSupportedToBuildEffective = true;
106 public boolean isSupportedToBuildEffective() {
107 return isSupportedToBuildEffective;
111 public void setIsSupportedToBuildEffective(boolean isSupportedToBuildEffective) {
112 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
116 public List<TypeOfCopy> getCopyHistory() {
121 public void addToCopyHistory(TypeOfCopy typeOfCopy) {
122 this.copyHistory.add(typeOfCopy);
126 public void addAllToCopyHistory(List<TypeOfCopy> typeOfCopyList) {
127 this.copyHistory.addAll(typeOfCopyList);
131 public StatementContextBase<?, ?, ?> getOriginalCtx() {
136 public void setOriginalCtx(StatementContextBase<?, ?, ?> originalCtx) {
137 this.originalCtx = originalCtx;
141 public void setOrder(int order) {
146 public int getOrder() {
151 public ModelProcessingPhase getCompletedPhase() {
152 return completedPhase;
156 public void setCompletedPhase(ModelProcessingPhase completedPhase) {
157 this.completedPhase = completedPhase;
160 StatementContextBase(@Nonnull ContextBuilder<A, D, E> builder) throws SourceException {
161 this.definition = builder.getDefinition();
162 this.identifier = builder.createIdentifier();
163 this.statementDeclSource = builder.getStamementSource();
164 this.completedPhase = null;
168 StatementContextBase(StatementContextBase<A, D, E> original) {
169 this.definition = Preconditions
170 .checkNotNull(original.definition, "Statement context definition cannot be null");
171 this.identifier = Preconditions
172 .checkNotNull(original.identifier, "Statement context identifier cannot be null");
173 this.statementDeclSource = Preconditions.checkNotNull(original.statementDeclSource,
174 "Statement context statementDeclSource cannot be null");
175 this.completedPhase = null;
179 private void initCopyHistory() {
180 this.copyHistory = new LinkedList<>();
181 this.copyHistory.add(TypeOfCopy.ORIGINAL);
185 * @return context of parent of statement
188 public abstract StatementContextBase<?, ?, ?> getParentContext();
191 * @return root context of statement
194 public abstract RootStatementContext<?, ?, ?> getRoot();
197 * @return statement identifier
200 public StatementIdentifier getIdentifier() {
205 * @return origin of statement
208 public StatementSource getStatementSource() {
209 return statementDeclSource.getStatementSource();
213 * @return reference of statement source
216 public StatementSourceReference getStatementSourceReference() {
217 return statementDeclSource;
221 * @return raw statement argument string
224 public String rawStatementArgument() {
225 return identifier.getArgument();
229 * @return collection of declared substatements
232 public Collection<StatementContextBase<?, ?, ?>> declaredSubstatements() {
233 return Collections.unmodifiableCollection(declared);
237 * @return collection of substatements
240 public Collection<StatementContextBase<?, ?, ?>> substatements() {
241 return Collections.unmodifiableCollection(substatements.values());
245 * @return collection of effective substatements
248 public Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements() {
249 return Collections.unmodifiableCollection(effective);
252 public void removeStatementsFromEffectiveSubstatements(Collection<StatementContextBase<?, ?, ?>> substatements) {
253 effective.removeAll(substatements);
256 public void removeStatementFromEffectiveSubstatements(StatementDefinition refineSubstatementDef) {
257 Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
258 while (iterator.hasNext()) {
259 StatementContextBase<?, ?, ?> next = iterator.next();
260 if (next.getPublicDefinition().equals(refineSubstatementDef)) {
267 * adds effective statement to collection of substatements
269 * @throws IllegalStateException
270 * if added in declared phase
271 * @throws NullPointerException
272 * if statement parameter is null
274 * @param substatement substatement
276 public void addEffectiveSubstatement(StatementContextBase<?, ?, ?> substatement) {
278 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
279 Preconditions.checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
280 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
281 "Effective statement cannot be added in declared phase");
283 effective.add(Preconditions.checkNotNull(substatement,
284 "StatementContextBase effective substatement cannot be null"));
288 * adds declared statement to collection of substatements
290 * @throws IllegalStateException
291 * if added in effective phase
292 * @throws NullPointerException
293 * if statement parameter is null
295 * @param substatement substatement
297 public void addDeclaredSubstatement(StatementContextBase<?, ?, ?> substatement) {
299 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
300 Preconditions.checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
301 "Declared statement cannot be added in effective phase");
303 declared.add(Preconditions.checkNotNull(substatement,
304 "StatementContextBase declared substatement cannot be null"));
308 * builds new substatement from statement definition context and statement source reference
310 * @param def definition context
311 * @param ref source reference
313 * @return instance of ContextBuilder
315 @SuppressWarnings({ "rawtypes", "unchecked" })
316 public ContextBuilder<?, ?, ?> substatementBuilder(StatementDefinitionContext<?, ?, ?> def,
317 StatementSourceReference ref) {
318 return new ContextBuilder(def, ref) {
321 public StatementContextBase build() throws SourceException {
322 StatementContextBase<?, ?, ?> potential = null;
324 if (getDefinition().getPublicView() != Rfc6020Mapping.AUGMENT) {
325 potential = substatements.get(createIdentifier());
327 if (potential == null) {
328 potential = new SubstatementContext(StatementContextBase.this, this);
329 substatements.put(createIdentifier(), potential);
330 getDefinition().onStatementAdded(potential);
332 potential.resetLists();
333 switch (this.getStamementSource().getStatementSource()) {
335 addDeclaredSubstatement(potential);
338 addEffectiveSubstatement(potential);
347 * @return local namespace behaviour type {@link NamespaceBehaviour}
350 public StorageNodeType getStorageNodeType() {
351 return StorageNodeType.STATEMENT_LOCAL;
355 * builds {@link DeclaredStatement} for statement context
358 public D buildDeclared() {
359 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
360 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
361 if (declaredInstance == null) {
362 declaredInstance = definition().getFactory().createDeclared(this);
364 return declaredInstance;
368 * builds {@link EffectiveStatement} for statement context
371 public E buildEffective() {
372 if (effectiveInstance == null) {
373 effectiveInstance = definition().getFactory().createEffective(this);
375 return effectiveInstance;
379 * clears collection of declared substatements
381 * @throws IllegalStateException
382 * if invoked in effective build phase
386 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
387 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
388 "Declared statements list cannot be cleared in effective phase");
394 * tries to execute current {@link ModelProcessingPhase} of source parsing
397 * to be executed (completed)
398 * @return if phase was successfully completed
399 * @throws SourceException
400 * when an error occured in source parsing
402 boolean tryToCompletePhase(ModelProcessingPhase phase) throws SourceException {
403 Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
404 boolean finished = true;
405 while (openMutations.hasNext()) {
406 ContextMutation current = openMutations.next();
407 if (current.isFinished()) {
408 openMutations.remove();
413 for (StatementContextBase<?, ?, ?> child : declared) {
414 finished &= child.tryToCompletePhase(phase);
416 for (StatementContextBase<?, ?, ?> child : effective) {
417 finished &= child.tryToCompletePhase(phase);
421 onPhaseCompleted(phase);
428 * occurs on end of {@link ModelProcessingPhase} of source parsing
431 * that was to be completed (finished)
432 * @throws SourceException
433 * when an error occured in source parsing
435 private void onPhaseCompleted(ModelProcessingPhase phase) throws SourceException {
436 completedPhase = phase;
437 Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
438 while (listener.hasNext()) {
439 OnPhaseFinished next = listener.next();
440 if (next.phaseFinished(this, phase)) {
447 * Ends declared section of current node.
450 * @throws SourceException
452 void endDeclared(StatementSourceReference ref, ModelProcessingPhase phase) throws SourceException {
453 definition().onDeclarationFinished(this, phase);
457 * @return statement definition
459 protected final StatementDefinitionContext<A, D, E> definition() {
464 protected void checkLocalNamespaceAllowed(Class<? extends IdentifierNamespace<?, ?>> type) {
465 definition().checkNamespaceAllowed(type);
469 * occurs when an item is added to model namespace
471 * @throws SourceException instance of SourceException
474 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(Class<N> type, K key, V value) {
475 // definition().onNamespaceElementAdded(this, type, key, value);
478 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, K key,
479 final OnNamespaceItemAdded listener) throws SourceException {
480 Object potential = getFromNamespace(type, key);
481 if (potential != null) {
482 listener.namespaceItemAdded(this, type, key, potential);
485 NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
486 if (behaviour instanceof NamespaceBehaviourWithListeners) {
487 NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
488 casted.addValueListener(new ValueAddedListener<K>(this, key) {
490 void onValueAdded(Object key, Object value) {
492 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
493 } catch (SourceException e) {
494 throw Throwables.propagate(e);
502 * @see StatementSupport#getPublicView()
505 public StatementDefinition getPublicDefinition() {
506 return definition().getPublicView();
510 * @return new {@link ModelActionBuilder} for the phase
513 public ModelActionBuilder newInferenceAction(ModelProcessingPhase phase) {
514 return getRoot().getSourceContext().newInferenceAction(phase);
518 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
520 * @throws SourceException
522 void addPhaseCompletedListener(ModelProcessingPhase phase, OnPhaseFinished listener) throws SourceException {
524 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null");
525 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null");
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(ModelProcessingPhase phase, 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.");
550 finishedPhase = finishedPhase.getPreviousPhase();
552 phaseMutation.put(phase, mutation);
556 * adds statement to namespace map with the key
559 * {@link StatementNamespace} child that determines namespace to be added to
561 * of type according to namespace class specification
563 * to be added to namespace map
566 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(Class<N> namespace, KT key,
567 StmtContext<?, ?, ?> stmt) {
568 addContextToNamespace(namespace, (K) key, stmt);