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