83a45cab27803018779bfb1979970c466a1da6fb
[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      * @return Map with all child nodes, to their most top augmentation
172      */
173     public static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
174         return mapChildElementsFromChoices(schema, schema.getChildNodes());
175     }
176
177     private static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema, final Iterable<DataSchemaNode> childNodes) {
178         Map<QName, ChoiceSchemaNode> mappedChoices = Maps.newLinkedHashMap();
179
180         for (final DataSchemaNode childSchema : childNodes) {
181             if (childSchema instanceof ChoiceSchemaNode) {
182
183                 if (isFromAugment(schema, childSchema)) {
184                     continue;
185                 }
186
187                 for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
188
189                     for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
190                         mappedChoices.put(qName, (ChoiceSchemaNode) childSchema);
191                     }
192                 }
193             }
194         }
195
196         return mappedChoices;
197     }
198
199     private static boolean isFromAugment(final DataNodeContainer schema, final DataSchemaNode childSchema) {
200         if (!(schema instanceof AugmentationTarget)) {
201             return false;
202         }
203
204         for (AugmentationSchema augmentationSchema : ((AugmentationTarget) schema).getAvailableAugmentations()) {
205             if(augmentationSchema.getDataChildByName(childSchema.getQName()) != null) {
206                 return true;
207             }
208         }
209
210         return false;
211     }
212
213     /**
214      * Recursively find all child nodes that come from augmentations.
215      *
216      * @return Map with all child nodes, to their most top augmentation
217      */
218     public static Map<QName, AugmentationSchema> mapChildElementsFromAugments(final AugmentationTarget schema) {
219
220         Map<QName, AugmentationSchema> childNodesToAugmentation = Maps.newLinkedHashMap();
221
222         // Find QNames of augmented child nodes
223         Map<QName, AugmentationSchema> augments = Maps.newHashMap();
224         for (final AugmentationSchema augmentationSchema : schema.getAvailableAugmentations()) {
225             for (DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
226                 augments.put(dataSchemaNode.getQName(), augmentationSchema);
227             }
228         }
229
230         // Augmented nodes have to be looked up directly in augmentationTarget
231         // because nodes from augment do not contain nodes from other augmentations
232         if (schema instanceof DataNodeContainer) {
233
234             for (DataSchemaNode child : ((DataNodeContainer) schema).getChildNodes()) {
235                 // If is not augmented child, continue
236                 if (!(augments.containsKey(child.getQName()))) {
237                     continue;
238                 }
239
240                 AugmentationSchema mostTopAugmentation = augments.get(child.getQName());
241
242                 // recursively add all child nodes in case of augment, case and choice
243                 if (child instanceof AugmentationSchema || child instanceof ChoiceCaseNode) {
244                     for (QName qName : getChildNodesRecursive((DataNodeContainer) child)) {
245                         childNodesToAugmentation.put(qName, mostTopAugmentation);
246                     }
247                 } else if (child instanceof ChoiceSchemaNode) {
248                     for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) child).getCases()) {
249                         for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
250                             childNodesToAugmentation.put(qName, mostTopAugmentation);
251                         }
252                     }
253                 } else {
254                     childNodesToAugmentation.put(child.getQName(), mostTopAugmentation);
255                 }
256             }
257         }
258
259         // Choice Node has to map child nodes from all its cases
260         if (schema instanceof ChoiceSchemaNode) {
261             for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) schema).getCases()) {
262                 if (!(augments.containsKey(choiceCaseNode.getQName()))) {
263                     continue;
264                 }
265
266                 for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
267                     childNodesToAugmentation.put(qName, augments.get(choiceCaseNode.getQName()));
268                 }
269             }
270         }
271
272         return childNodesToAugmentation;
273     }
274
275     /**
276      * Recursively list all child nodes.
277      *
278      * In case of choice, augment and cases, step in.
279      */
280     public static Set<QName> getChildNodesRecursive(final DataNodeContainer nodeContainer) {
281         Set<QName> allChildNodes = Sets.newHashSet();
282
283         for (DataSchemaNode childSchema : nodeContainer.getChildNodes()) {
284             if(childSchema instanceof ChoiceSchemaNode) {
285                 for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
286                     allChildNodes.addAll(getChildNodesRecursive(choiceCaseNode));
287                 }
288             } else if(childSchema instanceof AugmentationSchema || childSchema instanceof ChoiceCaseNode) {
289                 allChildNodes.addAll(getChildNodesRecursive((DataNodeContainer) childSchema));
290             }
291             else {
292                 allChildNodes.add(childSchema.getQName());
293             }
294         }
295
296         return allChildNodes;
297     }
298
299     /**
300      * Retrieves real schemas for augmented child node.
301      *
302      * Schema of the same child node from augment, and directly from target is not the same.
303      * Schema of child node from augment is incomplete, therefore its useless for XML/NormalizedNode translation.
304      *
305      */
306     public static Set<DataSchemaNode> getRealSchemasForAugment(final AugmentationTarget targetSchema, final AugmentationSchema augmentSchema) {
307         if (!(targetSchema.getAvailableAugmentations().contains(augmentSchema))) {
308             return Collections.emptySet();
309         }
310
311         Set<DataSchemaNode> realChildNodes = Sets.newHashSet();
312
313         if(targetSchema instanceof DataNodeContainer) {
314             realChildNodes = getRealSchemasForAugment((DataNodeContainer)targetSchema, augmentSchema);
315         } else if(targetSchema instanceof ChoiceSchemaNode) {
316             for (DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
317                 for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) targetSchema).getCases()) {
318                     if(getChildNodesRecursive(choiceCaseNode).contains(dataSchemaNode.getQName())) {
319                         realChildNodes.add(choiceCaseNode.getDataChildByName(dataSchemaNode.getQName()));
320                     }
321                 }
322             }
323         }
324
325         return realChildNodes;
326     }
327
328     public static Set<DataSchemaNode> getRealSchemasForAugment(final DataNodeContainer targetSchema,
329             final AugmentationSchema augmentSchema) {
330         Set<DataSchemaNode> realChildNodes = Sets.newHashSet();
331         for (DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
332             DataSchemaNode realChild = targetSchema.getDataChildByName(dataSchemaNode.getQName());
333             realChildNodes.add(realChild);
334         }
335         return realChildNodes;
336     }
337
338     public static Optional<ChoiceCaseNode> detectCase(final ChoiceSchemaNode schema, final DataContainerChild<?, ?> child) {
339         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
340             if (child instanceof AugmentationNode
341                     && belongsToCaseAugment(choiceCaseNode, (AugmentationIdentifier) child.getIdentifier())) {
342                 return Optional.of(choiceCaseNode);
343             } else if (choiceCaseNode.getDataChildByName(child.getNodeType()) != null) {
344                 return Optional.of(choiceCaseNode);
345             }
346         }
347
348         return Optional.absent();
349     }
350
351     public static boolean belongsToCaseAugment(final ChoiceCaseNode caseNode, final AugmentationIdentifier childToProcess) {
352         for (AugmentationSchema augmentationSchema : caseNode.getAvailableAugmentations()) {
353
354             Set<QName> currentAugmentChildNodes = Sets.newHashSet();
355             for (DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
356                 currentAugmentChildNodes.add(dataSchemaNode.getQName());
357             }
358
359             if(childToProcess.getPossibleChildNames().equals(currentAugmentChildNodes)){
360                 return true;
361             }
362         }
363
364         return false;
365     }
366
367     /**
368      * Tries to find in {@code parent} which is dealed as augmentation target node with QName as {@code child}. If such
369      * node is found then it is returned, else null.
370      */
371     public static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
372         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
373             for (AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
374                 DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
375                 if (childInAugmentation != null) {
376                     return augmentation;
377                 }
378             }
379         }
380         return null;
381     }
382
383     public static AugmentationIdentifier getNodeIdentifierForAugmentation(final AugmentationSchema schema) {
384         final Collection<QName> qnames = Collections2.transform(schema.getChildNodes(), QNAME_FUNCTION);
385         return new AugmentationIdentifier(ImmutableSet.copyOf(qnames));
386     }
387
388 }