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.model.util;
10 import com.google.common.annotations.Beta;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.Iterables;
15 import java.util.HashSet;
16 import java.util.Iterator;
17 import java.util.LinkedList;
18 import java.util.List;
19 import java.util.Optional;
21 import java.util.regex.Pattern;
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
26 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
32 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
36 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
37 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
38 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
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;
43 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * The Schema Context Util contains support methods for searching through Schema
51 * Context modules for specified schema nodes via Schema Path or Revision Aware
52 * XPath. The Schema Context Util is designed as mixin, so it is not
56 public final class SchemaContextUtil {
57 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
58 private static final Splitter COLON_SPLITTER = Splitter.on(':');
59 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
61 private SchemaContextUtil() {
65 * Method attempts to find DataSchemaNode in Schema Context via specified
66 * Schema Path. The returned DataSchemaNode from method will be the node at
67 * the end of the SchemaPath. If the DataSchemaNode is not present in the
68 * Schema Context the method will return <code>null</code>. <br>
69 * In case that Schema Context or Schema Path are not specified correctly
70 * (i.e. contains <code>null</code> values) the method will throw
71 * IllegalArgumentException.
76 * Schema Path to search for
77 * @return SchemaNode from the end of the Schema Path or <code>null</code>
78 * if the Node is not present.
79 * @throws IllegalArgumentException if context or schemaPath is not correct.
81 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
82 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
83 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
85 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
86 if (prefixedPath == null) {
87 LOG.debug("Schema path {} has null path", schemaPath);
91 LOG.trace("Looking for path {} in context {}", schemaPath, context);
92 return findNodeInSchemaContext(context, prefixedPath);
96 * Method attempts to find DataSchemaNode inside of provided Schema Context
97 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
98 * specified Module MUST be present in Schema Context otherwise the
99 * operation would fail and return <code>null</code>. <br>
100 * The Revision Aware XPath MUST be specified WITHOUT the conditional
101 * statement (i.e. without [cond]) in path, because in this state the Schema
102 * Context is completely unaware of data state and will be not able to
103 * properly resolve XPath. If the XPath contains condition the method will
104 * return IllegalArgumentException. <br>
105 * In case that Schema Context or Module or Revision Aware XPath contains
106 * <code>null</code> references the method will throw
107 * IllegalArgumentException <br>
108 * If the Revision Aware XPath is correct and desired Data Schema Node is
109 * present in Yang module or in depending module in Schema Context the
110 * method will return specified Data Schema Node, otherwise the operation
111 * will fail and method will return <code>null</code>.
117 * @param nonCondXPath
118 * Non Conditional Revision Aware XPath
119 * @return Returns Data Schema Node for specified Schema Context for given
120 * Non-conditional Revision Aware XPath, or <code>null</code> if the
121 * DataSchemaNode is not present in Schema Context.
123 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
124 final RevisionAwareXPath nonCondXPath) {
125 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
126 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
127 Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
129 final String strXPath = nonCondXPath.toString();
130 if (strXPath != null) {
131 Preconditions.checkArgument(strXPath.indexOf('[') == -1,
132 "Revision Aware XPath may not contain a condition");
133 if (nonCondXPath.isAbsolute()) {
134 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
135 if (qnamedPath != null) {
136 return findNodeInSchemaContext(context, qnamedPath);
144 * Method attempts to find DataSchemaNode inside of provided Schema Context
145 * and Yang Module accordingly to Non-conditional relative Revision Aware
146 * XPath. The specified Module MUST be present in Schema Context otherwise
147 * the operation would fail and return <code>null</code>. <br>
148 * The relative Revision Aware XPath MUST be specified WITHOUT the
149 * conditional statement (i.e. without [cond]) in path, because in this
150 * state the Schema Context is completely unaware of data state and will be
151 * not able to properly resolve XPath. If the XPath contains condition the
152 * method will return IllegalArgumentException. <br>
153 * The Actual Schema Node MUST be specified correctly because from this
154 * Schema Node will search starts. If the Actual Schema Node is not correct
155 * the operation will simply fail, because it will be unable to find desired
156 * DataSchemaNode. <br>
157 * In case that Schema Context or Module or Actual Schema Node or relative
158 * Revision Aware XPath contains <code>null</code> references the method
159 * will throw IllegalArgumentException <br>
160 * If the Revision Aware XPath doesn't have flag
161 * <code>isAbsolute == false</code> the method will throw
162 * IllegalArgumentException. <br>
163 * If the relative Revision Aware XPath is correct and desired Data Schema
164 * Node is present in Yang module or in depending module in Schema Context
165 * the method will return specified Data Schema Node, otherwise the
166 * operation will fail and method will return <code>null</code>.
172 * @param actualSchemaNode
174 * @param relativeXPath
175 * Relative Non Conditional Revision Aware XPath
176 * @return DataSchemaNode if is present in specified Schema Context for
177 * given relative Revision Aware XPath, otherwise will return
180 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
181 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
182 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
183 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
184 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
185 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
186 Preconditions.checkState(!relativeXPath.isAbsolute(),
187 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
188 + "for non relative Revision Aware XPath use findDataSchemaNode method");
190 final SchemaPath actualNodePath = actualSchemaNode.getPath();
191 if (actualNodePath != null) {
192 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
194 if (qnamePath != null) {
195 return findNodeInSchemaContext(context, qnamePath);
202 * Returns parent Yang Module for specified Schema Context in which Schema
203 * Node is declared. If the Schema Node is not present in Schema Context the
204 * operation will return <code>null</code>. <br>
205 * If Schema Context or Schema Node contains <code>null</code> references
206 * the method will throw IllegalArgumentException
212 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
213 * return <code>null</code>
215 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
216 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
217 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
218 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
219 + "set properly (Schema Path is NULL)");
221 final QName qname = schemaNode.getPath().getLastComponent();
222 Preconditions.checkState(qname != null, "Schema Path contains invalid state of path parts. "
223 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
224 return context.findModule(qname.getModule()).orElse(null);
227 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
228 final QName current = path.iterator().next();
230 LOG.trace("Looking up module {} in context {}", current, path);
231 final Optional<Module> module = context.findModule(current.getModule());
232 if (!module.isPresent()) {
233 LOG.debug("Module {} not found", current);
237 return findNodeInModule(module.get(), path);
241 * Returns NotificationDefinition from Schema Context.
243 * @param schema SchemaContext in which lookup should be performed.
244 * @param path Schema Path of notification
245 * @return Notification schema or null, if notification is not present in schema context.
249 public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
250 @Nonnull final SchemaPath path) {
251 Preconditions.checkNotNull(schema, "Schema context must not be null.");
252 Preconditions.checkNotNull(path, "Schema path must not be null.");
253 for (final NotificationDefinition potential : schema.getNotifications()) {
254 if (path.equals(potential.getPath())) {
262 * Returns RPC Input or Output Data container from RPC definition.
264 * @param schema SchemaContext in which lookup should be performed.
265 * @param path Schema path of RPC input/output data container
266 * @return Notification schema or null, if notification is not present in schema context.
270 public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
271 @Nonnull final SchemaPath path) {
272 Preconditions.checkNotNull(schema, "Schema context must not be null.");
273 Preconditions.checkNotNull(path, "Schema path must not be null.");
274 final Iterator<QName> it = path.getPathFromRoot().iterator();
275 Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
276 final QName rpcName = it.next();
277 Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
278 final QName inOrOut = it.next();
279 for (final RpcDefinition potential : schema.getOperations()) {
280 if (rpcName.equals(potential.getQName())) {
281 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
288 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
290 * @param context SchemaContext to be examined
291 * @return Set of ModuleIdentifiers.
293 public static Set<ModuleIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
294 final Set<ModuleIdentifier> ret = new HashSet<>();
296 for (Module module : context.getModules()) {
297 ret.add(moduleToIdentifier(module));
299 for (Module submodule : module.getSubmodules()) {
300 ret.add(moduleToIdentifier(submodule));
307 private static ModuleIdentifier moduleToIdentifier(final Module module) {
308 return ModuleIdentifierImpl.create(module.getName(), module.getRevision());
311 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
313 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
314 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
316 if (!path.iterator().hasNext()) {
317 LOG.debug("No node matching {} found in node {}", path, module);
321 final QName current = path.iterator().next();
322 LOG.trace("Looking for node {} in module {}", current, module);
324 SchemaNode foundNode = null;
325 final Iterable<QName> nextPath = nextLevel(path);
327 foundNode = module.getDataChildByName(current);
328 if (foundNode != null && nextPath.iterator().hasNext()) {
329 foundNode = findNodeIn(foundNode, nextPath);
332 if (foundNode == null) {
333 foundNode = getGroupingByName(module, current);
334 if (foundNode != null && nextPath.iterator().hasNext()) {
335 foundNode = findNodeIn(foundNode, nextPath);
339 if (foundNode == null) {
340 foundNode = getRpcByName(module, current);
341 if (foundNode != null && nextPath.iterator().hasNext()) {
342 foundNode = findNodeIn(foundNode, nextPath);
346 if (foundNode == null) {
347 foundNode = getNotificationByName(module, current);
348 if (foundNode != null && nextPath.iterator().hasNext()) {
349 foundNode = findNodeIn(foundNode, nextPath);
353 if (foundNode == null) {
354 LOG.debug("No node matching {} found in node {}", path, module);
361 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
363 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
364 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
366 if (!path.iterator().hasNext()) {
367 LOG.debug("No node matching {} found in node {}", path, parent);
371 final QName current = path.iterator().next();
372 LOG.trace("Looking for node {} in node {}", current, parent);
374 SchemaNode foundNode = null;
375 final Iterable<QName> nextPath = nextLevel(path);
377 if (parent instanceof DataNodeContainer) {
378 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
380 foundNode = parentDataNodeContainer.getDataChildByName(current);
381 if (foundNode != null && nextPath.iterator().hasNext()) {
382 foundNode = findNodeIn(foundNode, nextPath);
385 if (foundNode == null) {
386 foundNode = getGroupingByName(parentDataNodeContainer, current);
387 if (foundNode != null && nextPath.iterator().hasNext()) {
388 foundNode = findNodeIn(foundNode, nextPath);
393 if (foundNode == null && parent instanceof RpcDefinition) {
394 final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
396 if (current.getLocalName().equals("input")) {
397 foundNode = parentRpcDefinition.getInput();
398 if (foundNode != null && nextPath.iterator().hasNext()) {
399 foundNode = findNodeIn(foundNode, nextPath);
403 if (current.getLocalName().equals("output")) {
404 foundNode = parentRpcDefinition.getOutput();
405 if (foundNode != null && nextPath.iterator().hasNext()) {
406 foundNode = findNodeIn(foundNode, nextPath);
410 if (foundNode == null) {
411 foundNode = getGroupingByName(parentRpcDefinition, current);
412 if (foundNode != null && nextPath.iterator().hasNext()) {
413 foundNode = findNodeIn(foundNode, nextPath);
418 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
419 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
421 if (foundNode != null && nextPath.iterator().hasNext()) {
422 foundNode = findNodeIn(foundNode, nextPath);
425 if (foundNode == null) {
426 // fallback that tries to map into one of the child cases
427 for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
428 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
429 if (maybeChild != null) {
430 foundNode = findNodeIn(maybeChild, nextPath);
437 if (foundNode == null) {
438 LOG.debug("No node matching {} found in node {}", path, parent);
445 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
446 return Iterables.skip(path, 1);
449 private static RpcDefinition getRpcByName(final Module module, final QName name) {
450 for (final RpcDefinition rpc : module.getRpcs()) {
451 if (rpc.getQName().equals(name)) {
458 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
459 for (final NotificationDefinition notification : module.getNotifications()) {
460 if (notification.getQName().equals(name)) {
467 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
468 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
469 if (grouping.getQName().equals(name)) {
476 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
477 for (final GroupingDefinition grouping : rpc.getGroupings()) {
478 if (grouping.getQName().equals(name)) {
486 * Transforms string representation of XPath to Queue of QNames. The XPath
487 * is split by "/" and for each part of XPath is assigned correct module in
489 * If Schema Context, Parent Module or XPath string contains
490 * <code>null</code> values, the method will throws IllegalArgumentException
494 * @param parentModule
498 * @return return a list of QName
500 * @throws IllegalArgumentException if any arguments are null
503 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
504 final String xpath) {
505 // FIXME: 2.0.0: this should throw NPE, not IAE
506 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
507 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
508 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
510 final List<QName> path = new LinkedList<>();
511 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
512 if (!pathComponent.isEmpty()) {
513 path.add(stringPathPartToQName(context, parentModule, pathComponent));
520 * Transforms part of Prefixed Path as java String to QName. <br>
521 * If the string contains module prefix separated by ":" (i.e.
522 * mod:container) this module is provided from from Parent Module list of
523 * imports. If the Prefixed module is present in Schema Context the QName
524 * can be constructed. <br>
525 * If the Prefixed Path Part does not contains prefix the Parent's Module
526 * namespace is taken for construction of QName. <br>
527 * If Schema Context, Parent Module or Prefixed Path Part refers to
528 * <code>null</code> the method will throw IllegalArgumentException
532 * @param parentModule
534 * @param prefixedPathPart
535 * Prefixed Path Part string
536 * @return QName from prefixed Path Part String.
537 * @throws IllegalArgumentException if any arguments are null
539 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
540 final String prefixedPathPart) {
541 // FIXME: 2.0.0: this should throw NPE, not IAE
542 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
543 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
544 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
546 if (prefixedPathPart.indexOf(':') != -1) {
547 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
548 final String modulePrefix = prefixedName.next();
550 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
551 Preconditions.checkArgument(module != null,
552 "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
553 parentModule.getName());
555 return QName.create(module.getQNameModule(), prefixedName.next());
558 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
562 * Method will attempt to resolve and provide Module reference for specified
563 * module prefix. Each Yang module could contains multiple imports which
564 * MUST be associated with corresponding module prefix. The method simply
565 * looks into module imports and returns the module that is bounded with
566 * specified prefix. If the prefix is not present in module or the prefixed
567 * module is not present in specified Schema Context, the method will return
568 * <code>null</code>. <br>
569 * If String prefix is the same as prefix of the specified Module the
570 * reference to this module is returned. <br>
571 * If Schema Context, Module or Prefix are referring to <code>null</code>
572 * the method will return IllegalArgumentException
580 * @return Module for given prefix in specified Schema Context if is
581 * present, otherwise returns <code>null</code>
582 * @throws IllegalArgumentException if any arguments are null
584 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
585 final String prefix) {
586 // FIXME: 2.0.0: this should throw NPE, not IAE
587 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
588 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
589 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
591 if (prefix.equals(module.getPrefix())) {
595 final Set<ModuleImport> imports = module.getImports();
596 for (final ModuleImport mi : imports) {
597 if (prefix.equals(mi.getPrefix())) {
598 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
605 * Resolve a relative XPath into a set of QNames.
611 * @param relativeXPath
612 * Non conditional Revision Aware Relative XPath
613 * @param actualSchemaNode
615 * @return list of QName
616 * @throws IllegalArgumentException if any arguments are null
618 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
619 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
620 // FIXME: 2.0.0: this should throw NPE, not IAE
621 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
622 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
623 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
624 Preconditions.checkState(!relativeXPath.isAbsolute(),
625 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
626 + "for non relative Revision Aware XPath use findDataSchemaNode method");
627 Preconditions.checkState(actualSchemaNode.getPath() != null,
628 "Schema Path reference for Leafref cannot be NULL");
630 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
632 // Find out how many "parent" components there are
633 // FIXME: is .contains() the right check here?
634 // FIXME: case ../../node1/node2/../node3/../node4
636 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
640 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
642 if (Iterables.size(schemaNodePath) - colCount >= 0) {
643 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
644 Iterables.transform(Iterables.skip(xpaths, colCount),
645 input -> stringPathPartToQName(context, module, input)));
647 return Iterables.concat(schemaNodePath,
648 Iterables.transform(Iterables.skip(xpaths, colCount),
649 input -> stringPathPartToQName(context, module, input)));
653 * Extracts the base type of node on which schema node points to. If target node is again of type
654 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
656 * @param typeDefinition
657 * type of node which will be extracted
658 * @param schemaContext
662 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
663 * is there to preserve backwards compatibility)
665 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
666 final SchemaContext schemaContext, final SchemaNode schema) {
667 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
668 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
669 pathStatement.isAbsolute());
671 final DataSchemaNode dataSchemaNode;
672 if (pathStatement.isAbsolute()) {
673 SchemaNode baseSchema = schema;
674 while (baseSchema instanceof DerivableSchemaNode) {
675 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
676 if (basePotential.isPresent()) {
677 baseSchema = basePotential.get();
683 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
684 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
687 Module parentModule = findParentModule(schemaContext, schema);
688 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
689 parentModule, schema, pathStatement);
692 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
693 // and current expected behaviour for such cases is to just use pure string
694 // This should throw an exception about incorrect XPath in leafref
695 if (dataSchemaNode == null) {
699 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
701 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
702 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
705 return targetTypeDefinition;
709 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
710 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
711 * module as typedef which is then imported to referenced module.
714 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
716 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
717 final SchemaContext schemaContext, final QName qname) {
718 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
719 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
720 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
721 if (!strippedPathStatement.isAbsolute()) {
725 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
726 Preconditions.checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
728 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
729 parentModule.get(), strippedPathStatement);
730 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
731 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
732 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
735 return targetTypeDefinition;
738 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
739 final SchemaNode schemaNode) {
740 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
741 Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
743 TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
744 if (nodeType.getBaseType() != null) {
745 while (nodeType.getBaseType() != null) {
746 nodeType = nodeType.getBaseType();
749 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
752 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
755 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
758 * Removes conditions from xPath pointed to target node.
760 * @param pathStatement
761 * xPath to target node
762 * @return string representation of xPath without conditions
765 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
766 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
770 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
773 * a node representing LeafSchemaNode
774 * @return concrete type definition of node value
776 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
777 TypeDefinition<?> baseType = node.getType();
778 while (baseType.getBaseType() != null) {
779 baseType = baseType.getBaseType();
785 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
788 * a node representing LeafListSchemaNode
789 * @return concrete type definition of node value
791 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
792 TypeDefinition<?> baseType = node.getType();
793 while (baseType.getBaseType() != null) {
794 baseType = baseType.getBaseType();
800 * Gets the base type of DataSchemaNode value.
803 * a node representing DataSchemaNode
804 * @return concrete type definition of node value
806 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
807 if (node instanceof LeafListSchemaNode) {
808 return typeDefinition((LeafListSchemaNode) node);
809 } else if (node instanceof LeafSchemaNode) {
810 return typeDefinition((LeafSchemaNode) node);
812 throw new IllegalArgumentException("Unhandled parameter type: " + node);