Bug 4295: Fixed incorrectly introduced nodes when MERGE was followed by DELETE
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / SchemaUtils.java
1 /*
2  * Copyright (c) 2013 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.data.impl.schema;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.Maps;
16 import com.google.common.collect.Sets;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashSet;
20 import java.util.Map;
21 import java.util.Set;
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
29 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
31 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34
35 public final class SchemaUtils {
36
37     private static final Function<DataSchemaNode, QName> QNAME_FUNCTION = new Function<DataSchemaNode, QName>() {
38         @Override
39         public QName apply(@Nonnull final DataSchemaNode input) {
40             return input.getQName();
41         }
42     };
43
44     private SchemaUtils() {
45         throw new UnsupportedOperationException();
46     }
47
48     /**
49      * @param qname - schema node to find
50      * @param dataSchemaNode - iterable of schemaNodes to look through
51      * @return - schema node with newest revision or absent if no schema node with matching qname is found
52      */
53     public static Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
54         DataSchemaNode sNode = null;
55         if (dataSchemaNode != null && qname != null) {
56             for (DataSchemaNode dsn : dataSchemaNode) {
57                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
58                     if (sNode == null || sNode.getQName().getRevision().compareTo(dsn.getQName().getRevision()) < 0) {
59                         sNode = dsn;
60                     }
61                 } else if (dsn instanceof ChoiceSchemaNode) {
62                     for (ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
63
64                         final DataSchemaNode dataChildByName = choiceCase.getDataChildByName(qname);
65                         if (dataChildByName != null) {
66                             return Optional.of(dataChildByName);
67                         }
68                         Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
69                         if (foundDsn.isPresent()) {
70                             return foundDsn;
71                         }
72                     }
73                 }
74             }
75         }
76         return Optional.fromNullable(sNode);
77     }
78
79     /**
80      *
81      * Find child schema node identified by its QName within a provided schema node
82      *
83      * @param schema schema for parent node - search root
84      * @param qname qname(with or without a revision) of a child node to be found in the parent schema
85      * @return found schema node
86      * @throws java.lang.IllegalStateException if the child was not found in parent schema node
87      */
88     public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname) {
89         // Try to find child schema node directly, but use a fallback that compares QNames without revisions and auto-expands choices
90         final DataSchemaNode dataChildByName = schema.getDataChildByName(qname);
91         return dataChildByName == null ? findSchemaForChild(schema, qname, schema.getChildNodes()) : dataChildByName;
92     }
93
94     @Nullable
95     public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname, final boolean strictMode) {
96         if (strictMode) {
97             return findSchemaForChild(schema, qname);
98         }
99
100         Optional<DataSchemaNode> childSchemaOptional = findFirstSchema(qname, schema.getChildNodes());
101         if (!childSchemaOptional.isPresent()) {
102             return null;
103         }
104         return childSchemaOptional.get();
105     }
106
107     public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname, final Iterable<DataSchemaNode> childNodes) {
108         Optional<DataSchemaNode> childSchema = findFirstSchema(qname, childNodes);
109         Preconditions.checkState(childSchema.isPresent(),
110                 "Unknown child(ren) node(s) detected, identified by: %s, in: %s", qname, schema);
111         return childSchema.get();
112     }
113
114     public static AugmentationSchema findSchemaForAugment(final AugmentationTarget schema, final Set<QName> qNames) {
115         Optional<AugmentationSchema> schemaForAugment = findAugment(schema, qNames);
116         Preconditions.checkState(schemaForAugment.isPresent(), "Unknown augmentation node detected, identified by: %s, in: %s",
117                 qNames, schema);
118         return schemaForAugment.get();
119     }
120
121     public static AugmentationSchema findSchemaForAugment(final ChoiceSchemaNode schema, final Set<QName> qNames) {
122         Optional<AugmentationSchema> schemaForAugment = Optional.absent();
123
124         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
125             schemaForAugment = findAugment(choiceCaseNode, qNames);
126             if(schemaForAugment.isPresent()) {
127                 break;
128             }
129         }
130
131         Preconditions.checkState(schemaForAugment.isPresent(), "Unknown augmentation node detected, identified by: %s, in: %s",
132                 qNames, schema);
133         return schemaForAugment.get();
134     }
135
136     private static Optional<AugmentationSchema> findAugment(final AugmentationTarget schema, final Set<QName> qNames) {
137         for (AugmentationSchema augment : schema.getAvailableAugmentations()) {
138
139             HashSet<QName> qNamesFromAugment = Sets.newHashSet(Collections2.transform(augment.getChildNodes(), new Function<DataSchemaNode, QName>() {
140                 @Override
141                 public QName apply(@Nonnull final DataSchemaNode input) {
142                     Preconditions.checkNotNull(input);
143                     return input.getQName();
144                 }
145             }));
146
147             if(qNamesFromAugment.equals(qNames)) {
148                 return Optional.of(augment);
149             }
150         }
151
152         return Optional.absent();
153     }
154
155     public static DataSchemaNode findSchemaForChild(final ChoiceSchemaNode schema, final QName childPartialQName) {
156         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
157             Optional<DataSchemaNode> childSchema = findFirstSchema(childPartialQName, choiceCaseNode.getChildNodes());
158             if (childSchema.isPresent()) {
159                 return childSchema.get();
160             }
161         }
162
163
164         throw new IllegalStateException(String.format("Unknown child(ren) node(s) detected, identified by: %s, in: %s",
165                 childPartialQName, schema));
166     }
167
168     /**
169      * Recursively find all child nodes that come from choices.
170      *
171      * @param schema schema
172      * @return Map with all child nodes, to their most top augmentation
173      */
174     public static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
175         return mapChildElementsFromChoices(schema, schema.getChildNodes());
176     }
177
178     private static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema, final Iterable<DataSchemaNode> childNodes) {
179         Map<QName, ChoiceSchemaNode> mappedChoices = Maps.newLinkedHashMap();
180
181         for (final DataSchemaNode childSchema : childNodes) {
182             if (childSchema instanceof ChoiceSchemaNode) {
183
184                 if (isFromAugment(schema, childSchema)) {
185                     continue;
186                 }
187
188                 for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
189
190                     for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
191                         mappedChoices.put(qName, (ChoiceSchemaNode) childSchema);
192                     }
193                 }
194             }
195         }
196
197         return mappedChoices;
198     }
199
200     private static boolean isFromAugment(final DataNodeContainer schema, final DataSchemaNode childSchema) {
201         if (!(schema instanceof AugmentationTarget)) {
202             return false;
203         }
204
205         for (AugmentationSchema augmentationSchema : ((AugmentationTarget) schema).getAvailableAugmentations()) {
206             if(augmentationSchema.getDataChildByName(childSchema.getQName()) != null) {
207                 return true;
208             }
209         }
210
211         return false;
212     }
213
214     /**
215      * Recursively find all child nodes that come from augmentations.
216      *
217      * @param schema schema
218      * @return Map with all child nodes, to their most top augmentation
219      */
220     public static Map<QName, AugmentationSchema> mapChildElementsFromAugments(final AugmentationTarget schema) {
221
222         Map<QName, AugmentationSchema> childNodesToAugmentation = Maps.newLinkedHashMap();
223
224         // Find QNames of augmented child nodes
225         Map<QName, AugmentationSchema> augments = Maps.newHashMap();
226         for (final AugmentationSchema augmentationSchema : schema.getAvailableAugmentations()) {
227             for (DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
228                 augments.put(dataSchemaNode.getQName(), augmentationSchema);
229             }
230         }
231
232         // Augmented nodes have to be looked up directly in augmentationTarget
233         // because nodes from augment do not contain nodes from other augmentations
234         if (schema instanceof DataNodeContainer) {
235
236             for (DataSchemaNode child : ((DataNodeContainer) schema).getChildNodes()) {
237                 // If is not augmented child, continue
238                 if (!(augments.containsKey(child.getQName()))) {
239                     continue;
240                 }
241
242                 AugmentationSchema mostTopAugmentation = augments.get(child.getQName());
243
244                 // recursively add all child nodes in case of augment, case and choice
245                 if (child instanceof AugmentationSchema || child instanceof ChoiceCaseNode) {
246                     for (QName qName : getChildNodesRecursive((DataNodeContainer) child)) {
247                         childNodesToAugmentation.put(qName, mostTopAugmentation);
248                     }
249                 } else if (child instanceof ChoiceSchemaNode) {
250                     for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) child).getCases()) {
251                         for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
252                             childNodesToAugmentation.put(qName, mostTopAugmentation);
253                         }
254                     }
255                 } else {
256                     childNodesToAugmentation.put(child.getQName(), mostTopAugmentation);
257                 }
258             }
259         }
260
261         // Choice Node has to map child nodes from all its cases
262         if (schema instanceof ChoiceSchemaNode) {
263             for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) schema).getCases()) {
264                 if (!(augments.containsKey(choiceCaseNode.getQName()))) {
265                     continue;
266                 }
267
268                 for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
269                     childNodesToAugmentation.put(qName, augments.get(choiceCaseNode.getQName()));
270                 }
271             }
272         }
273
274         return childNodesToAugmentation;
275     }
276
277     /**
278      * Recursively list all child nodes.
279      *
280      * In case of choice, augment and cases, step in.
281      *
282      * @param nodeContainer node container
283      * @return set of QNames
284      */
285     public static Set<QName> getChildNodesRecursive(final DataNodeContainer nodeContainer) {
286         Set<QName> allChildNodes = Sets.newHashSet();
287
288         for (DataSchemaNode childSchema : nodeContainer.getChildNodes()) {
289             if(childSchema instanceof ChoiceSchemaNode) {
290                 for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
291                     allChildNodes.addAll(getChildNodesRecursive(choiceCaseNode));
292                 }
293             } else if(childSchema instanceof AugmentationSchema || childSchema instanceof ChoiceCaseNode) {
294                 allChildNodes.addAll(getChildNodesRecursive((DataNodeContainer) childSchema));
295             }
296             else {
297                 allChildNodes.add(childSchema.getQName());
298             }
299         }
300
301         return allChildNodes;
302     }
303
304     /**
305      * Retrieves real schemas for augmented child node.
306      *
307      * Schema of the same child node from augment, and directly from target is not the same.
308      * Schema of child node from augment is incomplete, therefore its useless for XML/NormalizedNode translation.
309      *
310      * @param targetSchema target schema
311      * @param augmentSchema augment schema
312      * @return set of nodes
313      */
314     public static Set<DataSchemaNode> getRealSchemasForAugment(final AugmentationTarget targetSchema, final AugmentationSchema augmentSchema) {
315         if (!(targetSchema.getAvailableAugmentations().contains(augmentSchema))) {
316             return Collections.emptySet();
317         }
318
319         Set<DataSchemaNode> realChildNodes = Sets.newHashSet();
320
321         if(targetSchema instanceof DataNodeContainer) {
322             realChildNodes = getRealSchemasForAugment((DataNodeContainer)targetSchema, augmentSchema);
323         } else if(targetSchema instanceof ChoiceSchemaNode) {
324             for (DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
325                 for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) targetSchema).getCases()) {
326                     if(getChildNodesRecursive(choiceCaseNode).contains(dataSchemaNode.getQName())) {
327                         realChildNodes.add(choiceCaseNode.getDataChildByName(dataSchemaNode.getQName()));
328                     }
329                 }
330             }
331         }
332
333         return realChildNodes;
334     }
335
336     public static Set<DataSchemaNode> getRealSchemasForAugment(final DataNodeContainer targetSchema,
337             final AugmentationSchema augmentSchema) {
338         Set<DataSchemaNode> realChildNodes = Sets.newHashSet();
339         for (DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
340             DataSchemaNode realChild = targetSchema.getDataChildByName(dataSchemaNode.getQName());
341             realChildNodes.add(realChild);
342         }
343         return realChildNodes;
344     }
345
346     public static Optional<ChoiceCaseNode> detectCase(final ChoiceSchemaNode schema, final DataContainerChild<?, ?> child) {
347         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
348             if (child instanceof AugmentationNode
349                     && belongsToCaseAugment(choiceCaseNode, (AugmentationIdentifier) child.getIdentifier())) {
350                 return Optional.of(choiceCaseNode);
351             } else if (choiceCaseNode.getDataChildByName(child.getNodeType()) != null) {
352                 return Optional.of(choiceCaseNode);
353             }
354         }
355
356         return Optional.absent();
357     }
358
359     public static boolean belongsToCaseAugment(final ChoiceCaseNode caseNode, final AugmentationIdentifier childToProcess) {
360         for (AugmentationSchema augmentationSchema : caseNode.getAvailableAugmentations()) {
361
362             Set<QName> currentAugmentChildNodes = Sets.newHashSet();
363             for (DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
364                 currentAugmentChildNodes.add(dataSchemaNode.getQName());
365             }
366
367             if(childToProcess.getPossibleChildNames().equals(currentAugmentChildNodes)){
368                 return true;
369             }
370         }
371
372         return false;
373     }
374
375     /**
376      * Tries to find in {@code parent} which is dealed as augmentation target node with QName as {@code child}. If such
377      * node is found then it is returned, else null.
378      *
379      * @param parent parent node
380      * @param child child node
381      * @return augmentation schema
382      */
383     public static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
384         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
385             for (AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
386                 DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
387                 if (childInAugmentation != null) {
388                     return augmentation;
389                 }
390             }
391         }
392         return null;
393     }
394
395     public static AugmentationIdentifier getNodeIdentifierForAugmentation(final AugmentationSchema schema) {
396         final Collection<QName> qnames = Collections2.transform(schema.getChildNodes(), QNAME_FUNCTION);
397         return new AugmentationIdentifier(ImmutableSet.copyOf(qnames));
398     }
399
400 }