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 com.google.common.base.Preconditions;
11 import com.google.common.base.Predicate;
12 import com.google.common.collect.Collections2;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.Iterables;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.LinkedHashMap;
22 import java.util.List;
24 import java.util.Optional;
26 import javax.annotation.Nullable;
27 import org.opendaylight.yangtools.yang.common.QName;
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.AugmentationSchema;
33 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
34 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
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.RpcDefinition;
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() {
46 throw new UnsupportedOperationException();
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<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 || schema.getQName().getRevision().compareTo(dsn.getQName().getRevision()) < 0) {
65 } else if (dsn instanceof ChoiceSchemaNode) {
66 for (final ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
68 final DataSchemaNode dataChildByName = choiceCase.getDataChildByName(qname);
69 if (dataChildByName != null) {
70 return Optional.of(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 DataSchemaNode dataChildByName = schema.getDataChildByName(qname);
95 return dataChildByName == null ? findSchemaForChild(schema, qname, schema.getChildNodes()) : dataChildByName;
99 public static 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<DataSchemaNode> childNodes) {
114 final Optional<DataSchemaNode> childSchema = findFirstSchema(qname, childNodes);
115 Preconditions.checkState(childSchema.isPresent(),
116 "Unknown child(ren) node(s) detected, identified by: %s, in: %s", qname, schema);
117 return childSchema.get();
120 public static DataSchemaNode findSchemaForChild(final ChoiceSchemaNode schema, final QName childPartialQName) {
121 for (final ChoiceCaseNode 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 AugmentationSchema findSchemaForAugment(final AugmentationTarget schema, final Set<QName> qnames) {
135 final Optional<AugmentationSchema> schemaForAugment = findAugment(schema, qnames);
136 Preconditions.checkState(schemaForAugment.isPresent(),
137 "Unknown augmentation node detected, identified by: %s, in: %s", qnames, schema);
138 return schemaForAugment.get();
141 public static AugmentationSchema findSchemaForAugment(final ChoiceSchemaNode schema, final Set<QName> qnames) {
142 Optional<AugmentationSchema> schemaForAugment = Optional.empty();
144 for (final ChoiceCaseNode choiceCaseNode : schema.getCases()) {
145 schemaForAugment = findAugment(choiceCaseNode, qnames);
146 if (schemaForAugment.isPresent()) {
151 Preconditions.checkState(schemaForAugment.isPresent(),
152 "Unknown augmentation node detected, identified by: %s, in: %s", qnames, schema);
153 return schemaForAugment.get();
156 private static Optional<AugmentationSchema> findAugment(final AugmentationTarget schema, final Set<QName> qnames) {
157 for (final AugmentationSchema augment : schema.getAvailableAugmentations()) {
158 final Set<QName> qNamesFromAugment = ImmutableSet.copyOf(Collections2.transform(augment.getChildNodes(),
159 DataSchemaNode::getQName));
161 if (qNamesFromAugment.equals(qnames)) {
162 return Optional.of(augment);
166 return Optional.empty();
170 * Recursively find all child nodes that come from choices.
172 * @param schema schema
173 * @return Map with all child nodes, to their most top augmentation
175 public static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
176 return mapChildElementsFromChoices(schema, schema.getChildNodes());
179 private static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema,
180 final Iterable<DataSchemaNode> childNodes) {
181 final Map<QName, ChoiceSchemaNode> mappedChoices = new LinkedHashMap<>();
183 for (final DataSchemaNode childSchema : childNodes) {
184 if (childSchema instanceof ChoiceSchemaNode) {
186 if (isFromAugment(schema, childSchema)) {
190 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
191 for (final QName qname : getChildNodesRecursive(choiceCaseNode)) {
192 mappedChoices.put(qname, (ChoiceSchemaNode) childSchema);
198 return mappedChoices;
201 private static boolean isFromAugment(final DataNodeContainer schema, final DataSchemaNode childSchema) {
202 if (!(schema instanceof AugmentationTarget)) {
206 for (final AugmentationSchema augmentationSchema : ((AugmentationTarget) schema).getAvailableAugmentations()) {
207 if (augmentationSchema.getDataChildByName(childSchema.getQName()) != null) {
216 * Recursively find all child nodes that come from augmentations.
218 * @param schema schema
219 * @return Map with all child nodes, to their most top augmentation
221 public static Map<QName, AugmentationSchema> mapChildElementsFromAugments(final AugmentationTarget schema) {
223 final Map<QName, AugmentationSchema> childNodesToAugmentation = new LinkedHashMap<>();
225 // Find QNames of augmented child nodes
226 final Map<QName, AugmentationSchema> augments = new HashMap<>();
227 for (final AugmentationSchema augmentationSchema : schema.getAvailableAugmentations()) {
228 for (final DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
229 augments.put(dataSchemaNode.getQName(), augmentationSchema);
233 // Augmented nodes have to be looked up directly in augmentationTarget
234 // because nodes from augment do not contain nodes from other augmentations
235 if (schema instanceof DataNodeContainer) {
237 for (final DataSchemaNode child : ((DataNodeContainer) schema).getChildNodes()) {
238 // If is not augmented child, continue
239 if (!augments.containsKey(child.getQName())) {
243 final AugmentationSchema mostTopAugmentation = augments.get(child.getQName());
245 // recursively add all child nodes in case of augment, case and choice
246 if (child instanceof AugmentationSchema || child instanceof ChoiceCaseNode) {
247 for (final QName qname : getChildNodesRecursive((DataNodeContainer) child)) {
248 childNodesToAugmentation.put(qname, mostTopAugmentation);
250 } else if (child instanceof ChoiceSchemaNode) {
251 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) child).getCases()) {
252 for (final QName qname : getChildNodesRecursive(choiceCaseNode)) {
253 childNodesToAugmentation.put(qname, mostTopAugmentation);
257 childNodesToAugmentation.put(child.getQName(), mostTopAugmentation);
262 // Choice Node has to map child nodes from all its cases
263 if (schema instanceof ChoiceSchemaNode) {
264 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) schema).getCases()) {
265 if (!augments.containsKey(choiceCaseNode.getQName())) {
269 for (final QName qname : getChildNodesRecursive(choiceCaseNode)) {
270 childNodesToAugmentation.put(qname, augments.get(choiceCaseNode.getQName()));
275 return childNodesToAugmentation;
279 * Recursively list all child nodes. In case of choice, augment and cases, step in.
281 * @param nodeContainer node container
282 * @return set of QNames
284 public static Set<QName> getChildNodesRecursive(final DataNodeContainer nodeContainer) {
285 final Set<QName> allChildNodes = new HashSet<>();
287 for (final DataSchemaNode childSchema : nodeContainer.getChildNodes()) {
288 if (childSchema instanceof ChoiceSchemaNode) {
289 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
290 allChildNodes.addAll(getChildNodesRecursive(choiceCaseNode));
292 } else if (childSchema instanceof AugmentationSchema || childSchema instanceof ChoiceCaseNode) {
293 allChildNodes.addAll(getChildNodesRecursive((DataNodeContainer) childSchema));
295 allChildNodes.add(childSchema.getQName());
299 return allChildNodes;
303 * Retrieves real schemas for augmented child node.
306 * Schema of the same child node from augment, and directly from target is not the same.
307 * Schema of child node from augment is incomplete, therefore its useless for XML/NormalizedNode translation.
309 * @param targetSchema target schema
310 * @param augmentSchema augment schema
311 * @return set of nodes
313 public static Set<DataSchemaNode> getRealSchemasForAugment(final AugmentationTarget targetSchema,
314 final AugmentationSchema augmentSchema) {
315 if (!targetSchema.getAvailableAugmentations().contains(augmentSchema)) {
316 return Collections.emptySet();
318 if (targetSchema instanceof DataNodeContainer) {
319 return getRealSchemasForAugment((DataNodeContainer)targetSchema, augmentSchema);
321 final Set<DataSchemaNode> realChildNodes = new HashSet<>();
322 if (targetSchema instanceof ChoiceSchemaNode) {
323 for (final DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
324 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) targetSchema).getCases()) {
325 if (getChildNodesRecursive(choiceCaseNode).contains(dataSchemaNode.getQName())) {
326 realChildNodes.add(choiceCaseNode.getDataChildByName(dataSchemaNode.getQName()));
332 return realChildNodes;
335 public static Set<DataSchemaNode> getRealSchemasForAugment(final DataNodeContainer targetSchema,
336 final AugmentationSchema augmentSchema) {
337 final Set<DataSchemaNode> realChildNodes = new HashSet<>();
338 for (final DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
339 final DataSchemaNode realChild = targetSchema.getDataChildByName(dataSchemaNode.getQName());
340 realChildNodes.add(realChild);
342 return realChildNodes;
345 public static Optional<ChoiceCaseNode> detectCase(final ChoiceSchemaNode schema,
346 final DataContainerChild<?, ?> child) {
347 for (final 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);
356 return Optional.empty();
359 public static boolean belongsToCaseAugment(final ChoiceCaseNode caseNode,
360 final AugmentationIdentifier childToProcess) {
361 for (final AugmentationSchema augmentationSchema : caseNode.getAvailableAugmentations()) {
363 final Set<QName> currentAugmentChildNodes = new HashSet<>();
364 for (final DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
365 currentAugmentChildNodes.add(dataSchemaNode.getQName());
368 if (childToProcess.getPossibleChildNames().equals(currentAugmentChildNodes)) {
377 * Tries to find in {@code parent} which is dealed as augmentation target node with QName as {@code child}. If such
378 * node is found then it is returned, else null.
380 * @param parent parent node
381 * @param child child node
382 * @return augmentation schema
384 public static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
385 if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
386 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
387 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
388 if (childInAugmentation != null) {
396 public static AugmentationIdentifier getNodeIdentifierForAugmentation(final AugmentationSchema schema) {
397 final Collection<QName> qnames = Collections2.transform(schema.getChildNodes(), DataSchemaNode::getQName);
398 return new AugmentationIdentifier(ImmutableSet.copyOf(qnames));
402 * Finds schema node for given path in schema context. This method performs
403 * lookup in the namespace of all leafs, leaf-lists, lists, containers,
404 * choices, rpcs, actions, notifications, anydatas, and anyxmls according to
405 * Rfc6050/Rfc7950 section 6.2.1.
407 * @param schemaContext
411 * @return schema node on path
413 public static SchemaNode findDataParentSchemaOnPath(final SchemaContext schemaContext, final SchemaPath path) {
414 SchemaNode current = Preconditions.checkNotNull(schemaContext);
415 for (final QName qname : path.getPathFromRoot()) {
416 current = findDataChildSchemaByQName(current, qname);
422 * Finds schema node for given path in schema context. This method performs lookup in both the namespace
423 * of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions,
424 * notifications, anydatas and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
427 * This method is deprecated, because name conflicts can occur between the namespace of groupings and namespace
428 * of data nodes and in consequence lookup could be ambiguous.
430 * @param schemaContext
434 * @return schema node on path
436 * @deprecated Use {@link #findParentSchemaNodesOnPath(SchemaContext, SchemaPath)} instead.
439 public static SchemaNode findParentSchemaOnPath(final SchemaContext schemaContext, final SchemaPath path) {
440 SchemaNode current = Preconditions.checkNotNull(schemaContext);
441 for (final QName qname : path.getPathFromRoot()) {
442 current = findChildSchemaByQName(current, qname);
448 * Find child data schema node identified by its QName within a provided schema node. This method performs lookup
449 * in the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions, notifications, anydatas
450 * and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
456 * @return data child schema node
457 * @throws IllegalArgumentException
458 * if the schema node does not allow children
461 public static SchemaNode findDataChildSchemaByQName(final SchemaNode node, final QName qname) {
462 SchemaNode child = null;
463 if (node instanceof DataNodeContainer) {
464 child = ((DataNodeContainer) node).getDataChildByName(qname);
465 if (child == null && node instanceof SchemaContext) {
466 child = tryFindRpc((SchemaContext) node, qname).orElse(null);
468 if (child == null && node instanceof NotificationNodeContainer) {
469 child = tryFindNotification((NotificationNodeContainer) node, qname).orElse(null);
471 if (child == null && node instanceof ActionNodeContainer) {
472 child = tryFindAction((ActionNodeContainer) node, qname).orElse(null);
474 } else if (node instanceof ChoiceSchemaNode) {
475 child = ((ChoiceSchemaNode) node).getCaseNodeByName(qname);
476 } else if (node instanceof RpcDefinition) {
477 switch (qname.getLocalName()) {
479 child = ((RpcDefinition) node).getInput();
482 child = ((RpcDefinition) node).getOutput();
489 throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", node));
496 * Find child schema node identified by its QName within a provided schema node. This method performs lookup
497 * in both the namespace of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs,
498 * actions, notifications, anydatas and anyxmls according to RFC6050/RFC7950 section 6.2.1.
501 * This method is deprecated, because name conflicts can occur between the namespace of groupings and namespace
502 * of data nodes and in consequence lookup could be ambiguous.
508 * @return child schema node
509 * @throws IllegalArgumentException
510 * if the schema node does not allow children
512 * @deprecated Use {@link #findChildSchemaNodesByQName(SchemaNode, QName)} instead.
515 public static SchemaNode findChildSchemaByQName(final SchemaNode node, final QName qname) {
516 SchemaNode child = findDataChildSchemaByQName(node, qname);
517 if (child == null && node instanceof DataNodeContainer) {
518 child = tryFindGroupings((DataNodeContainer) node, qname).orElse(null);
525 * Finds schema node for given path in schema context. This method performs lookup in both the namespace
526 * of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions,
527 * notifications, anydatas and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
530 * This method returns collection of SchemaNodes, because name conflicts can occur between the namespace
531 * of groupings and namespace of data nodes. This method finds and collects all schema nodes that matches supplied
532 * SchemaPath and returns them all as collection of schema nodes.
534 * @param schemaContext
538 * @return collection of schema nodes on path
540 public static Collection<SchemaNode> findParentSchemaNodesOnPath(final SchemaContext schemaContext,
541 final SchemaPath path) {
542 final Collection<SchemaNode> currentNodes = new ArrayList<>();
543 final Collection<SchemaNode> childNodes = new ArrayList<>();
544 currentNodes.add(Preconditions.checkNotNull(schemaContext));
545 for (final QName qname : path.getPathFromRoot()) {
546 for (final SchemaNode current : currentNodes) {
547 childNodes.addAll(findChildSchemaNodesByQName(current, qname));
549 currentNodes.clear();
550 currentNodes.addAll(childNodes);
558 * Find child schema node identified by its QName within a provided schema node. This method performs lookup in both
559 * the namespace of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs,
560 * actions, notifications, anydatas and anyxmls according to RFC6050/RFC7950 section 6.2.1.
563 * This method returns collection of SchemaNodes, because name conflicts can occur between the namespace
564 * of groupings and namespace of data nodes. This method finds and collects all schema nodes with supplied QName
565 * and returns them all as collection of schema nodes.
571 * @return collection of child schema nodes
572 * @throws IllegalArgumentException
573 * if the schema node does not allow children
575 public static Collection<SchemaNode> findChildSchemaNodesByQName(final SchemaNode node, final QName qname) {
576 final List<SchemaNode> childNodes = new ArrayList<>();
577 final SchemaNode dataNode = findDataChildSchemaByQName(node, qname);
578 if (dataNode != null) {
579 childNodes.add(dataNode);
581 if (node instanceof DataNodeContainer) {
582 tryFindGroupings((DataNodeContainer) node, qname).ifPresent(childNodes::add);
584 return childNodes.isEmpty() ? Collections.emptyList() : ImmutableList.copyOf(childNodes);
587 private static Optional<SchemaNode> tryFindGroupings(final DataNodeContainer dataNodeContainer, final QName qname) {
589 .ofNullable(Iterables.find(dataNodeContainer.getGroupings(), new SchemaNodePredicate(qname), null));
592 private static Optional<SchemaNode> tryFindRpc(final SchemaContext ctx, final QName qname) {
593 return Optional.ofNullable(Iterables.find(ctx.getOperations(), new SchemaNodePredicate(qname), null));
596 private static Optional<SchemaNode> tryFindNotification(final NotificationNodeContainer notificationContanier,
598 return Optional.ofNullable(
599 Iterables.find(notificationContanier.getNotifications(), new SchemaNodePredicate(qname), null));
602 private static Optional<SchemaNode> tryFindAction(final ActionNodeContainer actionContanier, final QName qname) {
603 return Optional.ofNullable(Iterables.find(actionContanier.getActions(), new SchemaNodePredicate(qname), null));
606 private static final class SchemaNodePredicate implements Predicate<SchemaNode> {
607 private final QName qname;
609 SchemaNodePredicate(final QName qname) {
614 public boolean apply(final SchemaNode input) {
615 return input.getQName().equals(qname);