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(), Optional.of(module.getNamespace()),
309 Optional.of(module.getRevision()));
312 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
314 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
315 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
317 if (!path.iterator().hasNext()) {
318 LOG.debug("No node matching {} found in node {}", path, module);
322 final QName current = path.iterator().next();
323 LOG.trace("Looking for node {} in module {}", current, module);
325 SchemaNode foundNode = null;
326 final Iterable<QName> nextPath = nextLevel(path);
328 foundNode = module.getDataChildByName(current);
329 if (foundNode != null && nextPath.iterator().hasNext()) {
330 foundNode = findNodeIn(foundNode, nextPath);
333 if (foundNode == null) {
334 foundNode = getGroupingByName(module, current);
335 if (foundNode != null && nextPath.iterator().hasNext()) {
336 foundNode = findNodeIn(foundNode, nextPath);
340 if (foundNode == null) {
341 foundNode = getRpcByName(module, current);
342 if (foundNode != null && nextPath.iterator().hasNext()) {
343 foundNode = findNodeIn(foundNode, nextPath);
347 if (foundNode == null) {
348 foundNode = getNotificationByName(module, current);
349 if (foundNode != null && nextPath.iterator().hasNext()) {
350 foundNode = findNodeIn(foundNode, nextPath);
354 if (foundNode == null) {
355 LOG.debug("No node matching {} found in node {}", path, module);
362 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
364 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
365 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
367 if (!path.iterator().hasNext()) {
368 LOG.debug("No node matching {} found in node {}", path, parent);
372 final QName current = path.iterator().next();
373 LOG.trace("Looking for node {} in node {}", current, parent);
375 SchemaNode foundNode = null;
376 final Iterable<QName> nextPath = nextLevel(path);
378 if (parent instanceof DataNodeContainer) {
379 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
381 foundNode = parentDataNodeContainer.getDataChildByName(current);
382 if (foundNode != null && nextPath.iterator().hasNext()) {
383 foundNode = findNodeIn(foundNode, nextPath);
386 if (foundNode == null) {
387 foundNode = getGroupingByName(parentDataNodeContainer, current);
388 if (foundNode != null && nextPath.iterator().hasNext()) {
389 foundNode = findNodeIn(foundNode, nextPath);
394 if (foundNode == null && parent instanceof RpcDefinition) {
395 final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
397 if (current.getLocalName().equals("input")) {
398 foundNode = parentRpcDefinition.getInput();
399 if (foundNode != null && nextPath.iterator().hasNext()) {
400 foundNode = findNodeIn(foundNode, nextPath);
404 if (current.getLocalName().equals("output")) {
405 foundNode = parentRpcDefinition.getOutput();
406 if (foundNode != null && nextPath.iterator().hasNext()) {
407 foundNode = findNodeIn(foundNode, nextPath);
411 if (foundNode == null) {
412 foundNode = getGroupingByName(parentRpcDefinition, current);
413 if (foundNode != null && nextPath.iterator().hasNext()) {
414 foundNode = findNodeIn(foundNode, nextPath);
419 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
420 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
422 if (foundNode != null && nextPath.iterator().hasNext()) {
423 foundNode = findNodeIn(foundNode, nextPath);
426 if (foundNode == null) {
427 // fallback that tries to map into one of the child cases
428 for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
429 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
430 if (maybeChild != null) {
431 foundNode = findNodeIn(maybeChild, nextPath);
438 if (foundNode == null) {
439 LOG.debug("No node matching {} found in node {}", path, parent);
446 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
447 return Iterables.skip(path, 1);
450 private static RpcDefinition getRpcByName(final Module module, final QName name) {
451 for (final RpcDefinition rpc : module.getRpcs()) {
452 if (rpc.getQName().equals(name)) {
459 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
460 for (final NotificationDefinition notification : module.getNotifications()) {
461 if (notification.getQName().equals(name)) {
468 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
469 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
470 if (grouping.getQName().equals(name)) {
477 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
478 for (final GroupingDefinition grouping : rpc.getGroupings()) {
479 if (grouping.getQName().equals(name)) {
487 * Transforms string representation of XPath to Queue of QNames. The XPath
488 * is split by "/" and for each part of XPath is assigned correct module in
490 * If Schema Context, Parent Module or XPath string contains
491 * <code>null</code> values, the method will throws IllegalArgumentException
495 * @param parentModule
499 * @return return a list of QName
501 * @throws IllegalArgumentException if any arguments are null
504 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
505 final String xpath) {
506 // FIXME: 2.0.0: this should throw NPE, not IAE
507 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
508 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
509 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
511 final List<QName> path = new LinkedList<>();
512 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
513 if (!pathComponent.isEmpty()) {
514 path.add(stringPathPartToQName(context, parentModule, pathComponent));
521 * Transforms part of Prefixed Path as java String to QName. <br>
522 * If the string contains module prefix separated by ":" (i.e.
523 * mod:container) this module is provided from from Parent Module list of
524 * imports. If the Prefixed module is present in Schema Context the QName
525 * can be constructed. <br>
526 * If the Prefixed Path Part does not contains prefix the Parent's Module
527 * namespace is taken for construction of QName. <br>
528 * If Schema Context, Parent Module or Prefixed Path Part refers to
529 * <code>null</code> the method will throw IllegalArgumentException
533 * @param parentModule
535 * @param prefixedPathPart
536 * Prefixed Path Part string
537 * @return QName from prefixed Path Part String.
538 * @throws IllegalArgumentException if any arguments are null
540 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
541 final String prefixedPathPart) {
542 // FIXME: 2.0.0: this should throw NPE, not IAE
543 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
544 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
545 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
547 if (prefixedPathPart.indexOf(':') != -1) {
548 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
549 final String modulePrefix = prefixedName.next();
551 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
552 Preconditions.checkArgument(module != null,
553 "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
554 parentModule.getName());
556 return QName.create(module.getQNameModule(), prefixedName.next());
559 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
563 * Method will attempt to resolve and provide Module reference for specified
564 * module prefix. Each Yang module could contains multiple imports which
565 * MUST be associated with corresponding module prefix. The method simply
566 * looks into module imports and returns the module that is bounded with
567 * specified prefix. If the prefix is not present in module or the prefixed
568 * module is not present in specified Schema Context, the method will return
569 * <code>null</code>. <br>
570 * If String prefix is the same as prefix of the specified Module the
571 * reference to this module is returned. <br>
572 * If Schema Context, Module or Prefix are referring to <code>null</code>
573 * the method will return IllegalArgumentException
581 * @return Module for given prefix in specified Schema Context if is
582 * present, otherwise returns <code>null</code>
583 * @throws IllegalArgumentException if any arguments are null
585 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
586 final String prefix) {
587 // FIXME: 2.0.0: this should throw NPE, not IAE
588 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
589 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
590 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
592 if (prefix.equals(module.getPrefix())) {
596 final Set<ModuleImport> imports = module.getImports();
597 for (final ModuleImport mi : imports) {
598 if (prefix.equals(mi.getPrefix())) {
599 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
606 * Resolve a relative XPath into a set of QNames.
612 * @param relativeXPath
613 * Non conditional Revision Aware Relative XPath
614 * @param actualSchemaNode
616 * @return list of QName
617 * @throws IllegalArgumentException if any arguments are null
619 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
620 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
621 // FIXME: 2.0.0: this should throw NPE, not IAE
622 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
623 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
624 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
625 Preconditions.checkState(!relativeXPath.isAbsolute(),
626 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
627 + "for non relative Revision Aware XPath use findDataSchemaNode method");
628 Preconditions.checkState(actualSchemaNode.getPath() != null,
629 "Schema Path reference for Leafref cannot be NULL");
631 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
633 // Find out how many "parent" components there are
634 // FIXME: is .contains() the right check here?
635 // FIXME: case ../../node1/node2/../node3/../node4
637 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
641 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
643 if (Iterables.size(schemaNodePath) - colCount >= 0) {
644 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
645 Iterables.transform(Iterables.skip(xpaths, colCount),
646 input -> stringPathPartToQName(context, module, input)));
648 return Iterables.concat(schemaNodePath,
649 Iterables.transform(Iterables.skip(xpaths, colCount),
650 input -> stringPathPartToQName(context, module, input)));
654 * Extracts the base type of node on which schema node points to. If target node is again of type
655 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
657 * @param typeDefinition
658 * type of node which will be extracted
659 * @param schemaContext
663 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
664 * is there to preserve backwards compatibility)
666 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
667 final SchemaContext schemaContext, final SchemaNode schema) {
668 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
669 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
670 pathStatement.isAbsolute());
672 final DataSchemaNode dataSchemaNode;
673 if (pathStatement.isAbsolute()) {
674 SchemaNode baseSchema = schema;
675 while (baseSchema instanceof DerivableSchemaNode) {
676 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
677 if (basePotential.isPresent()) {
678 baseSchema = basePotential.get();
684 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
685 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
688 Module parentModule = findParentModule(schemaContext, schema);
689 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
690 parentModule, schema, pathStatement);
693 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
694 // and current expected behaviour for such cases is to just use pure string
695 // This should throw an exception about incorrect XPath in leafref
696 if (dataSchemaNode == null) {
700 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
702 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
703 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
706 return targetTypeDefinition;
710 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
711 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
712 * module as typedef which is then imported to referenced module.
715 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
717 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
718 final SchemaContext schemaContext, final QName qname) {
719 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
720 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
721 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
722 if (!strippedPathStatement.isAbsolute()) {
726 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
727 Preconditions.checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
729 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
730 parentModule.get(), strippedPathStatement);
731 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
732 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
733 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
736 return targetTypeDefinition;
739 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
740 final SchemaNode schemaNode) {
741 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
742 Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
744 TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
745 if (nodeType.getBaseType() != null) {
746 while (nodeType.getBaseType() != null) {
747 nodeType = nodeType.getBaseType();
750 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
753 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
756 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
759 * Removes conditions from xPath pointed to target node.
761 * @param pathStatement
762 * xPath to target node
763 * @return string representation of xPath without conditions
766 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
767 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
771 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
774 * a node representing LeafSchemaNode
775 * @return concrete type definition of node value
777 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
778 TypeDefinition<?> baseType = node.getType();
779 while (baseType.getBaseType() != null) {
780 baseType = baseType.getBaseType();
786 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
789 * a node representing LeafListSchemaNode
790 * @return concrete type definition of node value
792 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
793 TypeDefinition<?> baseType = node.getType();
794 while (baseType.getBaseType() != null) {
795 baseType = baseType.getBaseType();
801 * Gets the base type of DataSchemaNode value.
804 * a node representing DataSchemaNode
805 * @return concrete type definition of node value
807 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
808 if (node instanceof LeafListSchemaNode) {
809 return typeDefinition((LeafListSchemaNode) node);
810 } else if (node instanceof LeafSchemaNode) {
811 return typeDefinition((LeafSchemaNode) node);
813 throw new IllegalArgumentException("Unhandled parameter type: " + node);