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