Further yang-parser-impl checkstyle fixes
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / DeviateStatementImpl.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
9
10 import com.google.common.collect.ImmutableMap;
11 import com.google.common.collect.ImmutableMap.Builder;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.Collection;
14 import java.util.Map;
15 import java.util.Objects;
16 import java.util.Set;
17 import javax.annotation.Nonnull;
18 import org.opendaylight.yangtools.yang.common.QNameModule;
19 import org.opendaylight.yangtools.yang.common.YangVersion;
20 import org.opendaylight.yangtools.yang.model.api.DeviateKind;
21 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
22 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
24 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
26 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
27 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
39 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
40 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
41 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
42 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
43 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
44 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.DeviateEffectiveStatementImpl;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 public class DeviateStatementImpl extends AbstractDeclaredStatement<DeviateKind> implements DeviateStatement {
49     private static final Logger LOG = LoggerFactory.getLogger(DeviateStatementImpl.class);
50
51     private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
52             SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
53
54     private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
55             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
56                 .addOptional(YangStmtMapping.CONFIG)
57                 .addOptional(YangStmtMapping.DEFAULT)
58                 .addOptional(YangStmtMapping.MANDATORY)
59                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
60                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
61                 .addAny(YangStmtMapping.MUST)
62                 .addAny(YangStmtMapping.UNIQUE)
63                 .addOptional(YangStmtMapping.UNITS)
64                 .build();
65
66     private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
67             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
68                 .addOptional(YangStmtMapping.CONFIG)
69                 .addOptional(YangStmtMapping.DEFAULT)
70                 .addOptional(YangStmtMapping.MANDATORY)
71                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
72                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
73                 .addOptional(YangStmtMapping.TYPE)
74                 .addOptional(YangStmtMapping.UNITS)
75                 .build();
76
77     private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
78             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
79                 .addOptional(YangStmtMapping.DEFAULT)
80                 .addAny(YangStmtMapping.MUST)
81                 .addAny(YangStmtMapping.UNIQUE)
82                 .addOptional(YangStmtMapping.UNITS)
83                 .build();
84
85     protected DeviateStatementImpl(final StmtContext<DeviateKind, DeviateStatement, ?> context) {
86         super(context);
87     }
88
89     public static class Definition extends AbstractStatementSupport<DeviateKind, DeviateStatement,
90             EffectiveStatement<DeviateKind, DeviateStatement>> {
91         private static final Map<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP;
92
93         static {
94             final Builder<String, DeviateKind> keywordToDeviateMapBuilder = ImmutableMap.builder();
95             for (final DeviateKind deviate : DeviateKind.values()) {
96                 keywordToDeviateMapBuilder.put(deviate.getKeyword(), deviate);
97             }
98             KEYWORD_TO_DEVIATE_MAP = keywordToDeviateMapBuilder.build();
99         }
100
101         private static final Set<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
102                 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
103                 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
104
105         public Definition() {
106             super(YangStmtMapping.DEVIATE);
107         }
108
109         @Override
110         public DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
111             return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value),
112                 ctx.getStatementSourceReference(), "String '%s' is not valid deviate argument", value);
113         }
114
115         @Override
116         public DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx) {
117             return new DeviateStatementImpl(ctx);
118         }
119
120         @Override
121         public EffectiveStatement<DeviateKind, DeviateStatement> createEffective(
122                 final StmtContext<DeviateKind, DeviateStatement, EffectiveStatement<DeviateKind,
123                         DeviateStatement>> ctx) {
124             return new DeviateEffectiveStatementImpl(ctx);
125         }
126
127         @Override
128         public void onFullDefinitionDeclared(final Mutable<DeviateKind, DeviateStatement,
129                 EffectiveStatement<DeviateKind, DeviateStatement>> deviateStmtCtx) {
130             final DeviateKind deviateKind = deviateStmtCtx.getStatementArgument();
131             getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
132
133             final SchemaNodeIdentifier deviationTarget =
134                     (SchemaNodeIdentifier) deviateStmtCtx.getParentContext().getStatementArgument();
135
136             if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
137                 return;
138             }
139
140             final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
141                     ModelProcessingPhase.EFFECTIVE_MODEL);
142
143             final Prerequisite<StmtContext<DeviateKind, DeviateStatement, EffectiveStatement<DeviateKind,
144                     DeviateStatement>>> sourceCtxPrerequisite =
145                     deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
146
147             final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
148                     deviateAction.mutatesEffectiveCtx(deviateStmtCtx.getRoot(),
149                         SchemaNodeIdentifierBuildNamespace.class,  deviationTarget);
150
151             deviateAction.apply(new InferenceAction() {
152                 @Override
153                 public void apply(final InferenceContext ctx) throws InferenceException {
154                     // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
155                     final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
156                             (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.resolve(ctx);
157                     final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
158                             (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.resolve(ctx);
159
160                     switch (deviateKind) {
161                         case NOT_SUPPORTED:
162                             targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
163                             break;
164                         case ADD:
165                             performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
166                             break;
167                         case REPLACE:
168                             performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
169                             break;
170                         case DELETE:
171                             performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
172                             break;
173                         default:
174                             throw new IllegalStateException("Unsupported deviate " + deviateKind);
175                     }
176                 }
177
178                 @Override
179                 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
180                     throw new InferenceException(deviateStmtCtx.getParentContext().getStatementSourceReference(),
181                         "Deviation target '%s' not found.", deviationTarget);
182                 }
183             });
184         }
185
186         private static boolean isDeviationSupported(final Mutable<DeviateKind, DeviateStatement,
187                 EffectiveStatement<DeviateKind, DeviateStatement>> deviateStmtCtx,
188                 final SchemaNodeIdentifier deviationTarget) {
189             final Map<QNameModule, Set<QNameModule>> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
190                     ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES);
191             if (modulesDeviatedByModules == null) {
192                 return true;
193             }
194
195             final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
196                     deviateStmtCtx.getRoot());
197             final QNameModule targetModule = deviationTarget.getLastComponent().getModule();
198
199             final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
200             if (deviationModulesSupportedByTargetModule != null) {
201                 return deviationModulesSupportedByTargetModule.contains(currentModule);
202             }
203
204             return false;
205         }
206
207         private static void performDeviateAdd(final StatementContextBase<?, ?, ?> deviateStmtCtx,
208                 final StatementContextBase<?, ?, ?> targetCtx) {
209             for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
210                 validateDeviationTarget(originalStmtCtx, targetCtx);
211                 addStatement(originalStmtCtx, targetCtx);
212             }
213         }
214
215         private static void addStatement(final Mutable<?, ?, ?> stmtCtxToBeAdded,
216                 final StatementContextBase<?, ?, ?> targetCtx) {
217             if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
218                 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.getPublicDefinition();
219                 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
220                         && YangStmtMapping.LEAF.equals(targetCtx.getPublicDefinition())) {
221                     for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
222                         InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.getPublicDefinition()),
223                             stmtCtxToBeAdded.getStatementSourceReference(),
224                             "Deviation cannot add substatement %s to target node %s because it is already defined "
225                             + "in target and can appear only once.",
226                             stmtToBeAdded.getStatementName(), targetCtx.getStatementArgument());
227                     }
228                 }
229             }
230
231             targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeAdded, CopyType.ORIGINAL));
232         }
233
234         private static void performDeviateReplace(final StatementContextBase<?, ?, ?> deviateStmtCtx,
235                 final StatementContextBase<?, ?, ?> targetCtx) {
236             for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
237                 validateDeviationTarget(originalStmtCtx, targetCtx);
238                 replaceStatement(originalStmtCtx, targetCtx);
239             }
240         }
241
242         private static void replaceStatement(final Mutable<?, ?, ?> stmtCtxToBeReplaced,
243                 final StatementContextBase<?, ?, ?> targetCtx) {
244             final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.getPublicDefinition();
245
246             if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
247                     && YangStmtMapping.LEAF_LIST.equals(targetCtx.getPublicDefinition())) {
248                 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
249                         + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
250                         targetCtx.getStatementArgument(), stmtCtxToBeReplaced.getStatementSourceReference());
251                 return;
252             }
253
254             for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
255                 if (stmtToBeReplaced.equals(targetCtxSubstatement.getPublicDefinition())) {
256                     targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
257                     targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeReplaced, CopyType.ORIGINAL));
258                     return;
259                 }
260             }
261
262             for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
263                 if (stmtToBeReplaced.equals(targetCtxSubstatement.getPublicDefinition())) {
264                     targetCtxSubstatement.setIsSupportedToBuildEffective(false);
265                     targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeReplaced, CopyType.ORIGINAL));
266                     return;
267                 }
268             }
269
270             throw new InferenceException(stmtCtxToBeReplaced.getStatementSourceReference(), "Deviation cannot replace "
271                     + "substatement %s in target node %s because it does not exist in target node.",
272                     stmtToBeReplaced.getStatementName(), targetCtx.getStatementArgument());
273         }
274
275         private static void performDeviateDelete(final StatementContextBase<?, ?, ?> deviateStmtCtx,
276                 final StatementContextBase<?, ?, ?> targetCtx) {
277             for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
278                 validateDeviationTarget(originalStmtCtx, targetCtx);
279                 deleteStatement(originalStmtCtx, targetCtx);
280             }
281         }
282
283         private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
284                 final StatementContextBase<?, ?, ?> targetCtx) {
285             final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.getPublicDefinition();
286             final String stmtArgument = stmtCtxToBeDeleted.rawStatementArgument();
287
288             for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
289                 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.getPublicDefinition(),
290                         targetCtxSubstatement.rawStatementArgument())) {
291                     targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
292                     return;
293                 }
294             }
295
296             for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
297                 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.getPublicDefinition(),
298                         targetCtxSubstatement.rawStatementArgument())) {
299                     targetCtxSubstatement.setIsSupportedToBuildEffective(false);
300                     return;
301                 }
302             }
303
304             LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
305                     + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
306                     targetCtx.getStatementArgument(), stmtCtxToBeDeleted.getStatementSourceReference());
307         }
308
309         private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
310                 final StatementDefinition secondStmtDef, final String secondStmtArg) {
311             return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
312         }
313
314         private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
315                 final StmtContext<?, ?, ?> targetCtx) {
316             InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
317                     targetCtx.getRootVersion()), deviateSubStmtCtx.getStatementSourceReference(),
318                     "%s is not a valid deviation target for substatement %s.",
319                     targetCtx.getStatementArgument(), deviateSubStmtCtx.getPublicDefinition().getStatementName());
320         }
321
322         private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
323                 final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
324             Set<StatementDefinition> supportedDeviationTargets =
325                     YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(deviateTargetCtx.getRootVersion(),
326                             deviateSubstatementCtx.getPublicDefinition());
327
328             if (supportedDeviationTargets == null) {
329                 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
330                         deviateSubstatementCtx.getPublicDefinition());
331             }
332
333             // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
334             return supportedDeviationTargets == null || supportedDeviationTargets.contains(
335                     deviateTargetCtx.getPublicDefinition());
336         }
337
338         protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
339             switch (deviateKind) {
340                 case NOT_SUPPORTED:
341                     return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
342                 case ADD:
343                     return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
344                 case REPLACE:
345                     return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
346                 case DELETE:
347                     return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
348                 default:
349                     throw new IllegalStateException(String.format(
350                             "Substatement validator for deviate %s has not been defined.", deviateKind));
351             }
352         }
353
354         @Override
355         protected SubstatementValidator getSubstatementValidator() {
356             return null;
357         }
358     }
359
360     @Nonnull
361     @Override
362     public DeviateKind getValue() {
363         return argument();
364     }
365 }