2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.schema;
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableSet;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.HashSet;
20 import java.util.LinkedHashMap;
21 import java.util.List;
23 import java.util.Optional;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.Revision;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
31 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
34 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 public final class SchemaUtils {
45 private SchemaUtils() {
50 * Find the first schema with specified QName.
52 * @param qname schema node to find
53 * @param dataSchemaNode Iterable of schemaNodes to look through
54 * @return schema node with newest revision or absent if no schema node with matching qname is found
56 public static Optional<DataSchemaNode> findFirstSchema(final QName qname,
57 final Iterable<? extends DataSchemaNode> dataSchemaNode) {
58 DataSchemaNode schema = null;
59 if (dataSchemaNode != null && qname != null) {
60 for (final DataSchemaNode dsn : dataSchemaNode) {
61 if (qname.isEqualWithoutRevision(dsn.getQName())) {
62 if (schema == null || Revision.compare(schema.getQName().getRevision(),
63 dsn.getQName().getRevision()) < 0) {
66 } else if (dsn instanceof ChoiceSchemaNode) {
67 for (final CaseSchemaNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
68 final Optional<DataSchemaNode> dataChildByName = choiceCase.findDataChildByName(qname);
69 if (dataChildByName.isPresent()) {
70 return dataChildByName;
72 final Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
73 if (foundDsn.isPresent()) {
80 return Optional.ofNullable(schema);
84 * Find child schema node identified by its QName within a provided schema node.
86 * @param schema schema for parent node - search root
87 * @param qname qname(with or without a revision) of a child node to be found in the parent schema
88 * @return found schema node
89 * @throws java.lang.IllegalStateException if the child was not found in parent schema node
91 public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname) {
92 // Try to find child schema node directly, but use a fallback that compares QNames without revisions
93 // and auto-expands choices
94 final Optional<DataSchemaNode> dataChildByName = schema.findDataChildByName(qname);
95 return dataChildByName.isPresent() ? dataChildByName.get()
96 : findSchemaForChild(schema, qname, schema.getChildNodes());
99 public static @Nullable DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname,
100 final boolean strictMode) {
102 return findSchemaForChild(schema, qname);
105 final Optional<DataSchemaNode> childSchemaOptional = findFirstSchema(qname, schema.getChildNodes());
106 if (!childSchemaOptional.isPresent()) {
109 return childSchemaOptional.get();
112 public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname,
113 final Iterable<? extends DataSchemaNode> childNodes) {
114 final Optional<DataSchemaNode> childSchema = findFirstSchema(qname, childNodes);
115 checkState(childSchema.isPresent(), "Unknown child(ren) node(s) detected, identified by: %s, in: %s", qname,
117 return childSchema.get();
120 public static DataSchemaNode findSchemaForChild(final ChoiceSchemaNode schema, final QName childPartialQName) {
121 for (final CaseSchemaNode choiceCaseNode : schema.getCases()) {
122 final Optional<DataSchemaNode> childSchema = findFirstSchema(childPartialQName,
123 choiceCaseNode.getChildNodes());
124 if (childSchema.isPresent()) {
125 return childSchema.get();
130 throw new IllegalStateException(String.format("Unknown child(ren) node(s) detected, identified by: %s, in: %s",
131 childPartialQName, schema));
134 public static AugmentationSchemaNode findSchemaForAugment(final AugmentationTarget schema,
135 final Set<QName> qnames) {
136 final Optional<AugmentationSchemaNode> schemaForAugment = findAugment(schema, qnames);
137 checkState(schemaForAugment.isPresent(), "Unknown augmentation node detected, identified by: %s, in: %s",
139 return schemaForAugment.get();
142 public static AugmentationSchemaNode findSchemaForAugment(final ChoiceSchemaNode schema, final Set<QName> qnames) {
143 for (final CaseSchemaNode choiceCaseNode : schema.getCases()) {
144 final Optional<AugmentationSchemaNode> schemaForAugment = findAugment(choiceCaseNode, qnames);
145 if (schemaForAugment.isPresent()) {
146 return schemaForAugment.get();
150 throw new IllegalStateException(String.format("Unknown augmentation node detected, identified by: %s, in: %s",
154 private static Optional<AugmentationSchemaNode> findAugment(final AugmentationTarget schema,
155 final Set<QName> qnames) {
156 for (final AugmentationSchemaNode augment : schema.getAvailableAugmentations()) {
157 final Set<QName> qNamesFromAugment = ImmutableSet.copyOf(Collections2.transform(augment.getChildNodes(),
158 DataSchemaNode::getQName));
159 if (qnames.equals(qNamesFromAugment)) {
160 return Optional.of(augment);
164 return Optional.empty();
168 * Recursively find all child nodes that come from choices.
170 * @param schema schema
171 * @return Map with all child nodes, to their most top augmentation
173 public static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
174 return mapChildElementsFromChoices(schema, schema.getChildNodes());
177 private static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema,
178 final Iterable<? extends DataSchemaNode> childNodes) {
179 final Map<QName, ChoiceSchemaNode> mappedChoices = new LinkedHashMap<>();
181 for (final DataSchemaNode childSchema : childNodes) {
182 if (childSchema instanceof ChoiceSchemaNode) {
184 if (isFromAugment(schema, childSchema)) {
188 for (final CaseSchemaNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
189 for (final QName qname : getChildNodesRecursive(choiceCaseNode)) {
190 mappedChoices.put(qname, (ChoiceSchemaNode) childSchema);
196 return mappedChoices;
199 private static boolean isFromAugment(final DataNodeContainer schema, final DataSchemaNode childSchema) {
200 if (!(schema instanceof AugmentationTarget)) {
204 for (final AugmentationSchemaNode augmentation : ((AugmentationTarget) schema).getAvailableAugmentations()) {
205 if (augmentation.findDataChildByName(childSchema.getQName()).isPresent()) {
214 * Recursively find all child nodes that come from augmentations.
216 * @param schema schema
217 * @return Map with all child nodes, to their most top augmentation
219 public static Map<QName, AugmentationSchemaNode> mapChildElementsFromAugments(final AugmentationTarget schema) {
221 final Map<QName, AugmentationSchemaNode> childNodesToAugmentation = new LinkedHashMap<>();
223 // Find QNames of augmented child nodes
224 final Map<QName, AugmentationSchemaNode> augments = new HashMap<>();
225 for (final AugmentationSchemaNode augmentationSchema : schema.getAvailableAugmentations()) {
226 for (final DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
227 augments.put(dataSchemaNode.getQName(), augmentationSchema);
231 // Augmented nodes have to be looked up directly in augmentationTarget
232 // because nodes from augment do not contain nodes from other augmentations
233 if (schema instanceof DataNodeContainer) {
235 for (final DataSchemaNode child : ((DataNodeContainer) schema).getChildNodes()) {
236 // If is not augmented child, continue
237 if (!augments.containsKey(child.getQName())) {
241 final AugmentationSchemaNode mostTopAugmentation = augments.get(child.getQName());
243 // recursively add all child nodes in case of augment, case and choice
244 if (child instanceof AugmentationSchemaNode || child instanceof CaseSchemaNode) {
245 for (final QName qname : getChildNodesRecursive((DataNodeContainer) child)) {
246 childNodesToAugmentation.put(qname, mostTopAugmentation);
248 } else if (child instanceof ChoiceSchemaNode) {
249 for (final CaseSchemaNode choiceCaseNode : ((ChoiceSchemaNode) child).getCases()) {
250 for (final QName qname : getChildNodesRecursive(choiceCaseNode)) {
251 childNodesToAugmentation.put(qname, mostTopAugmentation);
255 childNodesToAugmentation.put(child.getQName(), mostTopAugmentation);
260 // Choice Node has to map child nodes from all its cases
261 if (schema instanceof ChoiceSchemaNode) {
262 for (final CaseSchemaNode choiceCaseNode : ((ChoiceSchemaNode) schema).getCases()) {
263 if (!augments.containsKey(choiceCaseNode.getQName())) {
267 for (final QName qname : getChildNodesRecursive(choiceCaseNode)) {
268 childNodesToAugmentation.put(qname, augments.get(choiceCaseNode.getQName()));
273 return childNodesToAugmentation;
277 * Recursively list all child nodes. In case of choice, augment and cases, step in.
279 * @param nodeContainer node container
280 * @return set of QNames
282 public static Set<QName> getChildNodesRecursive(final DataNodeContainer nodeContainer) {
283 final Set<QName> allChildNodes = new HashSet<>();
285 for (final DataSchemaNode childSchema : nodeContainer.getChildNodes()) {
286 if (childSchema instanceof ChoiceSchemaNode) {
287 for (final CaseSchemaNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
288 allChildNodes.addAll(getChildNodesRecursive(choiceCaseNode));
290 } else if (childSchema instanceof AugmentationSchemaNode || childSchema instanceof CaseSchemaNode) {
291 allChildNodes.addAll(getChildNodesRecursive((DataNodeContainer) childSchema));
293 allChildNodes.add(childSchema.getQName());
297 return allChildNodes;
301 * Retrieves real schemas for augmented child node.
304 * Schema of the same child node from augment, and directly from target is not the same.
305 * Schema of child node from augment is incomplete, therefore its useless for XML/NormalizedNode translation.
307 * @param targetSchema target schema
308 * @param augmentSchema augment schema
309 * @return set of nodes
311 public static Set<DataSchemaNode> getRealSchemasForAugment(final AugmentationTarget targetSchema,
312 final AugmentationSchemaNode augmentSchema) {
313 if (!targetSchema.getAvailableAugmentations().contains(augmentSchema)) {
314 return ImmutableSet.of();
316 if (targetSchema instanceof DataNodeContainer) {
317 return getRealSchemasForAugment((DataNodeContainer)targetSchema, augmentSchema);
319 final Set<DataSchemaNode> realChildNodes = new HashSet<>();
320 if (targetSchema instanceof ChoiceSchemaNode) {
321 for (final DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
322 for (final CaseSchemaNode choiceCaseNode : ((ChoiceSchemaNode) targetSchema).getCases()) {
323 if (getChildNodesRecursive(choiceCaseNode).contains(dataSchemaNode.getQName())) {
324 realChildNodes.add(choiceCaseNode.getDataChildByName(dataSchemaNode.getQName()));
330 return realChildNodes;
333 public static Set<DataSchemaNode> getRealSchemasForAugment(final DataNodeContainer targetSchema,
334 final AugmentationSchemaNode augmentSchema) {
335 final Set<DataSchemaNode> realChildNodes = new HashSet<>();
336 for (final DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
337 final DataSchemaNode realChild = targetSchema.getDataChildByName(dataSchemaNode.getQName());
338 realChildNodes.add(realChild);
340 return realChildNodes;
343 public static Optional<CaseSchemaNode> detectCase(final ChoiceSchemaNode schema, final DataContainerChild child) {
344 for (final CaseSchemaNode choiceCaseNode : schema.getCases()) {
345 if (child instanceof AugmentationNode
346 && belongsToCaseAugment(choiceCaseNode, (AugmentationIdentifier) child.getIdentifier())
347 || choiceCaseNode.findDataChildByName(child.getNodeType()).isPresent()) {
348 return Optional.of(choiceCaseNode);
352 return Optional.empty();
355 public static boolean belongsToCaseAugment(final CaseSchemaNode caseNode,
356 final AugmentationIdentifier childToProcess) {
357 for (final AugmentationSchemaNode augmentationSchema : caseNode.getAvailableAugmentations()) {
359 final Set<QName> currentAugmentChildNodes = new HashSet<>();
360 for (final DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
361 currentAugmentChildNodes.add(dataSchemaNode.getQName());
364 if (childToProcess.getPossibleChildNames().equals(currentAugmentChildNodes)) {
373 * Tries to find in {@code parent} which is dealed as augmentation target node with QName as {@code child}. If such
374 * node is found then it is returned, else null.
376 * @param parent parent node
377 * @param child child node
378 * @return augmentation schema
380 public static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
381 final DataSchemaNode child) {
382 if (!(parent instanceof AugmentationTarget) || parent instanceof ChoiceSchemaNode) {
386 for (final AugmentationSchemaNode augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
387 final Optional<DataSchemaNode> childInAugmentation = augmentation.findDataChildByName(child.getQName());
388 if (childInAugmentation.isPresent()) {
396 * Finds schema node for given path in schema context. This method performs
397 * lookup in the namespace of all leafs, leaf-lists, lists, containers,
398 * choices, rpcs, actions, notifications, anydatas, and anyxmls according to
399 * Rfc6050/Rfc7950 section 6.2.1.
401 * @param schemaContext
405 * @return schema node on path
407 public static SchemaNode findDataParentSchemaOnPath(final SchemaContext schemaContext, final SchemaPath path) {
408 SchemaNode current = requireNonNull(schemaContext);
409 for (final QName qname : path.getPathFromRoot()) {
410 current = findDataChildSchemaByQName(current, qname);
416 * Find child data schema node identified by its QName within a provided schema node. This method performs lookup
417 * in the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions, notifications, anydatas
418 * and anyxmls according to RFC6050/RFC7950 section 6.2.1.
424 * @return data child schema node
425 * @throws IllegalArgumentException
426 * if the schema node does not allow children
428 public static @Nullable SchemaNode findDataChildSchemaByQName(final SchemaNode node, final QName qname) {
429 if (node instanceof DataNodeContainer) {
430 SchemaNode child = ((DataNodeContainer) node).dataChildByName(qname);
431 if (child == null && node instanceof SchemaContext) {
432 child = tryFind(((SchemaContext) node).getOperations(), qname).orElse(null);
434 if (child == null && node instanceof NotificationNodeContainer) {
435 child = tryFind(((NotificationNodeContainer) node).getNotifications(), qname).orElse(null);
437 if (child == null && node instanceof ActionNodeContainer) {
438 child = tryFind(((ActionNodeContainer) node).getActions(), qname).orElse(null);
443 if (node instanceof ChoiceSchemaNode) {
444 return ((ChoiceSchemaNode) node).findCase(qname).orElse(null);
446 if (node instanceof OperationDefinition) {
447 switch (qname.getLocalName()) {
449 return ((OperationDefinition) node).getInput();
451 return ((OperationDefinition) node).getOutput();
457 throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", node));
461 * Finds schema node for given path in schema context. This method performs lookup in both the namespace
462 * of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions,
463 * notifications, anydatas and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
466 * This method returns collection of SchemaNodes, because name conflicts can occur between the namespace
467 * of groupings and namespace of data nodes. This method finds and collects all schema nodes that matches supplied
468 * SchemaPath and returns them all as collection of schema nodes.
470 * @param schemaContext
474 * @return collection of schema nodes on path
476 public static Collection<SchemaNode> findParentSchemaNodesOnPath(final SchemaContext schemaContext,
477 final SchemaPath path) {
478 return findParentSchemaNodesOnPath(schemaContext, path.getPathFromRoot());
482 * Finds schema node for given path in schema context. This method performs lookup in both the namespace
483 * of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions,
484 * notifications, anydatas and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
487 * This method returns collection of SchemaNodes, because name conflicts can occur between the namespace
488 * of groupings and namespace of data nodes. This method finds and collects all schema nodes that matches supplied
489 * SchemaPath and returns them all as collection of schema nodes.
491 * @param schemaContext schema context
493 * @return collection of schema nodes on path
495 public static Collection<SchemaNode> findParentSchemaNodesOnPath(final SchemaContext schemaContext,
496 final Iterable<QName> path) {
497 final Collection<SchemaNode> currentNodes = new ArrayList<>();
498 final Collection<SchemaNode> childNodes = new ArrayList<>();
499 currentNodes.add(requireNonNull(schemaContext));
500 for (final QName qname : path) {
501 for (final SchemaNode current : currentNodes) {
502 childNodes.addAll(findChildSchemaNodesByQName(current, qname));
504 currentNodes.clear();
505 currentNodes.addAll(childNodes);
513 * Find child schema node identified by its QName within a provided schema node. This method performs lookup in both
514 * the namespace of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs,
515 * actions, notifications, anydatas and anyxmls according to RFC6050/RFC7950 section 6.2.1.
518 * This method returns collection of SchemaNodes, because name conflicts can occur between the namespace
519 * of groupings and namespace of data nodes. This method finds and collects all schema nodes with supplied QName
520 * and returns them all as collection of schema nodes.
526 * @return collection of child schema nodes
527 * @throws IllegalArgumentException
528 * if the schema node does not allow children
530 public static Collection<SchemaNode> findChildSchemaNodesByQName(final SchemaNode node, final QName qname) {
531 final List<SchemaNode> childNodes = new ArrayList<>();
532 final SchemaNode dataNode = findDataChildSchemaByQName(node, qname);
533 if (dataNode != null) {
534 childNodes.add(dataNode);
536 if (node instanceof DataNodeContainer) {
537 tryFind(((DataNodeContainer) node).getGroupings(), qname).ifPresent(childNodes::add);
539 return childNodes.isEmpty() ? ImmutableList.of() : ImmutableList.copyOf(childNodes);
542 private static <T extends SchemaNode> Optional<T> tryFind(final Collection<T> nodes, final QName qname) {
543 return nodes.stream().filter(node -> qname.equals(node.getQName())).findFirst();