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.common.QNameModule;
26 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
27 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
30 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
33 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.Module;
36 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
37 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
38 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
39 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
40 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * The Schema Context Util contains support methods for searching through Schema
52 * Context modules for specified schema nodes via Schema Path or Revision Aware
53 * XPath. The Schema Context Util is designed as mixin, so it is not
57 public final class SchemaContextUtil {
58 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
59 private static final Splitter COLON_SPLITTER = Splitter.on(':');
60 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
62 private SchemaContextUtil() {
66 * Method attempts to find DataSchemaNode in Schema Context via specified
67 * Schema Path. The returned DataSchemaNode from method will be the node at
68 * the end of the SchemaPath. If the DataSchemaNode is not present in the
69 * Schema Context the method will return <code>null</code>. <br>
70 * In case that Schema Context or Schema Path are not specified correctly
71 * (i.e. contains <code>null</code> values) the method will throw
72 * IllegalArgumentException.
77 * Schema Path to search for
78 * @return SchemaNode from the end of the Schema Path or <code>null</code>
79 * if the Node is not present.
80 * @throws IllegalArgumentException if context or schemaPath is not correct.
82 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
83 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
84 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
86 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
87 if (prefixedPath == null) {
88 LOG.debug("Schema path {} has null path", schemaPath);
92 LOG.trace("Looking for path {} in context {}", schemaPath, context);
93 return findNodeInSchemaContext(context, prefixedPath);
97 * Method attempts to find DataSchemaNode inside of provided Schema Context
98 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
99 * specified Module MUST be present in Schema Context otherwise the
100 * operation would fail and return <code>null</code>. <br>
101 * The Revision Aware XPath MUST be specified WITHOUT the conditional
102 * statement (i.e. without [cond]) in path, because in this state the Schema
103 * Context is completely unaware of data state and will be not able to
104 * properly resolve XPath. If the XPath contains condition the method will
105 * return IllegalArgumentException. <br>
106 * In case that Schema Context or Module or Revision Aware XPath contains
107 * <code>null</code> references the method will throw
108 * IllegalArgumentException <br>
109 * If the Revision Aware XPath is correct and desired Data Schema Node is
110 * present in Yang module or in depending module in Schema Context the
111 * method will return specified Data Schema Node, otherwise the operation
112 * will fail and method will return <code>null</code>.
118 * @param nonCondXPath
119 * Non Conditional Revision Aware XPath
120 * @return Returns Data Schema Node for specified Schema Context for given
121 * Non-conditional Revision Aware XPath, or <code>null</code> if the
122 * DataSchemaNode is not present in Schema Context.
124 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
125 final RevisionAwareXPath nonCondXPath) {
126 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
127 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
128 Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
130 final String strXPath = nonCondXPath.toString();
131 if (strXPath != null) {
132 Preconditions.checkArgument(strXPath.indexOf('[') == -1,
133 "Revision Aware XPath may not contain a condition");
134 if (nonCondXPath.isAbsolute()) {
135 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
136 if (qnamedPath != null) {
137 return findNodeInSchemaContext(context, qnamedPath);
145 * Method attempts to find DataSchemaNode inside of provided Schema Context
146 * and Yang Module accordingly to Non-conditional relative Revision Aware
147 * XPath. The specified Module MUST be present in Schema Context otherwise
148 * the operation would fail and return <code>null</code>. <br>
149 * The relative Revision Aware XPath MUST be specified WITHOUT the
150 * conditional statement (i.e. without [cond]) in path, because in this
151 * state the Schema Context is completely unaware of data state and will be
152 * not able to properly resolve XPath. If the XPath contains condition the
153 * method will return IllegalArgumentException. <br>
154 * The Actual Schema Node MUST be specified correctly because from this
155 * Schema Node will search starts. If the Actual Schema Node is not correct
156 * the operation will simply fail, because it will be unable to find desired
157 * DataSchemaNode. <br>
158 * In case that Schema Context or Module or Actual Schema Node or relative
159 * Revision Aware XPath contains <code>null</code> references the method
160 * will throw IllegalArgumentException <br>
161 * If the Revision Aware XPath doesn't have flag
162 * <code>isAbsolute == false</code> the method will throw
163 * IllegalArgumentException. <br>
164 * If the relative Revision Aware XPath is correct and desired Data Schema
165 * Node is present in Yang module or in depending module in Schema Context
166 * the method will return specified Data Schema Node, otherwise the
167 * operation will fail and method will return <code>null</code>.
173 * @param actualSchemaNode
175 * @param relativeXPath
176 * Relative Non Conditional Revision Aware XPath
177 * @return DataSchemaNode if is present in specified Schema Context for
178 * given relative Revision Aware XPath, otherwise will return
181 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
182 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
183 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
184 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
185 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
186 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
187 Preconditions.checkState(!relativeXPath.isAbsolute(),
188 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
189 + "for non relative Revision Aware XPath use findDataSchemaNode method");
191 final SchemaPath actualNodePath = actualSchemaNode.getPath();
192 if (actualNodePath != null) {
193 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
195 if (qnamePath != null) {
196 return findNodeInSchemaContext(context, qnamePath);
203 * Returns parent Yang Module for specified Schema Context in which Schema
204 * Node is declared. If the Schema Node is not present in Schema Context the
205 * operation will return <code>null</code>. <br>
206 * If Schema Context or Schema Node contains <code>null</code> references
207 * the method will throw IllegalArgumentException
213 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
214 * return <code>null</code>
216 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
217 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
218 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
219 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
220 + "set properly (Schema Path is NULL)");
222 final QName qname = schemaNode.getPath().getLastComponent();
223 Preconditions.checkState(qname != null, "Schema Path contains invalid state of path parts. "
224 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
225 return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
228 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
229 final QName current = path.iterator().next();
231 LOG.trace("Looking up module {} in context {}", current, path);
232 final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
233 if (module == null) {
234 LOG.debug("Module {} not found", current);
238 return findNodeInModule(module, path);
242 * Returns NotificationDefinition from Schema Context.
244 * @param schema SchemaContext in which lookup should be performed.
245 * @param path Schema Path of notification
246 * @return Notification schema or null, if notification is not present in schema context.
250 public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
251 @Nonnull final SchemaPath path) {
252 Preconditions.checkNotNull(schema, "Schema context must not be null.");
253 Preconditions.checkNotNull(path, "Schema path must not be null.");
254 for (final NotificationDefinition potential : schema.getNotifications()) {
255 if (path.equals(potential.getPath())) {
263 * Returns RPC Input or Output Data container from RPC definition.
265 * @param schema SchemaContext in which lookup should be performed.
266 * @param path Schema path of RPC input/output data container
267 * @return Notification schema or null, if notification is not present in schema context.
271 public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
272 @Nonnull final SchemaPath path) {
273 Preconditions.checkNotNull(schema, "Schema context must not be null.");
274 Preconditions.checkNotNull(path, "Schema path must not be null.");
275 final Iterator<QName> it = path.getPathFromRoot().iterator();
276 Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
277 final QName rpcName = it.next();
278 Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
279 final QName inOrOut = it.next();
280 for (final RpcDefinition potential : schema.getOperations()) {
281 if (rpcName.equals(potential.getQName())) {
282 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
289 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
291 * @param context SchemaContext to be examined
292 * @return Set of ModuleIdentifiers.
294 public static Set<ModuleIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
295 final Set<ModuleIdentifier> ret = new HashSet<>();
297 for (Module module : context.getModules()) {
298 ret.add(moduleToIdentifier(module));
300 for (Module submodule : module.getSubmodules()) {
301 ret.add(moduleToIdentifier(submodule));
308 private static ModuleIdentifier moduleToIdentifier(final Module module) {
309 return ModuleIdentifierImpl.create(module.getName(), Optional.of(module.getNamespace()),
310 Optional.of(module.getRevision()));
313 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
315 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
316 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
318 if (!path.iterator().hasNext()) {
319 LOG.debug("No node matching {} found in node {}", path, module);
323 final QName current = path.iterator().next();
324 LOG.trace("Looking for node {} in module {}", current, module);
326 SchemaNode foundNode = null;
327 final Iterable<QName> nextPath = nextLevel(path);
329 foundNode = module.getDataChildByName(current);
330 if (foundNode != null && nextPath.iterator().hasNext()) {
331 foundNode = findNodeIn(foundNode, nextPath);
334 if (foundNode == null) {
335 foundNode = getGroupingByName(module, current);
336 if (foundNode != null && nextPath.iterator().hasNext()) {
337 foundNode = findNodeIn(foundNode, nextPath);
341 if (foundNode == null) {
342 foundNode = getRpcByName(module, current);
343 if (foundNode != null && nextPath.iterator().hasNext()) {
344 foundNode = findNodeIn(foundNode, nextPath);
348 if (foundNode == null) {
349 foundNode = getNotificationByName(module, current);
350 if (foundNode != null && nextPath.iterator().hasNext()) {
351 foundNode = findNodeIn(foundNode, nextPath);
355 if (foundNode == null) {
356 LOG.debug("No node matching {} found in node {}", path, module);
363 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
365 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
366 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
368 if (!path.iterator().hasNext()) {
369 LOG.debug("No node matching {} found in node {}", path, parent);
373 final QName current = path.iterator().next();
374 LOG.trace("Looking for node {} in node {}", current, parent);
376 SchemaNode foundNode = null;
377 final Iterable<QName> nextPath = nextLevel(path);
379 if (parent instanceof DataNodeContainer) {
380 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
382 foundNode = parentDataNodeContainer.getDataChildByName(current);
383 if (foundNode != null && nextPath.iterator().hasNext()) {
384 foundNode = findNodeIn(foundNode, nextPath);
387 if (foundNode == null) {
388 foundNode = getGroupingByName(parentDataNodeContainer, current);
389 if (foundNode != null && nextPath.iterator().hasNext()) {
390 foundNode = findNodeIn(foundNode, nextPath);
395 if (foundNode == null && parent instanceof RpcDefinition) {
396 final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
398 if (current.getLocalName().equals("input")) {
399 foundNode = parentRpcDefinition.getInput();
400 if (foundNode != null && nextPath.iterator().hasNext()) {
401 foundNode = findNodeIn(foundNode, nextPath);
405 if (current.getLocalName().equals("output")) {
406 foundNode = parentRpcDefinition.getOutput();
407 if (foundNode != null && nextPath.iterator().hasNext()) {
408 foundNode = findNodeIn(foundNode, nextPath);
412 if (foundNode == null) {
413 foundNode = getGroupingByName(parentRpcDefinition, current);
414 if (foundNode != null && nextPath.iterator().hasNext()) {
415 foundNode = findNodeIn(foundNode, nextPath);
420 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
421 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
423 if (foundNode != null && nextPath.iterator().hasNext()) {
424 foundNode = findNodeIn(foundNode, nextPath);
427 if (foundNode == null) {
428 // fallback that tries to map into one of the child cases
429 for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
430 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
431 if (maybeChild != null) {
432 foundNode = findNodeIn(maybeChild, nextPath);
439 if (foundNode == null) {
440 LOG.debug("No node matching {} found in node {}", path, parent);
447 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
448 return Iterables.skip(path, 1);
451 private static RpcDefinition getRpcByName(final Module module, final QName name) {
452 for (final RpcDefinition rpc : module.getRpcs()) {
453 if (rpc.getQName().equals(name)) {
460 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
461 for (final NotificationDefinition notification : module.getNotifications()) {
462 if (notification.getQName().equals(name)) {
469 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
470 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
471 if (grouping.getQName().equals(name)) {
478 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
479 for (final GroupingDefinition grouping : rpc.getGroupings()) {
480 if (grouping.getQName().equals(name)) {
488 * Transforms string representation of XPath to Queue of QNames. The XPath
489 * is split by "/" and for each part of XPath is assigned correct module in
491 * If Schema Context, Parent Module or XPath string contains
492 * <code>null</code> values, the method will throws IllegalArgumentException
496 * @param parentModule
500 * @return return a list of QName
502 * @throws IllegalArgumentException if any arguments are null
505 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
506 final String xpath) {
507 // FIXME: 2.0.0: this should throw NPE, not IAE
508 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
509 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
510 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
512 final List<QName> path = new LinkedList<>();
513 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
514 if (!pathComponent.isEmpty()) {
515 path.add(stringPathPartToQName(context, parentModule, pathComponent));
522 * Transforms part of Prefixed Path as java String to QName. <br>
523 * If the string contains module prefix separated by ":" (i.e.
524 * mod:container) this module is provided from from Parent Module list of
525 * imports. If the Prefixed module is present in Schema Context the QName
526 * can be constructed. <br>
527 * If the Prefixed Path Part does not contains prefix the Parent's Module
528 * namespace is taken for construction of QName. <br>
529 * If Schema Context, Parent Module or Prefixed Path Part refers to
530 * <code>null</code> the method will throw IllegalArgumentException
534 * @param parentModule
536 * @param prefixedPathPart
537 * Prefixed Path Part string
538 * @return QName from prefixed Path Part String.
539 * @throws IllegalArgumentException if any arguments are null
541 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
542 final String prefixedPathPart) {
543 // FIXME: 2.0.0: this should throw NPE, not IAE
544 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
545 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
546 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
548 if (prefixedPathPart.indexOf(':') != -1) {
549 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
550 final String modulePrefix = prefixedName.next();
552 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
553 Preconditions.checkArgument(module != null,
554 "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
555 parentModule.getName());
557 return QName.create(module.getQNameModule(), prefixedName.next());
560 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
564 * Method will attempt to resolve and provide Module reference for specified
565 * module prefix. Each Yang module could contains multiple imports which
566 * MUST be associated with corresponding module prefix. The method simply
567 * looks into module imports and returns the module that is bounded with
568 * specified prefix. If the prefix is not present in module or the prefixed
569 * module is not present in specified Schema Context, the method will return
570 * <code>null</code>. <br>
571 * If String prefix is the same as prefix of the specified Module the
572 * reference to this module is returned. <br>
573 * If Schema Context, Module or Prefix are referring to <code>null</code>
574 * the method will return IllegalArgumentException
582 * @return Module for given prefix in specified Schema Context if is
583 * present, otherwise returns <code>null</code>
584 * @throws IllegalArgumentException if any arguments are null
586 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
587 final String prefix) {
588 // FIXME: 2.0.0: this should throw NPE, not IAE
589 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
590 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
591 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
593 if (prefix.equals(module.getPrefix())) {
597 final Set<ModuleImport> imports = module.getImports();
598 for (final ModuleImport mi : imports) {
599 if (prefix.equals(mi.getPrefix())) {
600 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
607 * Resolve a relative XPath into a set of QNames.
613 * @param relativeXPath
614 * Non conditional Revision Aware Relative XPath
615 * @param actualSchemaNode
617 * @return list of QName
618 * @throws IllegalArgumentException if any arguments are null
620 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
621 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
622 // FIXME: 2.0.0: this should throw NPE, not IAE
623 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
624 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
625 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
626 Preconditions.checkState(!relativeXPath.isAbsolute(),
627 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
628 + "for non relative Revision Aware XPath use findDataSchemaNode method");
629 Preconditions.checkState(actualSchemaNode.getPath() != null,
630 "Schema Path reference for Leafref cannot be NULL");
632 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
634 // Find out how many "parent" components there are
635 // FIXME: is .contains() the right check here?
636 // FIXME: case ../../node1/node2/../node3/../node4
638 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
642 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
644 if (Iterables.size(schemaNodePath) - colCount >= 0) {
645 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
646 Iterables.transform(Iterables.skip(xpaths, colCount),
647 input -> stringPathPartToQName(context, module, input)));
649 return Iterables.concat(schemaNodePath,
650 Iterables.transform(Iterables.skip(xpaths, colCount),
651 input -> stringPathPartToQName(context, module, input)));
655 * Extracts the base type of node on which schema node points to. If target node is again of type
656 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
658 * @param typeDefinition
659 * type of node which will be extracted
660 * @param schemaContext
664 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
665 * is there to preserve backwards compatibility)
667 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
668 final SchemaContext schemaContext, final SchemaNode schema) {
669 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
670 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
671 pathStatement.isAbsolute());
673 final DataSchemaNode dataSchemaNode;
674 if (pathStatement.isAbsolute()) {
675 SchemaNode baseSchema = schema;
676 while (baseSchema instanceof DerivableSchemaNode) {
677 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
678 if (basePotential.isPresent()) {
679 baseSchema = basePotential.get();
685 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
686 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
689 Module parentModule = findParentModule(schemaContext, schema);
690 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
691 parentModule, schema, pathStatement);
694 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
695 // and current expected behaviour for such cases is to just use pure string
696 // This should throw an exception about incorrect XPath in leafref
697 if (dataSchemaNode == null) {
701 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
703 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
704 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
707 return targetTypeDefinition;
711 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
712 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
713 * module as typedef which is then imported to referenced module.
716 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
718 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
719 final SchemaContext schemaContext, final QName qname) {
720 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
721 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
722 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
723 if (!strippedPathStatement.isAbsolute()) {
727 final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
728 qname.getRevision());
729 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
730 parentModule, 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 final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
751 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
752 typeDefModuleQname.getRevision());
755 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
758 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
761 * Removes conditions from xPath pointed to target node.
763 * @param pathStatement
764 * xPath to target node
765 * @return string representation of xPath without conditions
768 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
769 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
773 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
776 * a node representing LeafSchemaNode
777 * @return concrete type definition of node value
779 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
780 TypeDefinition<?> baseType = node.getType();
781 while (baseType.getBaseType() != null) {
782 baseType = baseType.getBaseType();
788 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
791 * a node representing LeafListSchemaNode
792 * @return concrete type definition of node value
794 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
795 TypeDefinition<?> baseType = node.getType();
796 while (baseType.getBaseType() != null) {
797 baseType = baseType.getBaseType();
803 * Gets the base type of DataSchemaNode value.
806 * a node representing DataSchemaNode
807 * @return concrete type definition of node value
809 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
810 if (node instanceof LeafListSchemaNode) {
811 return typeDefinition((LeafListSchemaNode) node);
812 } else if (node instanceof LeafSchemaNode) {
813 return typeDefinition((LeafSchemaNode) node);
815 throw new IllegalArgumentException("Unhandled parameter type: " + node);