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 * 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.fromNullable(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.absent();
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 HashSet<QName> qNamesFromAugment = Sets.newHashSet(Collections2.transform(augment.getChildNodes(),
159 DataSchemaNode::getQName));
161 if (qNamesFromAugment.equals(qnames)) {
162 return Optional.of(augment);
166 return Optional.absent();
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 = Maps.newLinkedHashMap();
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 = Maps.newLinkedHashMap();
225 // Find QNames of augmented child nodes
226 final Map<QName, AugmentationSchema> augments = Maps.newHashMap();
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 = Sets.newHashSet();
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();
319 Set<DataSchemaNode> realChildNodes = Sets.newHashSet();
321 if (targetSchema instanceof DataNodeContainer) {
322 realChildNodes = getRealSchemasForAugment((DataNodeContainer)targetSchema, augmentSchema);
323 } else if (targetSchema instanceof ChoiceSchemaNode) {
324 for (final DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
325 for (final ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) targetSchema).getCases()) {
326 if (getChildNodesRecursive(choiceCaseNode).contains(dataSchemaNode.getQName())) {
327 realChildNodes.add(choiceCaseNode.getDataChildByName(dataSchemaNode.getQName()));
333 return realChildNodes;
336 public static Set<DataSchemaNode> getRealSchemasForAugment(final DataNodeContainer targetSchema,
337 final AugmentationSchema augmentSchema) {
338 final Set<DataSchemaNode> realChildNodes = Sets.newHashSet();
339 for (final DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
340 final DataSchemaNode realChild = targetSchema.getDataChildByName(dataSchemaNode.getQName());
341 realChildNodes.add(realChild);
343 return realChildNodes;
346 public static Optional<ChoiceCaseNode> detectCase(final ChoiceSchemaNode schema,
347 final DataContainerChild<?, ?> child) {
348 for (final ChoiceCaseNode choiceCaseNode : schema.getCases()) {
349 if (child instanceof AugmentationNode
350 && belongsToCaseAugment(choiceCaseNode, (AugmentationIdentifier) child.getIdentifier())) {
351 return Optional.of(choiceCaseNode);
352 } else if (choiceCaseNode.getDataChildByName(child.getNodeType()) != null) {
353 return Optional.of(choiceCaseNode);
357 return Optional.absent();
360 public static boolean belongsToCaseAugment(final ChoiceCaseNode caseNode,
361 final AugmentationIdentifier childToProcess) {
362 for (final AugmentationSchema augmentationSchema : caseNode.getAvailableAugmentations()) {
364 final Set<QName> currentAugmentChildNodes = Sets.newHashSet();
365 for (final DataSchemaNode dataSchemaNode : augmentationSchema.getChildNodes()) {
366 currentAugmentChildNodes.add(dataSchemaNode.getQName());
369 if (childToProcess.getPossibleChildNames().equals(currentAugmentChildNodes)) {
378 * Tries to find in {@code parent} which is dealed as augmentation target node with QName as {@code child}. If such
379 * node is found then it is returned, else null.
381 * @param parent parent node
382 * @param child child node
383 * @return augmentation schema
385 public static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
386 if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
387 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
388 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
389 if (childInAugmentation != null) {
397 public static AugmentationIdentifier getNodeIdentifierForAugmentation(final AugmentationSchema schema) {
398 final Collection<QName> qnames = Collections2.transform(schema.getChildNodes(), DataSchemaNode::getQName);
399 return new AugmentationIdentifier(ImmutableSet.copyOf(qnames));
403 * Finds schema node for given path in schema context. This method performs
404 * lookup in the namespace of all leafs, leaf-lists, lists, containers,
405 * choices, rpcs, actions, notifications, anydatas, and anyxmls according to
406 * Rfc6050/Rfc7950 section 6.2.1.
408 * @param schemaContext
412 * @return schema node on path
414 public static SchemaNode findDataParentSchemaOnPath(final SchemaContext schemaContext, final SchemaPath path) {
415 SchemaNode current = Preconditions.checkNotNull(schemaContext);
416 for (final QName qname : path.getPathFromRoot()) {
417 current = findDataChildSchemaByQName(current, qname);
423 * Finds schema node for given path in schema context. This method performs lookup in both the namespace
424 * of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions,
425 * notifications, anydatas and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
428 * This method is deprecated, because name conflicts can occur between the namespace of groupings and namespace
429 * of data nodes and in consequence lookup could be ambiguous.
431 * @param schemaContext
435 * @return schema node on path
437 * @deprecated Use {@link #findParentSchemaNodesOnPath(SchemaContext, SchemaPath)} instead.
440 public static SchemaNode findParentSchemaOnPath(final SchemaContext schemaContext, final SchemaPath path) {
441 SchemaNode current = Preconditions.checkNotNull(schemaContext);
442 for (final QName qname : path.getPathFromRoot()) {
443 current = findChildSchemaByQName(current, qname);
449 * Find child data schema node identified by its QName within a provided schema node. This method performs lookup
450 * in the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions, notifications, anydatas
451 * and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
457 * @return data child schema node
458 * @throws IllegalArgumentException
459 * if the schema node does not allow children
462 public static SchemaNode findDataChildSchemaByQName(final SchemaNode node, final QName qname) {
463 SchemaNode child = null;
464 if (node instanceof DataNodeContainer) {
465 child = ((DataNodeContainer) node).getDataChildByName(qname);
466 if (child == null && node instanceof SchemaContext) {
467 child = tryFindRpc((SchemaContext) node, qname).orNull();
469 if (child == null && node instanceof NotificationNodeContainer) {
470 child = tryFindNotification((NotificationNodeContainer) node, qname).orNull();
472 if (child == null && node instanceof ActionNodeContainer) {
473 child = tryFindAction((ActionNodeContainer) node, qname).orNull();
475 } else if (node instanceof ChoiceSchemaNode) {
476 child = ((ChoiceSchemaNode) node).getCaseNodeByName(qname);
477 } else if (node instanceof RpcDefinition) {
478 switch (qname.getLocalName()) {
480 child = ((RpcDefinition) node).getInput();
483 child = ((RpcDefinition) node).getOutput();
490 throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", node));
497 * Find child schema node identified by its QName within a provided schema node. This method performs lookup
498 * in both the namespace of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs,
499 * actions, notifications, anydatas and anyxmls according to RFC6050/RFC7950 section 6.2.1.
502 * This method is deprecated, because name conflicts can occur between the namespace of groupings and namespace
503 * of data nodes and in consequence lookup could be ambiguous.
509 * @return child schema node
510 * @throws IllegalArgumentException
511 * if the schema node does not allow children
513 * @deprecated Use {@link #findChildSchemaNodesByQName(SchemaNode, QName)} instead.
516 public static SchemaNode findChildSchemaByQName(final SchemaNode node, final QName qname) {
517 SchemaNode child = findDataChildSchemaByQName(node, qname);
518 if (child == null && node instanceof DataNodeContainer) {
519 child = tryFindGroupings((DataNodeContainer) node, qname).orNull();
526 * Finds schema node for given path in schema context. This method performs lookup in both the namespace
527 * of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs, actions,
528 * notifications, anydatas and anyxmls according to Rfc6050/Rfc7950 section 6.2.1.
531 * This method returns collection of SchemaNodes, because name conflicts can occur between the namespace
532 * of groupings and namespace of data nodes. This method finds and collects all schema nodes that matches supplied
533 * SchemaPath and returns them all as collection of schema nodes.
535 * @param schemaContext
539 * @return collection of schema nodes on path
541 public static Collection<SchemaNode> findParentSchemaNodesOnPath(final SchemaContext schemaContext,
542 final SchemaPath path) {
543 final Collection<SchemaNode> currentNodes = new ArrayList<>();
544 final Collection<SchemaNode> childNodes = new ArrayList<>();
545 currentNodes.add(Preconditions.checkNotNull(schemaContext));
546 for (final QName qname : path.getPathFromRoot()) {
547 for (final SchemaNode current : currentNodes) {
548 childNodes.addAll(findChildSchemaNodesByQName(current, qname));
550 currentNodes.clear();
551 currentNodes.addAll(childNodes);
559 * Find child schema node identified by its QName within a provided schema node. This method performs lookup in both
560 * the namespace of groupings and the namespace of all leafs, leaf-lists, lists, containers, choices, rpcs,
561 * actions, notifications, anydatas and anyxmls according to RFC6050/RFC7950 section 6.2.1.
564 * This method returns collection of SchemaNodes, because name conflicts can occur between the namespace
565 * of groupings and namespace of data nodes. This method finds and collects all schema nodes with supplied QName
566 * and returns them all as collection of schema nodes.
572 * @return collection of child schema nodes
573 * @throws IllegalArgumentException
574 * if the schema node does not allow children
576 public static Collection<SchemaNode> findChildSchemaNodesByQName(final SchemaNode node, final QName qname) {
577 final List<SchemaNode> childNodes = new ArrayList<>();
578 final SchemaNode dataNode = findDataChildSchemaByQName(node, qname);
579 if (dataNode != null) {
580 childNodes.add(dataNode);
582 if (node instanceof DataNodeContainer) {
583 final SchemaNode groupingNode = tryFindGroupings((DataNodeContainer) node, qname).orNull();
584 if (groupingNode != null) {
585 childNodes.add(groupingNode);
588 return childNodes.isEmpty() ? Collections.emptyList() : ImmutableList.copyOf(childNodes);
591 private static Optional<SchemaNode> tryFindGroupings(final DataNodeContainer dataNodeContainer, final QName qname) {
593 .fromNullable(Iterables.find(dataNodeContainer.getGroupings(), new SchemaNodePredicate(qname), null));
596 private static Optional<SchemaNode> tryFindRpc(final SchemaContext ctx, final QName qname) {
597 return Optional.fromNullable(Iterables.find(ctx.getOperations(), new SchemaNodePredicate(qname), null));
600 private static Optional<SchemaNode> tryFindNotification(final NotificationNodeContainer notificationContanier,
602 return Optional.fromNullable(
603 Iterables.find(notificationContanier.getNotifications(), new SchemaNodePredicate(qname), null));
606 private static Optional<SchemaNode> tryFindAction(final ActionNodeContainer actionContanier, final QName qname) {
607 return Optional.fromNullable(Iterables.find(actionContanier.getActions(), new SchemaNodePredicate(qname),
611 private static final class SchemaNodePredicate implements Predicate<SchemaNode> {
612 private final QName qname;
614 SchemaNodePredicate(final QName qname) {
619 public boolean apply(final SchemaNode input) {
620 return input.getQName().equals(qname);