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.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.Iterables;
16 import java.util.Iterator;
17 import java.util.LinkedList;
18 import java.util.List;
20 import java.util.regex.Pattern;
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.QNameModule;
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.ModuleImport;
36 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
37 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
38 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * The Schema Context Util contains support methods for searching through Schema
50 * Context modules for specified schema nodes via Schema Path or Revision Aware
51 * XPath. The Schema Context Util is designed as mixin, so it is not
55 public final class SchemaContextUtil {
56 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
57 private static final Splitter COLON_SPLITTER = Splitter.on(':');
58 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
60 private SchemaContextUtil() {
64 * Method attempts to find DataSchemaNode in Schema Context via specified
65 * Schema Path. The returned DataSchemaNode from method will be the node at
66 * the end of the SchemaPath. If the DataSchemaNode is not present in the
67 * Schema Context the method will return <code>null</code>. <br>
68 * In case that Schema Context or Schema Path are not specified correctly
69 * (i.e. contains <code>null</code> values) the method will return
70 * IllegalArgumentException.
75 * Schema Path to search for
76 * @return SchemaNode from the end of the Schema Path or <code>null</code>
77 * if the Node is not present.
79 * @throws IllegalArgumentException
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.
122 * @throws IllegalArgumentException
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 * @throws IllegalArgumentException
183 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
184 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
185 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
186 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
187 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
188 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
189 Preconditions.checkState(!relativeXPath.isAbsolute(),
190 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
191 + "for non relative Revision Aware XPath use findDataSchemaNode method");
193 final SchemaPath actualNodePath = actualSchemaNode.getPath();
194 if (actualNodePath != null) {
195 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
197 if (qnamePath != null) {
198 return findNodeInSchemaContext(context, qnamePath);
205 * Returns parent Yang Module for specified Schema Context in which Schema
206 * Node is declared. If the Schema Node is not present in Schema Context the
207 * operation will return <code>null</code>. <br>
208 * If Schema Context or Schema Node contains <code>null</code> references
209 * the method will throw IllegalArgumentException
215 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
216 * return <code>null</code>
218 * @throws IllegalArgumentException
220 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
221 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
222 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
223 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
224 + "set properly (Schema Path is NULL)");
226 final QName qname = schemaNode.getPath().getLastComponent();
227 Preconditions.checkState(qname != null, "Schema Path contains invalid state of path parts. "
228 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
229 return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
232 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
233 final QName current = path.iterator().next();
235 LOG.trace("Looking up module {} in context {}", current, path);
236 final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
237 if (module == null) {
238 LOG.debug("Module {} not found", current);
242 return findNodeInModule(module, path);
246 * Returns NotificationDefinition from Schema Context
248 * @param schema SchemaContext in which lookup should be performed.
249 * @param path Schema Path of notification
250 * @return Notification schema or null, if notification is not present in schema context.
253 @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
254 @Nonnull final SchemaPath path) {
255 Preconditions.checkNotNull(schema, "Schema context must not be null.");
256 Preconditions.checkNotNull(path, "Schema path must not be null.");
257 for (final NotificationDefinition potential : schema.getNotifications()) {
258 if (path.equals(potential.getPath())) {
266 * Returns RPC Input or Output Data container from RPC definition.
268 * @param schema SchemaContext in which lookup should be performed.
269 * @param path Schema path of RPC input/output data container
270 * @return Notification schema or null, if notification is not present in schema context.
273 @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
274 @Nonnull final SchemaPath path) {
275 Preconditions.checkNotNull(schema, "Schema context must not be null.");
276 Preconditions.checkNotNull(path, "Schema path must not be null.");
277 final Iterator<QName> it = path.getPathFromRoot().iterator();
278 Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
279 final QName rpcName = it.next();
280 Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
281 final QName inOrOut = it.next();
282 for (final RpcDefinition potential : schema.getOperations()) {
283 if (rpcName.equals(potential.getQName())) {
284 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
290 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
292 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
293 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
295 if (!path.iterator().hasNext()) {
296 LOG.debug("No node matching {} found in node {}", path, module);
300 final QName current = path.iterator().next();
301 LOG.trace("Looking for node {} in module {}", current, module);
303 SchemaNode foundNode = null;
304 final Iterable<QName> nextPath = nextLevel(path);
306 foundNode = module.getDataChildByName(current);
307 if (foundNode != null && nextPath.iterator().hasNext()) {
308 foundNode = findNodeIn(foundNode, nextPath);
311 if (foundNode == null) {
312 foundNode = getGroupingByName(module, current);
313 if (foundNode != null && nextPath.iterator().hasNext()) {
314 foundNode = findNodeIn(foundNode, nextPath);
318 if (foundNode == null) {
319 foundNode = getRpcByName(module, current);
320 if (foundNode != null && nextPath.iterator().hasNext()) {
321 foundNode = findNodeIn(foundNode, nextPath);
325 if (foundNode == null) {
326 foundNode = getNotificationByName(module, current);
327 if (foundNode != null && nextPath.iterator().hasNext()) {
328 foundNode = findNodeIn(foundNode, nextPath);
332 if (foundNode == null) {
333 LOG.debug("No node matching {} found in node {}", path, module);
340 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
342 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
343 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
345 if (!path.iterator().hasNext()) {
346 LOG.debug("No node matching {} found in node {}", path, parent);
350 final QName current = path.iterator().next();
351 LOG.trace("Looking for node {} in node {}", current, parent);
353 SchemaNode foundNode = null;
354 final Iterable<QName> nextPath = nextLevel(path);
356 if (parent instanceof DataNodeContainer) {
357 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
359 foundNode = parentDataNodeContainer.getDataChildByName(current);
360 if (foundNode != null && nextPath.iterator().hasNext()) {
361 foundNode = findNodeIn(foundNode, nextPath);
364 if (foundNode == null) {
365 foundNode = getGroupingByName(parentDataNodeContainer, current);
366 if (foundNode != null && nextPath.iterator().hasNext()) {
367 foundNode = findNodeIn(foundNode, nextPath);
372 if (foundNode == null && parent instanceof RpcDefinition) {
373 final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
375 if (current.getLocalName().equals("input")) {
376 foundNode = parentRpcDefinition.getInput();
377 if (foundNode != null && nextPath.iterator().hasNext()) {
378 foundNode = findNodeIn(foundNode, nextPath);
382 if (current.getLocalName().equals("output")) {
383 foundNode = parentRpcDefinition.getOutput();
384 if (foundNode != null && nextPath.iterator().hasNext()) {
385 foundNode = findNodeIn(foundNode, nextPath);
389 if (foundNode == null) {
390 foundNode = getGroupingByName(parentRpcDefinition, current);
391 if (foundNode != null && nextPath.iterator().hasNext()) {
392 foundNode = findNodeIn(foundNode, nextPath);
397 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
398 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
400 if (foundNode != null && nextPath.iterator().hasNext()) {
401 foundNode = findNodeIn(foundNode, nextPath);
404 if (foundNode == null) {
405 // fallback that tries to map into one of the child cases
406 for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
407 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
408 if (maybeChild != null) {
409 foundNode = findNodeIn(maybeChild, nextPath);
416 if (foundNode == null) {
417 LOG.debug("No node matching {} found in node {}", path, parent);
424 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
425 return Iterables.skip(path, 1);
428 private static RpcDefinition getRpcByName(final Module module, final QName name) {
429 for (final RpcDefinition rpc : module.getRpcs()) {
430 if (rpc.getQName().equals(name)) {
437 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
438 for (final NotificationDefinition notification : module.getNotifications()) {
439 if (notification.getQName().equals(name)) {
446 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
447 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
448 if (grouping.getQName().equals(name)) {
455 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
456 for (final GroupingDefinition grouping : rpc.getGroupings()) {
457 if (grouping.getQName().equals(name)) {
465 * Transforms string representation of XPath to Queue of QNames. The XPath
466 * is split by "/" and for each part of XPath is assigned correct module in
468 * If Schema Context, Parent Module or XPath string contains
469 * <code>null</code> values, the method will throws IllegalArgumentException
473 * @param parentModule
477 * @return return a list of QName
479 * @throws IllegalArgumentException
481 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
482 final String xpath) {
483 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
484 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
485 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
487 final List<QName> path = new LinkedList<>();
488 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
489 if (!pathComponent.isEmpty()) {
490 path.add(stringPathPartToQName(context, parentModule, pathComponent));
497 * Transforms part of Prefixed Path as java String to QName. <br>
498 * If the string contains module prefix separated by ":" (i.e.
499 * mod:container) this module is provided from from Parent Module list of
500 * imports. If the Prefixed module is present in Schema Context the QName
501 * can be constructed. <br>
502 * If the Prefixed Path Part does not contains prefix the Parent's Module
503 * namespace is taken for construction of QName. <br>
504 * If Schema Context, Parent Module or Prefixed Path Part refers to
505 * <code>null</code> the method will throw IllegalArgumentException
509 * @param parentModule
511 * @param prefixedPathPart
512 * Prefixed Path Part string
513 * @return QName from prefixed Path Part String.
515 * @throws IllegalArgumentException
517 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
518 final String prefixedPathPart) {
519 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
520 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
521 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
523 if (prefixedPathPart.indexOf(':') != -1) {
524 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
525 final String modulePrefix = prefixedName.next();
527 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
528 Preconditions.checkArgument(module != null,
529 "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
530 parentModule.getName());
532 return QName.create(module.getQNameModule(), prefixedName.next());
535 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
539 * Method will attempt to resolve and provide Module reference for specified
540 * module prefix. Each Yang module could contains multiple imports which
541 * MUST be associated with corresponding module prefix. The method simply
542 * looks into module imports and returns the module that is bounded with
543 * specified prefix. If the prefix is not present in module or the prefixed
544 * module is not present in specified Schema Context, the method will return
545 * <code>null</code>. <br>
546 * If String prefix is the same as prefix of the specified Module the
547 * reference to this module is returned. <br>
548 * If Schema Context, Module or Prefix are referring to <code>null</code>
549 * the method will return IllegalArgumentException
557 * @return Module for given prefix in specified Schema Context if is
558 * present, otherwise returns <code>null</code>
560 * @throws IllegalArgumentException
562 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
563 final String prefix) {
564 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
565 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
566 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
568 if (prefix.equals(module.getPrefix())) {
572 final Set<ModuleImport> imports = module.getImports();
573 for (final ModuleImport mi : imports) {
574 if (prefix.equals(mi.getPrefix())) {
575 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
586 * @param relativeXPath
587 * Non conditional Revision Aware Relative XPath
588 * @param actualSchemaNode
590 * @return list of QName
592 * @throws IllegalArgumentException
594 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
595 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
596 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
597 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
598 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
599 Preconditions.checkState(!relativeXPath.isAbsolute(),
600 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
601 + "for non relative Revision Aware XPath use findDataSchemaNode method");
602 Preconditions.checkState(actualSchemaNode.getPath() != null,
603 "Schema Path reference for Leafref cannot be NULL");
605 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
607 // Find out how many "parent" components there are
608 // FIXME: is .contains() the right check here?
609 // FIXME: case ../../node1/node2/../node3/../node4
611 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
615 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
617 if (Iterables.size(schemaNodePath) - colCount >= 0) {
618 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
619 Iterables.transform(Iterables.skip(xpaths, colCount),
620 input -> stringPathPartToQName(context, module, input)));
622 return Iterables.concat(schemaNodePath,
623 Iterables.transform(Iterables.skip(xpaths, colCount),
624 input -> stringPathPartToQName(context, module, input)));
628 * Extracts the base type of node on which schema node points to. If target node is again of type
629 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
631 * @param typeDefinition
632 * type of node which will be extracted
633 * @param schemaContext
637 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
638 * is there to preserve backwards compatibility)
640 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
641 final SchemaContext schemaContext, final SchemaNode schema) {
642 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
643 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
644 pathStatement.isAbsolute());
646 final DataSchemaNode dataSchemaNode;
647 if (pathStatement.isAbsolute()) {
648 SchemaNode baseSchema = schema;
649 while (baseSchema instanceof DerivableSchemaNode) {
650 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
651 if (basePotential.isPresent()) {
652 baseSchema = basePotential.get();
658 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
659 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
662 Module parentModule = findParentModule(schemaContext, schema);
663 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
664 parentModule, schema, pathStatement);
667 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
668 // and current expected behaviour for such cases is to just use pure string
669 // This should throw an exception about incorrect XPath in leafref
670 if (dataSchemaNode == null) {
674 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
676 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
677 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
680 return targetTypeDefinition;
683 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
684 final SchemaNode schemaNode) {
685 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
686 Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
688 TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
689 if (nodeType.getBaseType() != null) {
690 while (nodeType.getBaseType() != null) {
691 nodeType = nodeType.getBaseType();
694 final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
695 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
696 typeDefModuleQname.getRevision());
699 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
703 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle
704 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
705 * module as typedef which is then imported to referenced module.
707 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
709 * @param typeDefinition
710 * @param schemaContext
713 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
714 final SchemaContext schemaContext, final QName qName) {
715 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
716 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
717 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
718 if (!strippedPathStatement.isAbsolute()) {
722 final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace()
723 ,qName.getRevision());
724 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
725 parentModule, strippedPathStatement);
726 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
727 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
728 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
731 return targetTypeDefinition;
734 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
737 * Removes conditions from xPath pointed to target node.
739 * @param pathStatement
740 * xPath to target node
741 * @return string representation of xPath without conditions
745 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
746 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
750 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
753 * a node representing LeafSchemaNode
754 * @return concrete type definition of node value
756 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
757 TypeDefinition<?> baseType = node.getType();
758 while (baseType.getBaseType() != null) {
759 baseType = baseType.getBaseType();
765 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
768 * a node representing LeafListSchemaNode
769 * @return concrete type definition of node value
771 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
772 TypeDefinition<?> baseType = node.getType();
773 while (baseType.getBaseType() != null) {
774 baseType = baseType.getBaseType();
780 * Gets the base type of DataSchemaNode value.
783 * a node representing DataSchemaNode
784 * @return concrete type definition of node value
786 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
787 if (node instanceof LeafListSchemaNode) {
788 return typeDefinition((LeafListSchemaNode) node);
789 } else if (node instanceof LeafSchemaNode) {
790 return typeDefinition((LeafSchemaNode) node);
792 throw new IllegalArgumentException("Unhandled parameter type: " + node);