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