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 if (getDefinition().getPublicView() != Rfc6020Mapping.AUGMENT) {
321 potential = substatements.get(createIdentifier());
323 if (potential == null) {
324 potential = new SubstatementContext(StatementContextBase.this, this);
325 substatements.put(createIdentifier(), potential);
326 getDefinition().onStatementAdded(potential);
328 potential.resetLists();
329 switch (this.getStamementSource().getStatementSource()) {
331 addDeclaredSubstatement(potential);
334 addEffectiveSubstatement(potential);
343 * @return local namespace behaviour type {@link NamespaceBehaviour}
346 public StorageNodeType getStorageNodeType() {
347 return StorageNodeType.STATEMENT_LOCAL;
351 * builds {@link DeclaredStatement} for statement context
354 public D buildDeclared() {
355 Preconditions.checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
356 || completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
357 if (declaredInstance == null) {
358 declaredInstance = definition().getFactory().createDeclared(this);
360 return declaredInstance;
364 * builds {@link EffectiveStatement} for statement context
367 public E buildEffective() {
368 if (effectiveInstance == null) {
369 effectiveInstance = definition().getFactory().createEffective(this);
371 return effectiveInstance;
375 * clears collection of declared substatements
377 * @throws IllegalStateException
378 * if invoked in effective build phase
382 final SourceSpecificContext sourceContext = getRoot().getSourceContext();
383 Preconditions.checkState(sourceContext.getInProgressPhase() != ModelProcessingPhase.EFFECTIVE_MODEL,
384 "Declared statements list cannot be cleared in effective phase");
390 * tries to execute current {@link ModelProcessingPhase} of source parsing
393 * to be executed (completed)
394 * @return if phase was successfully completed
395 * @throws SourceException
396 * when an error occured in source parsing
398 boolean tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
399 Iterator<ContextMutation> openMutations = phaseMutation.get(phase).iterator();
400 boolean finished = true;
401 while (openMutations.hasNext()) {
402 ContextMutation current = openMutations.next();
403 if (current.isFinished()) {
404 openMutations.remove();
409 for (StatementContextBase<?, ?, ?> child : declared) {
410 finished &= child.tryToCompletePhase(phase);
412 for (StatementContextBase<?, ?, ?> child : effective) {
413 finished &= child.tryToCompletePhase(phase);
417 onPhaseCompleted(phase);
424 * occurs on end of {@link ModelProcessingPhase} of source parsing
427 * that was to be completed (finished)
428 * @throws SourceException
429 * when an error occured in source parsing
431 private void onPhaseCompleted(final ModelProcessingPhase phase) throws SourceException {
432 completedPhase = phase;
433 Iterator<OnPhaseFinished> listener = phaseListeners.get(completedPhase).iterator();
434 while (listener.hasNext()) {
435 OnPhaseFinished next = listener.next();
436 if (next.phaseFinished(this, phase)) {
443 * Ends declared section of current node.
446 * @throws SourceException
448 void endDeclared(final StatementSourceReference ref, final ModelProcessingPhase phase) throws SourceException {
449 definition().onDeclarationFinished(this, phase);
453 * @return statement definition
455 protected final StatementDefinitionContext<A, D, E> definition() {
460 protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
461 definition().checkNamespaceAllowed(type);
465 * occurs when an item is added to model namespace
467 * @throws SourceException instance of SourceException
470 protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key, final V value) {
471 // definition().onNamespaceElementAdded(this, type, key, value);
474 <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
475 final OnNamespaceItemAdded listener) throws SourceException {
476 Object potential = getFromNamespace(type, key);
477 if (potential != null) {
478 listener.namespaceItemAdded(this, type, key, potential);
481 NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
482 if (behaviour instanceof NamespaceBehaviourWithListeners) {
483 NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
484 casted.addValueListener(new ValueAddedListener<K>(this, key) {
486 void onValueAdded(final Object key, final Object value) {
488 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
489 } catch (SourceException e) {
490 throw Throwables.propagate(e);
498 * @see StatementSupport#getPublicView()
501 public StatementDefinition getPublicDefinition() {
502 return definition().getPublicView();
506 * @return new {@link ModelActionBuilder} for the phase
509 public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
510 return getRoot().getSourceContext().newInferenceAction(phase);
514 * adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end
516 * @throws SourceException
518 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) throws SourceException {
520 Preconditions.checkNotNull(phase, "Statement context processing phase cannot be null");
521 Preconditions.checkNotNull(listener, "Statement context phase listener cannot be null");
523 ModelProcessingPhase finishedPhase = completedPhase;
524 while (finishedPhase != null) {
525 if (phase.equals(finishedPhase)) {
526 listener.phaseFinished(this, finishedPhase);
529 finishedPhase = finishedPhase.getPreviousPhase();
531 phaseListeners.put(phase, listener);
535 * adds {@link ContextMutation} to {@link ModelProcessingPhase}
537 * @throws IllegalStateException
538 * when the mutation was registered after phase was completed
540 void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
541 ModelProcessingPhase finishedPhase = completedPhase;
542 while (finishedPhase != null) {
543 if (phase.equals(finishedPhase)) {
544 throw new IllegalStateException("Mutation registered after phase was completed.");
546 finishedPhase = finishedPhase.getPreviousPhase();
548 phaseMutation.put(phase, mutation);
552 * adds statement to namespace map with the key
555 * {@link StatementNamespace} child that determines namespace to be added to
557 * of type according to namespace class specification
559 * to be added to namespace map
562 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace, final KT key,
563 final StmtContext<?, ?, ?> stmt) {
564 addContextToNamespace(namespace, (K) key, stmt);