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.ChoiceSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
31 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.Module;
34 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
35 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
36 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
37 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * The Schema Context Util contains support methods for searching through Schema
49 * Context modules for specified schema nodes via Schema Path or Revision Aware
50 * XPath. The Schema Context Util is designed as mixin, so it is not
54 public final class SchemaContextUtil {
55 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
56 private static final Splitter COLON_SPLITTER = Splitter.on(':');
57 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
59 private SchemaContextUtil() {
63 * Method attempts to find DataSchemaNode in Schema Context via specified
64 * Schema Path. The returned DataSchemaNode from method will be the node at
65 * the end of the SchemaPath. If the DataSchemaNode is not present in the
66 * Schema Context the method will return <code>null</code>. <br>
67 * In case that Schema Context or Schema Path are not specified correctly
68 * (i.e. contains <code>null</code> values) the method will return
69 * IllegalArgumentException.
74 * Schema Path to search for
75 * @return SchemaNode from the end of the Schema Path or <code>null</code>
76 * if the Node is not present.
78 * @throws IllegalArgumentException
80 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
81 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
82 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
84 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
85 if (prefixedPath == null) {
86 LOG.debug("Schema path {} has null path", schemaPath);
90 LOG.trace("Looking for path {} in context {}", schemaPath, context);
91 return findNodeInSchemaContext(context, prefixedPath);
95 * Method attempts to find DataSchemaNode inside of provided Schema Context
96 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
97 * specified Module MUST be present in Schema Context otherwise the
98 * operation would fail and return <code>null</code>. <br>
99 * The Revision Aware XPath MUST be specified WITHOUT the conditional
100 * statement (i.e. without [cond]) in path, because in this state the Schema
101 * Context is completely unaware of data state and will be not able to
102 * properly resolve XPath. If the XPath contains condition the method will
103 * return IllegalArgumentException. <br>
104 * In case that Schema Context or Module or Revision Aware XPath contains
105 * <code>null</code> references the method will throw
106 * IllegalArgumentException <br>
107 * If the Revision Aware XPath is correct and desired Data Schema Node is
108 * present in Yang module or in depending module in Schema Context the
109 * method will return specified Data Schema Node, otherwise the operation
110 * will fail and method will return <code>null</code>.
116 * @param nonCondXPath
117 * Non Conditional Revision Aware XPath
118 * @return Returns Data Schema Node for specified Schema Context for given
119 * Non-conditional Revision Aware XPath, or <code>null</code> if the
120 * DataSchemaNode is not present in Schema Context.
121 * @throws IllegalArgumentException
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 * @throws IllegalArgumentException
182 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
183 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
184 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
185 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
186 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
187 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
188 Preconditions.checkState(!relativeXPath.isAbsolute(),
189 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
190 + "for non relative Revision Aware XPath use findDataSchemaNode method");
192 final SchemaPath actualNodePath = actualSchemaNode.getPath();
193 if (actualNodePath != null) {
194 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
196 if (qnamePath != null) {
197 return findNodeInSchemaContext(context, qnamePath);
204 * Returns parent Yang Module for specified Schema Context in which Schema
205 * Node is declared. If the Schema Node is not present in Schema Context the
206 * operation will return <code>null</code>. <br>
207 * If Schema Context or Schema Node contains <code>null</code> references
208 * the method will throw IllegalArgumentException
214 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
215 * return <code>null</code>
217 * @throws IllegalArgumentException
219 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
220 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
221 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
222 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
223 + "set properly (Schema Path is NULL)");
225 final QName qname = schemaNode.getPath().getLastComponent();
226 Preconditions.checkState(qname != null, "Schema Path contains invalid state of path parts. "
227 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
228 return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
231 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
232 final QName current = path.iterator().next();
234 LOG.trace("Looking up module {} in context {}", current, path);
235 final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
236 if (module == null) {
237 LOG.debug("Module {} not found", current);
241 return findNodeInModule(module, path);
245 * Returns NotificationDefinition from Schema Context
247 * @param schema SchemaContext in which lookup should be performed.
248 * @param path Schema Path of notification
249 * @return Notification schema or null, if notification is not present in schema context.
252 @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
253 @Nonnull final SchemaPath path) {
254 Preconditions.checkNotNull(schema, "Schema context must not be null.");
255 Preconditions.checkNotNull(path, "Schema path must not be null.");
256 for (final NotificationDefinition potential : schema.getNotifications()) {
257 if (path.equals(potential.getPath())) {
265 * Returns RPC Input or Output Data container from RPC definition.
267 * @param schema SchemaContext in which lookup should be performed.
268 * @param path Schema path of RPC input/output data container
269 * @return Notification schema or null, if notification is not present in schema context.
272 @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
273 @Nonnull final SchemaPath path) {
274 Preconditions.checkNotNull(schema, "Schema context must not be null.");
275 Preconditions.checkNotNull(path, "Schema path must not be null.");
276 final Iterator<QName> it = path.getPathFromRoot().iterator();
277 Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
278 final QName rpcName = it.next();
279 Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
280 final QName inOrOut = it.next();
281 for (final RpcDefinition potential : schema.getOperations()) {
282 if (rpcName.equals(potential.getQName())) {
283 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
289 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
291 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
292 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
294 if (!path.iterator().hasNext()) {
295 LOG.debug("No node matching {} found in node {}", path, module);
299 final QName current = path.iterator().next();
300 LOG.trace("Looking for node {} in module {}", current, module);
302 SchemaNode foundNode = null;
303 final Iterable<QName> nextPath = nextLevel(path);
305 foundNode = module.getDataChildByName(current);
306 if (foundNode != null && nextPath.iterator().hasNext()) {
307 foundNode = findNodeIn(foundNode, nextPath);
310 if (foundNode == null) {
311 foundNode = getGroupingByName(module, current);
312 if (foundNode != null && nextPath.iterator().hasNext()) {
313 foundNode = findNodeIn(foundNode, nextPath);
317 if (foundNode == null) {
318 foundNode = getRpcByName(module, current);
319 if (foundNode != null && nextPath.iterator().hasNext()) {
320 foundNode = findNodeIn(foundNode, nextPath);
324 if (foundNode == null) {
325 foundNode = getNotificationByName(module, current);
326 if (foundNode != null && nextPath.iterator().hasNext()) {
327 foundNode = findNodeIn(foundNode, nextPath);
331 if (foundNode == null) {
332 LOG.debug("No node matching {} found in node {}", path, module);
339 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
341 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
342 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
344 if (!path.iterator().hasNext()) {
345 LOG.debug("No node matching {} found in node {}", path, parent);
349 final QName current = path.iterator().next();
350 LOG.trace("Looking for node {} in node {}", current, parent);
352 SchemaNode foundNode = null;
353 final Iterable<QName> nextPath = nextLevel(path);
355 if (parent instanceof DataNodeContainer) {
356 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
358 foundNode = parentDataNodeContainer.getDataChildByName(current);
359 if (foundNode != null && nextPath.iterator().hasNext()) {
360 foundNode = findNodeIn(foundNode, nextPath);
363 if (foundNode == null) {
364 foundNode = getGroupingByName(parentDataNodeContainer, current);
365 if (foundNode != null && nextPath.iterator().hasNext()) {
366 foundNode = findNodeIn(foundNode, nextPath);
371 if (foundNode == null && parent instanceof RpcDefinition) {
372 final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
374 if (current.getLocalName().equals("input")) {
375 foundNode = parentRpcDefinition.getInput();
376 if (foundNode != null && nextPath.iterator().hasNext()) {
377 foundNode = findNodeIn(foundNode, nextPath);
381 if (current.getLocalName().equals("output")) {
382 foundNode = parentRpcDefinition.getOutput();
383 if (foundNode != null && nextPath.iterator().hasNext()) {
384 foundNode = findNodeIn(foundNode, nextPath);
388 if (foundNode == null) {
389 foundNode = getGroupingByName(parentRpcDefinition, current);
390 if (foundNode != null && nextPath.iterator().hasNext()) {
391 foundNode = findNodeIn(foundNode, nextPath);
396 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
397 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
398 if (foundNode != null && nextPath.iterator().hasNext()) {
399 foundNode = findNodeIn(foundNode, nextPath);
403 if (foundNode == null) {
404 LOG.debug("No node matching {} found in node {}", path, parent);
411 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
412 return Iterables.skip(path, 1);
415 private static RpcDefinition getRpcByName(final Module module, final QName name) {
416 for (final RpcDefinition rpc : module.getRpcs()) {
417 if (rpc.getQName().equals(name)) {
424 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
425 for (final NotificationDefinition notification : module.getNotifications()) {
426 if (notification.getQName().equals(name)) {
433 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
434 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
435 if (grouping.getQName().equals(name)) {
442 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
443 for (final GroupingDefinition grouping : rpc.getGroupings()) {
444 if (grouping.getQName().equals(name)) {
452 * Transforms string representation of XPath to Queue of QNames. The XPath
453 * is split by "/" and for each part of XPath is assigned correct module in
455 * If Schema Context, Parent Module or XPath string contains
456 * <code>null</code> values, the method will throws IllegalArgumentException
460 * @param parentModule
464 * @return return a list of QName
466 * @throws IllegalArgumentException
468 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
469 final String xpath) {
470 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
471 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
472 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
474 final List<QName> path = new LinkedList<>();
475 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
476 if (!pathComponent.isEmpty()) {
477 path.add(stringPathPartToQName(context, parentModule, pathComponent));
484 * Transforms part of Prefixed Path as java String to QName. <br>
485 * If the string contains module prefix separated by ":" (i.e.
486 * mod:container) this module is provided from from Parent Module list of
487 * imports. If the Prefixed module is present in Schema Context the QName
488 * can be constructed. <br>
489 * If the Prefixed Path Part does not contains prefix the Parent's Module
490 * namespace is taken for construction of QName. <br>
491 * If Schema Context, Parent Module or Prefixed Path Part refers to
492 * <code>null</code> the method will throw IllegalArgumentException
496 * @param parentModule
498 * @param prefixedPathPart
499 * Prefixed Path Part string
500 * @return QName from prefixed Path Part String.
502 * @throws IllegalArgumentException
504 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
505 final String prefixedPathPart) {
506 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
507 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
508 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
510 if (prefixedPathPart.indexOf(':') != -1) {
511 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
512 final String modulePrefix = prefixedName.next();
514 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
515 Preconditions.checkArgument(module != null,
516 "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
517 parentModule.getName());
519 return QName.create(module.getQNameModule(), prefixedName.next());
522 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
526 * Method will attempt to resolve and provide Module reference for specified
527 * module prefix. Each Yang module could contains multiple imports which
528 * MUST be associated with corresponding module prefix. The method simply
529 * looks into module imports and returns the module that is bounded with
530 * specified prefix. If the prefix is not present in module or the prefixed
531 * module is not present in specified Schema Context, the method will return
532 * <code>null</code>. <br>
533 * If String prefix is the same as prefix of the specified Module the
534 * reference to this module is returned. <br>
535 * If Schema Context, Module or Prefix are referring to <code>null</code>
536 * the method will return IllegalArgumentException
544 * @return Module for given prefix in specified Schema Context if is
545 * present, otherwise returns <code>null</code>
547 * @throws IllegalArgumentException
549 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
550 final String prefix) {
551 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
552 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
553 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
555 if (prefix.equals(module.getPrefix())) {
559 final Set<ModuleImport> imports = module.getImports();
560 for (final ModuleImport mi : imports) {
561 if (prefix.equals(mi.getPrefix())) {
562 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
573 * @param relativeXPath
574 * Non conditional Revision Aware Relative XPath
575 * @param actualSchemaNode
577 * @return list of QName
579 * @throws IllegalArgumentException
581 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
582 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
583 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
584 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
585 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
586 Preconditions.checkState(!relativeXPath.isAbsolute(),
587 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
588 + "for non relative Revision Aware XPath use findDataSchemaNode method");
589 Preconditions.checkState(actualSchemaNode.getPath() != null,
590 "Schema Path reference for Leafref cannot be NULL");
592 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
594 // Find out how many "parent" components there are
595 // FIXME: is .contains() the right check here?
596 // FIXME: case ../../node1/node2/../node3/../node4
598 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
602 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
604 if (Iterables.size(schemaNodePath) - colCount >= 0) {
605 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
606 Iterables.transform(Iterables.skip(xpaths, colCount),
607 input -> stringPathPartToQName(context, module, input)));
609 return Iterables.concat(schemaNodePath,
610 Iterables.transform(Iterables.skip(xpaths, colCount),
611 input -> stringPathPartToQName(context, module, input)));
615 * Extracts the base type of node on which schema node points to. If target node is again of type
616 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
618 * @param typeDefinition
619 * type of node which will be extracted
620 * @param schemaContext
624 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
625 * is there to preserve backwards compatibility)
627 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
628 final SchemaContext schemaContext, final SchemaNode schema) {
629 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
630 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
631 pathStatement.isAbsolute());
633 final DataSchemaNode dataSchemaNode;
634 if (pathStatement.isAbsolute()) {
635 SchemaNode baseSchema = schema;
636 while (baseSchema instanceof DerivableSchemaNode) {
637 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
638 if (basePotential.isPresent()) {
639 baseSchema = basePotential.get();
645 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
646 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
649 Module parentModule = findParentModule(schemaContext, schema);
650 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
651 parentModule, schema, pathStatement);
654 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
655 // and current expected behaviour for such cases is to just use pure string
656 // This should throw an exception about incorrect XPath in leafref
657 if (dataSchemaNode == null) {
661 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
663 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
664 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
667 return targetTypeDefinition;
670 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
671 final SchemaNode schemaNode) {
672 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
673 Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
675 TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
676 if (nodeType.getBaseType() != null) {
677 while (nodeType.getBaseType() != null) {
678 nodeType = nodeType.getBaseType();
681 final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
682 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
683 typeDefModuleQname.getRevision());
686 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
690 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle
691 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
692 * module as typedef which is then imported to referenced module.
694 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
696 * @param typeDefinition
697 * @param schemaContext
700 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
701 final SchemaContext schemaContext, final QName qName) {
702 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
703 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
704 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
705 if (!strippedPathStatement.isAbsolute()) {
709 final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace()
710 ,qName.getRevision());
711 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
712 parentModule, strippedPathStatement);
713 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
714 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
715 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
718 return targetTypeDefinition;
721 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
724 * Removes conditions from xPath pointed to target node.
726 * @param pathStatement
727 * xPath to target node
728 * @return string representation of xPath without conditions
732 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
733 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
737 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
740 * a node representing LeafSchemaNode
741 * @return concrete type definition of node value
743 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
744 TypeDefinition<?> baseType = node.getType();
745 while (baseType.getBaseType() != null) {
746 baseType = baseType.getBaseType();
752 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
755 * a node representing LeafListSchemaNode
756 * @return concrete type definition of node value
758 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
759 TypeDefinition<?> baseType = node.getType();
760 while (baseType.getBaseType() != null) {
761 baseType = baseType.getBaseType();
767 * Gets the base type of DataSchemaNode value.
770 * a node representing DataSchemaNode
771 * @return concrete type definition of node value
773 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
774 if (node instanceof LeafListSchemaNode) {
775 return typeDefinition((LeafListSchemaNode) node);
776 } else if (node instanceof LeafSchemaNode) {
777 return typeDefinition((LeafSchemaNode) node);
779 throw new IllegalArgumentException("Unhandled parameter type: " + node);