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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicate;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Maps;
18 import com.google.common.collect.Sets;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.List;
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 * @param qname - schema node to find
51 * @param dataSchemaNode - iterable of schemaNodes to look through
52 * @return - schema node with newest revision or absent if no schema node with matching qname is found
54 public static Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
55 DataSchemaNode sNode = null;
56 if (dataSchemaNode != null && qname != null) {
57 for (final DataSchemaNode dsn : dataSchemaNode) {
58 if (qname.isEqualWithoutRevision(dsn.getQName())) {
59 if (sNode == null || sNode.getQName().getRevision().compareTo(dsn.getQName().getRevision()) < 0) {
62 } else if (dsn instanceof ChoiceSchemaNode) {
63 for (final ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
65 final DataSchemaNode dataChildByName = choiceCase.getDataChildByName(qname);
66 if (dataChildByName != null) {
67 return Optional.of(dataChildByName);
69 final Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
70 if (foundDsn.isPresent()) {
77 return Optional.fromNullable(sNode);
82 * Find child schema node identified by its QName within a provided schema node
84 * @param schema schema for parent node - search root
85 * @param qname qname(with or without a revision) of a child node to be found in the parent schema
86 * @return found schema node
87 * @throws java.lang.IllegalStateException if the child was not found in parent schema node
89 public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname) {
90 // Try to find child schema node directly, but use a fallback that compares QNames without revisions and auto-expands choices
91 final DataSchemaNode dataChildByName = schema.getDataChildByName(qname);
92 return dataChildByName == null ? findSchemaForChild(schema, qname, schema.getChildNodes()) : dataChildByName;
96 public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname, final boolean strictMode) {
98 return findSchemaForChild(schema, qname);
101 final Optional<DataSchemaNode> childSchemaOptional = findFirstSchema(qname, schema.getChildNodes());
102 if (!childSchemaOptional.isPresent()) {
105 return childSchemaOptional.get();
108 public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname, final Iterable<DataSchemaNode> childNodes) {
109 final Optional<DataSchemaNode> childSchema = findFirstSchema(qname, childNodes);
110 Preconditions.checkState(childSchema.isPresent(),
111 "Unknown child(ren) node(s) detected, identified by: %s, in: %s", qname, schema);
112 return childSchema.get();
115 public static AugmentationSchema findSchemaForAugment(final AugmentationTarget schema, final Set<QName> qNames) {
116 final Optional<AugmentationSchema> schemaForAugment = findAugment(schema, qNames);
117 Preconditions.checkState(schemaForAugment.isPresent(), "Unknown augmentation node detected, identified by: %s, in: %s",
119 return schemaForAugment.get();
122 public static AugmentationSchema findSchemaForAugment(final ChoiceSchemaNode schema, final Set<QName> qNames) {
123 Optional<AugmentationSchema> schemaForAugment = Optional.absent();
125 for (final ChoiceCaseNode choiceCaseNode : schema.getCases()) {
126 schemaForAugment = findAugment(choiceCaseNode, qNames);
127 if (schemaForAugment.isPresent()) {
132 Preconditions.checkState(schemaForAugment.isPresent(), "Unknown augmentation node detected, identified by: %s, in: %s",
134 return schemaForAugment.get();
137 private static Optional<AugmentationSchema> findAugment(final AugmentationTarget schema, final Set<QName> qNames) {
138 for (final AugmentationSchema augment : schema.getAvailableAugmentations()) {
139 final HashSet<QName> qNamesFromAugment = Sets.newHashSet(Collections2.transform(augment.getChildNodes(),
140 DataSchemaNode::getQName));
142 if (qNamesFromAugment.equals(qNames)) {
143 return Optional.of(augment);
147 return Optional.absent();
150 public static DataSchemaNode findSchemaForChild(final ChoiceSchemaNode schema, final QName childPartialQName) {
151 for (final ChoiceCaseNode choiceCaseNode : schema.getCases()) {
152 final Optional<DataSchemaNode> childSchema = findFirstSchema(childPartialQName, choiceCaseNode.getChildNodes());
153 if (childSchema.isPresent()) {
154 return childSchema.get();
159 throw new IllegalStateException(String.format("Unknown child(ren) node(s) detected, identified by: %s, in: %s",
160 childPartialQName, schema));
164 * Recursively find all child nodes that come from choices.
166 * @param schema schema
167 * @return Map with all child nodes, to their most top augmentation
169 public static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
170 return mapChildElementsFromChoices(schema, schema.getChildNodes());
173 private static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema, final Iterable<DataSchemaNode> childNodes) {
174 final Map<QName, ChoiceSchemaNode> mappedChoices = Maps.newLinkedHashMap();
176 for (final DataSchemaNode childSchema : childNodes) {
177 if (childSchema instanceof ChoiceSchemaNode) {
179 if (isFromAugment(schema, childSchema)) {
183 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
185 for (final QName qName : getChildNodesRecursive(choiceCaseNode)) {
186 mappedChoices.put(qName, (ChoiceSchemaNode) childSchema);
192 return mappedChoices;
195 private static boolean isFromAugment(final DataNodeContainer schema, final DataSchemaNode childSchema) {
196 if (!(schema instanceof AugmentationTarget)) {
200 for (final AugmentationSchema augmentationSchema : ((AugmentationTarget) schema).getAvailableAugmentations()) {
201 if (augmentationSchema.getDataChildByName(childSchema.getQName()) != null) {
210 * Recursively find all child nodes that come from augmentations.
212 * @param schema schema
213 * @return Map with all child nodes, to their most top augmentation
215 public static Map<QName, AugmentationSchema> mapChildElementsFromAugments(final AugmentationTarget schema) {
217 final Map<QName, AugmentationSchema> childNodesToAugmentation = Maps.newLinkedHashMap();
219 // Find QNames of augmented child nodes
220 final Map<QName, AugmentationSchema> augments = Maps.newHashMap();
221 for (final AugmentationSchema augmentationSchema : schema.getAvailableAugmentations()) {
222 for (final DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
223 augments.put(dataSchemaNode.getQName(), augmentationSchema);
227 // Augmented nodes have to be looked up directly in augmentationTarget
228 // because nodes from augment do not contain nodes from other augmentations
229 if (schema instanceof DataNodeContainer) {
231 for (final DataSchemaNode child : ((DataNodeContainer) schema).getChildNodes()) {
232 // If is not augmented child, continue
233 if (!(augments.containsKey(child.getQName()))) {
237 final AugmentationSchema mostTopAugmentation = augments.get(child.getQName());
239 // recursively add all child nodes in case of augment, case and choice
240 if (child instanceof AugmentationSchema || child instanceof ChoiceCaseNode) {
241 for (final QName qName : getChildNodesRecursive((DataNodeContainer) child)) {
242 childNodesToAugmentation.put(qName, mostTopAugmentation);
244 } else if (child instanceof ChoiceSchemaNode) {
245 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) child).getCases()) {
246 for (final QName qName : getChildNodesRecursive(choiceCaseNode)) {
247 childNodesToAugmentation.put(qName, mostTopAugmentation);
251 childNodesToAugmentation.put(child.getQName(), mostTopAugmentation);
256 // Choice Node has to map child nodes from all its cases
257 if (schema instanceof ChoiceSchemaNode) {
258 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) schema).getCases()) {
259 if (!(augments.containsKey(choiceCaseNode.getQName()))) {
263 for (final QName qName : getChildNodesRecursive(choiceCaseNode)) {
264 childNodesToAugmentation.put(qName, augments.get(choiceCaseNode.getQName()));
269 return childNodesToAugmentation;
273 * Recursively list all child nodes.
275 * In case of choice, augment and cases, step in.
277 * @param nodeContainer node container
278 * @return set of QNames
280 public static Set<QName> getChildNodesRecursive(final DataNodeContainer nodeContainer) {
281 final Set<QName> allChildNodes = Sets.newHashSet();
283 for (final DataSchemaNode childSchema : nodeContainer.getChildNodes()) {
284 if (childSchema instanceof ChoiceSchemaNode) {
285 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
286 allChildNodes.addAll(getChildNodesRecursive(choiceCaseNode));
288 } else if (childSchema instanceof AugmentationSchema || childSchema instanceof ChoiceCaseNode) {
289 allChildNodes.addAll(getChildNodesRecursive((DataNodeContainer) childSchema));
292 allChildNodes.add(childSchema.getQName());
296 return allChildNodes;
300 * Retrieves real schemas for augmented child node.
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.
305 * @param targetSchema target schema
306 * @param augmentSchema augment schema
307 * @return set of nodes
309 public static Set<DataSchemaNode> getRealSchemasForAugment(final AugmentationTarget targetSchema, final AugmentationSchema augmentSchema) {
310 if (!(targetSchema.getAvailableAugmentations().contains(augmentSchema))) {
311 return Collections.emptySet();
314 Set<DataSchemaNode> realChildNodes = Sets.newHashSet();
316 if (targetSchema instanceof DataNodeContainer) {
317 realChildNodes = getRealSchemasForAugment((DataNodeContainer)targetSchema, augmentSchema);
318 } else if (targetSchema instanceof ChoiceSchemaNode) {
319 for (final DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
320 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) targetSchema).getCases()) {
321 if (getChildNodesRecursive(choiceCaseNode).contains(dataSchemaNode.getQName())) {
322 realChildNodes.add(choiceCaseNode.getDataChildByName(dataSchemaNode.getQName()));
328 return realChildNodes;
331 public static Set<DataSchemaNode> getRealSchemasForAugment(final DataNodeContainer targetSchema,
332 final AugmentationSchema augmentSchema) {
333 final Set<DataSchemaNode> realChildNodes = Sets.newHashSet();
334 for (final DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
335 final DataSchemaNode realChild = targetSchema.getDataChildByName(dataSchemaNode.getQName());
336 realChildNodes.add(realChild);
338 return realChildNodes;
341 public static Optional<ChoiceCaseNode> detectCase(final ChoiceSchemaNode schema, final DataContainerChild<?, ?> child) {
342 for (final ChoiceCaseNode choiceCaseNode : schema.getCases()) {
343 if (child instanceof AugmentationNode
344 && belongsToCaseAugment(choiceCaseNode, (AugmentationIdentifier) child.getIdentifier())) {
345 return Optional.of(choiceCaseNode);
346 } else if (choiceCaseNode.getDataChildByName(child.getNodeType()) != null) {
347 return Optional.of(choiceCaseNode);
351 return Optional.absent();
354 public static boolean belongsToCaseAugment(final ChoiceCaseNode caseNode, final AugmentationIdentifier childToProcess) {
355 for (final AugmentationSchema augmentationSchema : caseNode.getAvailableAugmentations()) {
357 final Set<QName> currentAugmentChildNodes = Sets.newHashSet();
358 for (final DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
359 currentAugmentChildNodes.add(dataSchemaNode.getQName());
362 if (childToProcess.getPossibleChildNames().equals(currentAugmentChildNodes)){
371 * Tries to find in {@code parent} which is dealed as augmentation target node with QName as {@code child}. If such
372 * node is found then it is returned, else null.
374 * @param parent parent node
375 * @param child child node
376 * @return augmentation schema
378 public static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
379 if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
380 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
381 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
382 if (childInAugmentation != null) {
390 public static AugmentationIdentifier getNodeIdentifierForAugmentation(final AugmentationSchema schema) {
391 final Collection<QName> qnames = Collections2.transform(schema.getChildNodes(), DataSchemaNode::getQName);
392 return new AugmentationIdentifier(ImmutableSet.copyOf(qnames));
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 = Preconditions.checkNotNull(schemaContext);
409 for (final QName qname : path.getPathFromRoot()) {
410 current = findDataChildSchemaByQName(current, qname);
416 * Finds schema node for given path in schema context. This method performs
417 * lookup in both the namespace of groupings and the namespace of all leafs,
418 * leaf-lists, lists, containers, choices, rpcs, actions, notifications,
419 * anydatas, and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
421 * This method is deprecated, because name conflicts can occur between the
422 * namespace of groupings and namespace of data nodes and in consequence
423 * lookup could be ambiguous.
425 * @param schemaContext
429 * @return schema node on path
432 * {@link #findParentSchemaNodesOnPath(SchemaContext, SchemaPath)}
436 public static SchemaNode findParentSchemaOnPath(final SchemaContext schemaContext, final SchemaPath path) {
437 SchemaNode current = Preconditions.checkNotNull(schemaContext);
438 for (final QName qname : path.getPathFromRoot()) {
439 current = findChildSchemaByQName(current, qname);
445 * Find child data schema node identified by its QName within a provided
446 * schema node. This method performs lookup in the namespace of all leafs,
447 * leaf-lists, lists, containers, choices, rpcs, actions, notifications,
448 * anydatas, and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
454 * @return data child schema node
455 * @throws java.lang.IllegalArgumentException
456 * if the schema node does not allow children
459 public static SchemaNode findDataChildSchemaByQName(final SchemaNode node, final QName qname) {
460 SchemaNode child = null;
461 if (node instanceof DataNodeContainer) {
462 child = ((DataNodeContainer) node).getDataChildByName(qname);
463 if (child == null && node instanceof SchemaContext) {
464 child = tryFindRpc((SchemaContext) node, qname).orNull();
466 if (child == null && node instanceof NotificationNodeContainer) {
467 child = tryFindNotification((NotificationNodeContainer) node, qname).orNull();
469 if (child == null && node instanceof ActionNodeContainer) {
470 child = tryFindAction((ActionNodeContainer) node, qname).orNull();
472 } else if (node instanceof ChoiceSchemaNode) {
473 child = ((ChoiceSchemaNode) node).getCaseNodeByName(qname);
474 } else if (node instanceof RpcDefinition) {
475 switch (qname.getLocalName()) {
477 child = ((RpcDefinition) node).getInput();
480 child = ((RpcDefinition) node).getOutput();
487 throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", node));
494 * Find child schema node identified by its QName within a provided schema
495 * node. This method performs lookup in both the namespace of groupings and
496 * the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs,
497 * actions, notifications, anydatas, and anyxmls according to
498 * Rfc6050/Rfc7950 section 6.2.1.
500 * This method is deprecated, because name conflicts can occur between the
501 * namespace of groupings and namespace of data nodes and in consequence
502 * lookup could be ambiguous.
508 * @return child schema node
509 * @throws java.lang.IllegalArgumentException
510 * if the schema node does not allow children
513 * {@link #findChildSchemaNodesByQName(SchemaNode, QName)}
517 public static SchemaNode findChildSchemaByQName(final SchemaNode node, final QName qname) {
518 SchemaNode child = findDataChildSchemaByQName(node, qname);
519 if (child == null && node instanceof DataNodeContainer) {
520 child = tryFindGroupings((DataNodeContainer) node, qname).orNull();
527 * Finds schema node for given path in schema context. This method performs
528 * lookup in both the namespace of groupings and the namespace of all leafs,
529 * leaf-lists, lists, containers, choices, rpcs, actions, notifications,
530 * anydatas, and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
532 * This method returns collection of SchemaNodes, because name conflicts can
533 * occur between the namespace of groupings and namespace of data nodes.
534 * This method finds and collects all schema nodes that matches supplied
535 * SchemaPath and returns them all as collection of schema nodes.
537 * @param schemaContext
541 * @return collection of schema nodes on path
544 public static Collection<SchemaNode> findParentSchemaNodesOnPath(final SchemaContext schemaContext,
545 final SchemaPath path) {
546 final Collection<SchemaNode> currentNodes = new ArrayList<>();
547 final Collection<SchemaNode> childNodes = new ArrayList<>();
548 currentNodes.add(Preconditions.checkNotNull(schemaContext));
549 for (final QName qname : path.getPathFromRoot()) {
550 for (final SchemaNode current : currentNodes) {
551 childNodes.addAll(findChildSchemaNodesByQName(current, qname));
553 currentNodes.clear();
554 currentNodes.addAll(childNodes);
562 * Find child schema node identified by its QName within a provided schema
563 * node. This method performs lookup in both the namespace of groupings and
564 * the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs,
565 * actions, notifications, anydatas, and anyxmls according to
566 * Rfc6050/Rfc7950 section 6.2.1.
568 * This method returns collection of SchemaNodes, because name conflicts can
569 * occur between the namespace of groupings and namespace of data nodes.
570 * This method finds and collects all schema nodes with supplied QName and
571 * returns them all as collection of schema nodes.
577 * @return collection of child schema nodes
578 * @throws java.lang.IllegalArgumentException
579 * if the schema node does not allow children
582 public static Collection<SchemaNode> findChildSchemaNodesByQName(final SchemaNode node, final QName qname) {
583 final List<SchemaNode> childNodes = new ArrayList<>();
584 final SchemaNode dataNode = findDataChildSchemaByQName(node, qname);
585 if (dataNode != null) {
586 childNodes.add(dataNode);
588 if (node instanceof DataNodeContainer) {
589 final SchemaNode groupingNode = tryFindGroupings((DataNodeContainer) node, qname).orNull();
590 if (groupingNode != null) {
591 childNodes.add(groupingNode);
594 return childNodes.isEmpty() ? Collections.emptyList() : ImmutableList.copyOf(childNodes);
597 private static Optional<SchemaNode> tryFindGroupings(final DataNodeContainer dataNodeContainer, final QName qname) {
599 .fromNullable(Iterables.find(dataNodeContainer.getGroupings(), new SchemaNodePredicate(qname), null));
602 private static Optional<SchemaNode> tryFindRpc(final SchemaContext ctx, final QName qname) {
603 return Optional.fromNullable(Iterables.find(ctx.getOperations(), new SchemaNodePredicate(qname), null));
606 private static Optional<SchemaNode> tryFindNotification(final NotificationNodeContainer notificationContanier,
608 return Optional.fromNullable(
609 Iterables.find(notificationContanier.getNotifications(), new SchemaNodePredicate(qname), null));
612 private static Optional<SchemaNode> tryFindAction(final ActionNodeContainer actionContanier, final QName qname) {
613 return Optional.fromNullable(Iterables.find(actionContanier.getActions(), new SchemaNodePredicate(qname), null));
616 private static final class SchemaNodePredicate implements Predicate<SchemaNode> {
617 private final QName qname;
619 public SchemaNodePredicate(final QName qname) {
624 public boolean apply(final SchemaNode input) {
625 return input.getQName().equals(qname);